qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
188,452
|
<p>Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object?
I know that I can:</p>
<pre><code>$file = fopen('c:\file.doc', 'w+');
fwrite($file, $text);
fclose();
</code></pre>
<p>but Word will read it as an HTML file not a native .doc file.</p>
|
[
{
"answer_id": 265017,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<?php\n\n\n\n/*****************************************************************\nThis approach uses detection of NUL (chr(00)) and end line (chr(13))\nto decide where the text is:\n- divide the file contents up by chr(13)\n- reject any slices containing a NUL\n- stitch the rest together again\n- clean up with a regular expression\n*****************************************************************/\n\nfunction parseWord($userDoc) \n{\n $fileHandle = fopen($userDoc, \"r\");\n $line = @fread($fileHandle, filesize($userDoc)); \n $lines = explode(chr(0x0D),$line);\n $outtext = \"\";\n foreach($lines as $thisline)\n {\n $pos = strpos($thisline, chr(0x00));\n if (($pos !== FALSE)||(strlen($thisline)==0))\n {\n } else {\n $outtext .= $thisline.\" \";\n }\n }\n $outtext = preg_replace(\"/[^a-zA-Z0-9\\s\\,\\.\\-\\n\\r\\t@\\/\\_\\(\\)]/\",\"\",$outtext);\n return $outtext;\n} \n\n$userDoc = \"cv.doc\";\n\n$text = parseWord($userDoc);\necho $text;\n\n\n?>\n"
},
{
"answer_id": 900581,
"author": "Mantichora",
"author_id": 79147,
"author_profile": "https://Stackoverflow.com/users/79147",
"pm_score": 3,
"selected": false,
"text": "$document_file = 'c:\\file.doc';\n$text_from_doc = shell_exec('/usr/local/bin/antiword '.$document_file);\n"
},
{
"answer_id": 5534093,
"author": "WIlson",
"author_id": 690471,
"author_profile": "https://Stackoverflow.com/users/690471",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n/*****************************************************************\nThis approach uses detection of NUL (chr(00)) and end line (chr(13))\nto decide where the text is:\n- divide the file contents up by chr(13)\n- reject any slices containing a NUL\n- stitch the rest together again\n- clean up with a regular expression\n*****************************************************************/\n\nfunction parseWord($userDoc) \n{\n $fileHandle = fopen($userDoc, \"r\");\n $word_text = @fread($fileHandle, filesize($userDoc));\n $line = \"\";\n $tam = filesize($userDoc);\n $nulos = 0;\n $caracteres = 0;\n for($i=1536; $i<$tam; $i++)\n {\n $line .= $word_text[$i];\n\n if( $word_text[$i] == 0)\n {\n $nulos++;\n }\n else\n {\n $nulos=0;\n $caracteres++;\n }\n\n if( $nulos>1996)\n { \n break; \n }\n }\n\n //echo $caracteres;\n\n $lines = explode(chr(0x0D),$line);\n //$outtext = \"<pre>\";\n\n $outtext = \"\";\n foreach($lines as $thisline)\n {\n $tam = strlen($thisline);\n if( !$tam )\n {\n continue;\n }\n\n $new_line = \"\"; \n for($i=0; $i<$tam; $i++)\n {\n $onechar = $thisline[$i];\n if( $onechar > chr(240) )\n {\n continue;\n }\n\n if( $onechar >= chr(0x20) )\n {\n $caracteres++;\n $new_line .= $onechar;\n }\n\n if( $onechar == chr(0x14) )\n {\n $new_line .= \"</a>\";\n }\n\n if( $onechar == chr(0x07) )\n {\n $new_line .= \"\\t\";\n if( isset($thisline[$i+1]) )\n {\n if( $thisline[$i+1] == chr(0x07) )\n {\n $new_line .= \"\\n\";\n }\n }\n }\n }\n //troca por hiperlink\n $new_line = str_replace(\"HYPERLINK\" ,\"<a href=\",$new_line); \n $new_line = str_replace(\"\\o\" ,\">\",$new_line); \n $new_line .= \"\\n\";\n\n //link de imagens\n $new_line = str_replace(\"INCLUDEPICTURE\" ,\"<br><img src=\",$new_line); \n $new_line = str_replace(\"\\*\" ,\"><br>\",$new_line); \n $new_line = str_replace(\"MERGEFORMATINET\" ,\"\",$new_line); \n\n\n $outtext .= nl2br($new_line);\n }\n\n return $outtext;\n} \n\n$userDoc = \"custo.doc\";\n$userDoc = \"Cultura.doc\";\n$text = parseWord($userDoc);\n\necho $text;\n\n\n?>\n"
},
{
"answer_id": 56868010,
"author": "Mohamed Faalil",
"author_id": 10422340,
"author_profile": "https://Stackoverflow.com/users/10422340",
"pm_score": 1,
"selected": false,
"text": "class DocxConversion{\n private $filename;\n\n public function __construct($filePath) {\n $this->filename = $filePath;\n }\n\n private function read_doc() {\n $fileHandle = fopen($this->filename, \"r\");\n $line = @fread($fileHandle, filesize($this->filename)); \n $lines = explode(chr(0x0D),$line);\n $outtext = \"\";\n foreach($lines as $thisline)\n {\n $pos = strpos($thisline, chr(0x00));\n if (($pos !== FALSE)||(strlen($thisline)==0))\n {\n } else {\n $outtext .= $thisline.\" \";\n }\n }\n $outtext = preg_replace(\"/[^a-zA-Z0-9\\s\\,\\.\\-\\n\\r\\t@\\/\\_\\(\\)]/\",\"\",$outtext);\n return $outtext;\n }\n\n private function read_docx(){\n\n $striped_content = '';\n $content = '';\n\n $zip = zip_open($this->filename);\n\n if (!$zip || is_numeric($zip)) return false;\n\n while ($zip_entry = zip_read($zip)) {\n\n if (zip_entry_open($zip, $zip_entry) == FALSE) continue;\n\n if (zip_entry_name($zip_entry) != \"word/document.xml\") continue;\n\n $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));\n\n zip_entry_close($zip_entry);\n }// end while\n\n zip_close($zip);\n\n $content = str_replace('</w:r></w:p></w:tc><w:tc>', \" \", $content);\n $content = str_replace('</w:r></w:p>', \"\\r\\n\", $content);\n $striped_content = strip_tags($content);\n\n return $striped_content;\n }\n\n /************************excel sheet************************************/\n\nfunction xlsx_to_text($input_file){\n $xml_filename = \"xl/sharedStrings.xml\"; //content file name\n $zip_handle = new ZipArchive;\n $output_text = \"\";\n if(true === $zip_handle->open($input_file)){\n if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){\n $xml_datas = $zip_handle->getFromIndex($xml_index);\n $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);\n $output_text = strip_tags($xml_handle->saveXML());\n }else{\n $output_text .=\"\";\n }\n $zip_handle->close();\n }else{\n $output_text .=\"\";\n }\n return $output_text;\n}\n\n/*************************power point files*****************************/\nfunction pptx_to_text($input_file){\n $zip_handle = new ZipArchive;\n $output_text = \"\";\n if(true === $zip_handle->open($input_file)){\n $slide_number = 1; //loop through slide files\n while(($xml_index = $zip_handle->locateName(\"ppt/slides/slide\".$slide_number.\".xml\")) !== false){\n $xml_datas = $zip_handle->getFromIndex($xml_index);\n $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);\n $output_text .= strip_tags($xml_handle->saveXML());\n $slide_number++;\n }\n if($slide_number == 1){\n $output_text .=\"\";\n }\n $zip_handle->close();\n }else{\n $output_text .=\"\";\n }\n return $output_text;\n}\n\n\n public function convertToText() {\n\n if(isset($this->filename) && !file_exists($this->filename)) {\n return \"File Not exists\";\n }\n\n $fileArray = pathinfo($this->filename);\n $file_ext = $fileArray['extension'];\n if($file_ext == \"doc\" || $file_ext == \"docx\" || $file_ext == \"xlsx\" || $file_ext == \"pptx\")\n {\n if($file_ext == \"doc\") {\n return $this->read_doc();\n } elseif($file_ext == \"docx\") {\n return $this->read_docx();\n } elseif($file_ext == \"xlsx\") {\n return $this->xlsx_to_text();\n }elseif($file_ext == \"pptx\") {\n return $this->pptx_to_text();\n }\n } else {\n return \"Invalid File Type\";\n }\n }\n\n}\n\n$docObj = new DocxConversion(\"test.docx\"); //replace your document name with correct extension doc or docx \necho $docText= $docObj->convertToText();\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
188,461
|
<p>For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through.</p>
<p>Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands?</p>
<p><strong>Edit:</strong>
I wasn't specific enough to what I meant by fall-through. I use this type a lot:</p>
<pre class="lang-js prettyprint-override"><code> switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something
break;
case 2:
case 3:
case 4:
// Do something
break;
}
</code></pre>
<p>However, I'm concerned about something like this.</p>
<pre class="lang-js prettyprint-override"><code> switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something, but fall through to the other cases
// after doing it.
case 2:
case 3:
case 4:
// Do something else.
break;
}
</code></pre>
<p>This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is very useful and safe. The second seems kind of dangerous.</p>
|
[
{
"answer_id": 188477,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 5,
"selected": false,
"text": "switch ($someoption) {\n case 'a':\n case 'b':\n case 'c':\n // Do something\n break;\n\n case 'd':\n case 'e':\n // Do something else\n break;\n}\n"
},
{
"answer_id": 188481,
"author": "Dan Hulton",
"author_id": 8327,
"author_profile": "https://Stackoverflow.com/users/8327",
"pm_score": 3,
"selected": false,
"text": "switch($var) {\n case 'first':\n // Fall-through\n case 'second':\n i++;\n break;\n }\n"
},
{
"answer_id": 188492,
"author": "steffenj",
"author_id": 15328,
"author_profile": "https://Stackoverflow.com/users/15328",
"pm_score": 3,
"selected": false,
"text": "switch (x)\n{\ncase 1:\ncase 2:\ncase 3:\n Do something\n break;\n}\n switch (x)\n{\ncase 1:\n Some code\ncase 2:\n Some more code\ncase 3:\n Even more code\n break;\n}\n"
},
{
"answer_id": 188493,
"author": "John M",
"author_id": 20734,
"author_profile": "https://Stackoverflow.com/users/20734",
"pm_score": 6,
"selected": false,
"text": "switch (c) {\n case 1:\n case 2:\n ... Do some of the work ...\n /* FALLTHROUGH */\n case 17:\n ... Do something ...\n break;\n case 5:\n case 43:\n ... Do something else ...\n break;\n}\n"
},
{
"answer_id": 188498,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "switch case"
},
{
"answer_id": 188506,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 8,
"selected": true,
"text": "switch (value)\n{\n case 0:\n result = ZERO_DIGIT;\n break;\n\n case 1:\n case 3:\n case 5:\n case 7:\n case 9:\n result = ODD_DIGIT;\n break;\n\n case 2:\n case 4:\n case 6:\n case 8:\n result = EVEN_DIGIT;\n break;\n}\n"
},
{
"answer_id": 188848,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "switch (version) {\n case 1:\n // Update some stuff\n case 2:\n // Update more stuff\n case 3:\n // Update even more stuff\n case 4:\n // And so on\n}\n"
},
{
"answer_id": 530616,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 3,
"selected": false,
"text": "switch(myParam)\n{\n case 0 or 1 or 2:\n // Do something;\n break;\n case 3 or 4:\n // Do something else;\n break;\n}\n int value = 10;\nvalue.Switch()\n .Case(() => { /* Do something; */ }, new {0, 1, 2})\n .Case(() => { /* Do something else */ } new {3, 4})\n .Default(() => { /* Do the default case; */ });\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16524/"
] |
188,473
|
<p>I have a C# object with a critical resource that needs to be flushed very specific points in time making it a bad candidate to leave around for the garbage collector to take care of whenever it gets around to it, how should I handle this? Is there something like C++'s delete operator that will let me manually kill the instance of this object when needed?</p>
|
[
{
"answer_id": 188501,
"author": "David",
"author_id": 26144,
"author_profile": "https://Stackoverflow.com/users/26144",
"pm_score": 2,
"selected": false,
"text": "IDiposable Dispose()"
},
{
"answer_id": 188575,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 5,
"selected": false,
"text": "IDisposable class MyDisposableObject : IDisposable\n{\n public MyDisposableObject()\n {\n }\n\n ~MyDisposableObject()\n {\n Dispose(false);\n }\n\n private bool disposed;\n private void Dispose(bool disposing)\n {\n if (!this.disposed)\n {\n if (disposing)\n {\n // Dispose of your managed resources here.\n }\n\n // Dispose of your unmanaged resources here.\n\n this.disposed = true;\n }\n }\n\n void IDisposable.Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n}\n public void DoingMyThing()\n{\n using (MyDisposableObject obj = new MyDisposableObject())\n {\n // Use obj here.\n }\n}\n using Dispose() IDisposable"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
188,476
|
<p>Does anyone know of a simple way to compare two strings together to generate the "amount of difference" between the two? (in a numeric value) I have been crawling google with little luck on this. And after doing some coding it's not as simple as I had thought. Any clues?</p>
|
[
{
"answer_id": 188499,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "strcmp()"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] |
188,488
|
<p>The problem is following: I want to automate the way my emacs starts.
It has to be split in two buffers and the slime-repl has to be started in the smallest (bottom) buffer. Plus, I want my file to be opened in the bigger (upper) buffer.
In my .emacs there are lines:</p>
<pre><code>(slime)
...
(split-window-vertically -6)
(switch-to-buffer (other-buffer))
(find-file "g:/Private/pa/pa2.lsp")
</code></pre>
<p>SLIME opens o.k. in the bottom buffer, but the file is opened in one of the background buffers, while I want it to be in front.</p>
<p>How to fix this?</p>
|
[
{
"answer_id": 188641,
"author": "EfForEffort",
"author_id": 14113,
"author_profile": "https://Stackoverflow.com/users/14113",
"pm_score": 0,
"selected": false,
"text": "(other-window 1)\n(find-file \"g:/Private/pa/pa2.lsp\")\n"
},
{
"answer_id": 906559,
"author": "viam0Zah",
"author_id": 73603,
"author_profile": "https://Stackoverflow.com/users/73603",
"pm_score": 2,
"selected": true,
"text": "switch-to-buffer pop-to-buffer (pop-to-buffer BUFFER-OR-NAME &optional OTHER-WINDOW NORECORD) BUFFER-OR-NAME"
},
{
"answer_id": 1655455,
"author": "Łukasz Lew",
"author_id": 61342,
"author_profile": "https://Stackoverflow.com/users/61342",
"pm_score": 0,
"selected": false,
"text": "(ido-mode 1)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514/"
] |
188,503
|
<p>How do you detect the number of physical processors/cores in .net?</p>
|
[
{
"answer_id": 188526,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 6,
"selected": true,
"text": "System.Environment.ProcessorCount\n Environment.ProcessorCount <configuration>\n <runtime>\n <Thread_UseAllCpuGroups enabled=\"true\"/>\n <GCCpuGroup enabled=\"true\"/>\n <gcServer enabled=\"true\"/>\n </runtime>\n</configuration>\n"
},
{
"answer_id": 189371,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": false,
"text": "Environment.ProcessorCount using System;\nusing System.Diagnostics;\n\n/// <summary>\n/// Provides a single property which gets the number of processor threads\n/// available to the currently executing process.\n/// </summary>\ninternal static class ProcessInfo\n{\n /// <summary>\n /// Gets the number of processors.\n /// </summary>\n /// <value>The number of processors.</value>\n internal static uint NumberOfProcessorThreads\n {\n get\n {\n uint processAffinityMask;\n\n using (var currentProcess = Process.GetCurrentProcess())\n {\n processAffinityMask = (uint)currentProcess.ProcessorAffinity;\n }\n\n const uint BitsPerByte = 8;\n var loop = BitsPerByte * sizeof(uint);\n uint result = 0;\n\n while (--loop > 0)\n {\n result += processAffinityMask & 1;\n processAffinityMask >>= 1;\n }\n\n return (result == 0) ? 1 : result;\n }\n }\n}\n"
},
{
"answer_id": 20097109,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 1,
"selected": false,
"text": "Get-WmiObject -namespace root\\CIMV2 -class Win32_Processor -Property NumberOfCores\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952/"
] |
188,510
|
<p>I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.</p>
<p>I was thinking:</p>
<pre><code>String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
</code></pre>
<p>but that does not seem to do the trick.</p>
<p>** UPDATE **</p>
<p>Ok. I went with this solution</p>
<pre><code>Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
</code></pre>
<p>Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so</p>
<pre><code>1112224444 333 becomes
11-221-244 3334
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 188543,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 5,
"selected": false,
"text": "string.Format(\"({0}) {1}-{2}\",\n phoneNumber.Substring(0, 3),\n phoneNumber.Substring(3, 3),\n phoneNumber.Substring(6));\n"
},
{
"answer_id": 188544,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "string phone = i[\"MyPhone\"].ToString();\nstring area = phone.Substring(0, 3);\nstring major = phone.Substring(3, 3);\nstring minor = phone.Substring(6);\nstring formatted = string.Format(\"{0}-{1}-{2}\", area, major, minor);\n"
},
{
"answer_id": 188551,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "i[\"MyPhone\"] long long.ToString() Convert.ToLong(i[\"MyPhone\"]).ToString(\"###-###-####\");\n"
},
{
"answer_id": 188607,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 8,
"selected": false,
"text": "Regex.Replace(\"1112224444\", @\"(\\d{3})(\\d{3})(\\d{4})\", \"$1-$2-$3\");\n"
},
{
"answer_id": 188616,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 8,
"selected": false,
"text": "String.Format(\"{0:(###) ###-####}\", 8005551212);\n\n This will output \"(800) 555-1212\".\n"
},
{
"answer_id": 302889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Regex regex = new Regex(@\"(?<first3chr>\\d{3})(?<next3chr>\\d{3})(?<next4chr>\\d{4})\");\nMatch match = regex.Match(phone);\nif (match.Success) return \"(\" + match.Groups[\"first3chr\"].ToString() + \")\" + \" \" + \n match.Groups[\"next3chr\"].ToString() + \"-\" + match.Groups[\"next4chr\"].ToString();\n"
},
{
"answer_id": 1428591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Function FormatPhoneNumber(ByVal myNumber As String)\n Dim mynewNumber As String\n mynewNumber = \"\"\n myNumber = myNumber.Replace(\"(\", \"\").Replace(\")\", \"\").Replace(\"-\", \"\")\n If myNumber.Length < 10 Then\n mynewNumber = myNumber\n ElseIf myNumber.Length = 10 Then\n mynewNumber = \"(\" & myNumber.Substring(0, 3) & \") \" &\n myNumber.Substring(3, 3) & \"-\" & myNumber.Substring(6, 3)\n ElseIf myNumber.Length > 10 Then\n mynewNumber = \"(\" & myNumber.Substring(0, 3) & \") \" &\n myNumber.Substring(3, 3) & \"-\" & myNumber.Substring(6, 3) & \" \" &\n myNumber.Substring(10)\n End If\n Return mynewNumber\nEnd Function\n"
},
{
"answer_id": 3709252,
"author": "Mak",
"author_id": 447391,
"author_profile": "https://Stackoverflow.com/users/447391",
"pm_score": 1,
"selected": false,
"text": "public string phoneformat(string phnumber)\n{\nString phone=phnumber;\nstring countrycode = phone.Substring(0, 3); \nstring Areacode = phone.Substring(3, 3); \nstring number = phone.Substring(6,phone.Length); \n\nphnumber=\"(\"+countrycode+\")\" +Areacode+\"-\" +number ;\n\nreturn phnumber;\n}\n"
},
{
"answer_id": 3791026,
"author": "Larry Smithmier",
"author_id": 4911,
"author_profile": "https://Stackoverflow.com/users/4911",
"pm_score": 0,
"selected": false,
"text": "string formatString = \"###-###-#### ####\";\nreturnValue = Convert.ToInt64(phoneNumber)\n .ToString(formatString.Substring(0,phoneNumber.Length+3))\n .Trim();\n"
},
{
"answer_id": 3867716,
"author": "Vivek Shenoy",
"author_id": 467315,
"author_profile": "https://Stackoverflow.com/users/467315",
"pm_score": 4,
"selected": false,
"text": "String.Format(\"{0:(###)###-####}\", Convert.ToInt64(\"1112224444\"));\n String.Format(\"{0:###-###-####}\", Convert.ToInt64(\"1112224444\"));\n"
},
{
"answer_id": 7952302,
"author": "Humberto Moreno",
"author_id": 1021759,
"author_profile": "https://Stackoverflow.com/users/1021759",
"pm_score": 2,
"selected": false,
"text": "string result;\nif ( (!string.IsNullOrEmpty(phoneNumber)) && (phoneNumber.Length >= 10 ) )\n result = string.Format(\"{0:(###)###-\"+new string('#',phoneNumber.Length-6)+\"}\",\n Convert.ToInt64(phoneNumber)\n );\nelse\n result = phoneNumber;\nreturn result;\n"
},
{
"answer_id": 8403040,
"author": "Jerry Nixon",
"author_id": 265706,
"author_profile": "https://Stackoverflow.com/users/265706",
"pm_score": 5,
"selected": false,
"text": "public static string PhoneNumber(string value)\n{ \n if (string.IsNullOrEmpty(value)) return string.Empty;\n value = new System.Text.RegularExpressions.Regex(@\"\\D\")\n .Replace(value, string.Empty);\n value = value.TrimStart('1');\n if (value.Length == 7)\n return Convert.ToInt64(value).ToString(\"###-####\");\n if (value.Length == 10)\n return Convert.ToInt64(value).ToString(\"###-###-####\");\n if (value.Length > 10)\n return Convert.ToInt64(value)\n .ToString(\"###-###-#### \" + new String('#', (value.Length - 10)));\n return value;\n}\n"
},
{
"answer_id": 22539701,
"author": "underscore",
"author_id": 539698,
"author_profile": "https://Stackoverflow.com/users/539698",
"pm_score": 3,
"selected": false,
"text": "static string FormatPhoneNumber( string phoneNumber ) {\n\n if ( String.IsNullOrEmpty(phoneNumber) )\n return phoneNumber;\n\n Regex phoneParser = null;\n string format = \"\";\n\n switch( phoneNumber.Length ) {\n\n case 5 :\n phoneParser = new Regex(@\"(\\d{3})(\\d{2})\");\n format = \"$1 $2\";\n break;\n\n case 6 :\n phoneParser = new Regex(@\"(\\d{2})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3\";\n break;\n\n case 7 :\n phoneParser = new Regex(@\"(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3\";\n break;\n\n case 8 :\n phoneParser = new Regex(@\"(\\d{4})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3\";\n break;\n\n case 9 :\n phoneParser = new Regex(@\"(\\d{4})(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3 $4\";\n break;\n\n case 10 :\n phoneParser = new Regex(@\"(\\d{3})(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3 $4\";\n break;\n\n case 11 :\n phoneParser = new Regex(@\"(\\d{4})(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3 $4\";\n break;\n\n default:\n return phoneNumber;\n\n }//switch\n\n return phoneParser.Replace( phoneNumber, format );\n\n}//FormatPhoneNumber\n\n enter code here\n"
},
{
"answer_id": 30271625,
"author": "Kent Cooper",
"author_id": 2725843,
"author_profile": "https://Stackoverflow.com/users/2725843",
"pm_score": 0,
"selected": false,
"text": "string.Format long using System;\nusing System.Globalization;\nusing System.Text;\n\nnamespace System\n{\n /// <summary>\n /// A formatter that will apply a format to a string of numeric values.\n /// </summary>\n /// <example>\n /// The following example converts a string of numbers and inserts dashes between them.\n /// <code>\n /// public class Example\n /// {\n /// public static void Main()\n /// { \n /// string stringValue = \"123456789\";\n /// \n /// Console.WriteLine(String.Format(new NumericStringFormatter(),\n /// \"{0} (formatted: {0:###-##-####})\",stringValue));\n /// }\n /// }\n /// // The example displays the following output:\n /// // 123456789 (formatted: 123-45-6789)\n /// </code>\n /// </example>\n public class NumericStringFormatter : IFormatProvider, ICustomFormatter\n {\n /// <summary>\n /// Converts the value of a specified object to an equivalent string representation using specified format and\n /// culture-specific formatting information.\n /// </summary>\n /// <param name=\"format\">A format string containing formatting specifications.</param>\n /// <param name=\"arg\">An object to format.</param>\n /// <param name=\"formatProvider\">An object that supplies format information about the current instance.</param>\n /// <returns>\n /// The string representation of the value of <paramref name=\"arg\" />, formatted as specified by\n /// <paramref name=\"format\" /> and <paramref name=\"formatProvider\" />.\n /// </returns>\n /// <exception cref=\"System.NotImplementedException\"></exception>\n public string Format(string format, object arg, IFormatProvider formatProvider)\n {\n var strArg = arg as string;\n\n // If the arg is not a string then determine if it can be handled by another formatter\n if (strArg == null)\n {\n try\n {\n return HandleOtherFormats(format, arg);\n }\n catch (FormatException e)\n {\n throw new FormatException(string.Format(\"The format of '{0}' is invalid.\", format), e);\n }\n }\n\n // If the format is not set then determine if it can be handled by another formatter\n if (string.IsNullOrEmpty(format))\n {\n try\n {\n return HandleOtherFormats(format, arg);\n }\n catch (FormatException e)\n {\n throw new FormatException(string.Format(\"The format of '{0}' is invalid.\", format), e);\n }\n }\n var sb = new StringBuilder();\n var i = 0;\n\n foreach (var c in format)\n {\n if (c == '#')\n {\n if (i < strArg.Length)\n {\n sb.Append(strArg[i]);\n }\n i++;\n }\n else\n {\n sb.Append(c);\n }\n }\n\n return sb.ToString();\n }\n\n /// <summary>\n /// Returns an object that provides formatting services for the specified type.\n /// </summary>\n /// <param name=\"formatType\">An object that specifies the type of format object to return.</param>\n /// <returns>\n /// An instance of the object specified by <paramref name=\"formatType\" />, if the\n /// <see cref=\"T:System.IFormatProvider\" /> implementation can supply that type of object; otherwise, null.\n /// </returns>\n public object GetFormat(Type formatType)\n {\n // Determine whether custom formatting object is requested. \n return formatType == typeof(ICustomFormatter) ? this : null;\n }\n\n private string HandleOtherFormats(string format, object arg)\n {\n if (arg is IFormattable)\n return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);\n else if (arg != null)\n return arg.ToString();\n else\n return string.Empty;\n }\n }\n}\n String.Format(new NumericStringFormatter(),\"{0:###-###-####}\", i[\"MyPhone\"].ToString());\n String.Format(new NumericStringFormatter(),\"{0:###-###-####}\", \"12345\");"
},
{
"answer_id": 34273619,
"author": "Rama Krshna Ila",
"author_id": 5498737,
"author_profile": "https://Stackoverflow.com/users/5498737",
"pm_score": 2,
"selected": false,
"text": "string primaryContactNumber = !string.IsNullOrEmpty(formData.Profile.Phone) ? String.Format(\"{0:###-###-####}\", long.Parse(formData.Profile.Phone)) : \"\";\n"
},
{
"answer_id": 36166198,
"author": "James Copeland",
"author_id": 4897761,
"author_profile": "https://Stackoverflow.com/users/4897761",
"pm_score": 3,
"selected": false,
"text": "String.Format public static string PhoneNumberFormatter(this string value)\n{\n value = new Regex(@\"\\D\").Replace(value, string.Empty);\n value = value.TrimStart('1');\n\n if (value.Length == 0)\n value = string.Empty;\n else if (value.Length < 3)\n value = string.Format(\"({0})\", value.Substring(0, value.Length));\n else if (value.Length < 7)\n value = string.Format(\"({0}) {1}\", value.Substring(0, 3), value.Substring(3, value.Length - 3));\n else if (value.Length < 11)\n value = string.Format(\"({0}) {1}-{2}\", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));\n else if (value.Length > 10)\n {\n value = value.Remove(value.Length - 1, 1);\n value = string.Format(\"({0}) {1}-{2}\", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));\n }\n return value;\n}\n"
},
{
"answer_id": 45587547,
"author": "Mohammad Atiour Islam",
"author_id": 1077346,
"author_profile": "https://Stackoverflow.com/users/1077346",
"pm_score": 2,
"selected": false,
"text": " public string GetFormattedPhoneNumber(string phone)\n {\n if (phone != null && phone.Trim().Length == 10)\n return string.Format(\"({0}) {1}-{2}\", phone.Substring(0, 3), phone.Substring(3, 3), phone.Substring(6, 4));\n return phone;\n }\n"
},
{
"answer_id": 47658381,
"author": "Victor Johnson",
"author_id": 9057363,
"author_profile": "https://Stackoverflow.com/users/9057363",
"pm_score": 3,
"selected": false,
"text": "string formattedPhoneNumber = new System.Text.RegularExpressions.Regex(@\"\\D\")\n .Replace(originalPhoneNumber, string.Empty);\n formattedPhoneNumber = Convert.ToInt64(formattedPhoneNumber)\n .ToString(\"###-###-#### \" + new String('#', (value.Length - 10)));\n formattedPhoneNumber = Convert.ToInt64(value).ToString(\"###-###-####\");\n"
},
{
"answer_id": 50338647,
"author": "Mohammed Hossen",
"author_id": 9790698,
"author_profile": "https://Stackoverflow.com/users/9790698",
"pm_score": 1,
"selected": false,
"text": "private string FormatPhoneNumber(string phoneNum)\n{\n string phoneFormat = \"(###) ###-#### x####\";\n\n Regex regexObj = new Regex(@\"[^\\d]\");\n phoneNum = regexObj.Replace(phoneNum, \"\");\n if (phoneNum.Length > 0)\n {\n phoneNum = Convert.ToInt64(phoneNum).ToString(phoneFormat);\n }\n return phoneNum;\n}\n FormatPhoneNumber(string phoneNum)\n private string PhoneFormat(string phoneNum)\n {\n int max = 15, min = 10;\n string areaCode = phoneNum.Substring(0, 3);\n string mid = phoneNum.Substring(3, 3);\n string lastFour = phoneNum.Substring(6, 4);\n string extension = phoneNum.Substring(10, phoneNum.Length - min);\n if (phoneNum.Length == min)\n {\n return $\"({areaCode}) {mid}-{lastFour}\";\n }\n else if (phoneNum.Length > min && phoneNum.Length <= max)\n {\n return $\"({areaCode}) {mid}-{lastFour} x{extension}\";\n }\n return phoneNum;\n }\n"
},
{
"answer_id": 59109558,
"author": "Neil Garcia",
"author_id": 2030079,
"author_profile": "https://Stackoverflow.com/users/2030079",
"pm_score": 1,
"selected": false,
"text": "public string formatPhoneNumber(string _phoneNum)\n{\n string phoneNum = _phoneNum;\n if (phoneNum == null)\n phoneNum = \"\";\n phoneNum = phoneNum.PadRight(10 - phoneNum.Length);\n phoneNum = phoneNum.Insert(0, \"(\").Insert(4,\") \").Insert(9,\"-\");\n return phoneNum;\n}\n"
},
{
"answer_id": 61264621,
"author": "nirav gandhi",
"author_id": 6580613,
"author_profile": "https://Stackoverflow.com/users/6580613",
"pm_score": 2,
"selected": false,
"text": " string phoneNum;\n string phoneFormat = \"0#-###-###-####\";\n phoneNum = Convert.ToInt64(\"011234567891\").ToString(phoneFormat);\n"
},
{
"answer_id": 63252501,
"author": "Leoabarca",
"author_id": 12274857,
"author_profile": "https://Stackoverflow.com/users/12274857",
"pm_score": 0,
"selected": false,
"text": " Label12.Text = Convert.ToInt64(reader[6]).ToString(\"(###) ###-#### \");\n"
},
{
"answer_id": 65500642,
"author": "Fred Spataro",
"author_id": 14910402,
"author_profile": "https://Stackoverflow.com/users/14910402",
"pm_score": 2,
"selected": false,
"text": "var p = \"1234567890\";\nvar formatted = $\"({p[0..3]}) {p[3..6]}-{p[6..10]}\"\n"
},
{
"answer_id": 67878347,
"author": "revobtz",
"author_id": 3554970,
"author_profile": "https://Stackoverflow.com/users/3554970",
"pm_score": -1,
"selected": false,
"text": "public static string ToTelephoneNumberFormat(this string value, string format = \"({0}) {1}-{2}\") {\n if (string.IsNullOrWhiteSpace(value)) \n {\n return value;\n } \n else \n {\n string area = value.Substring(0, 3) ?? \"\";\n string major = value.Substring(3, 3) ?? \"\";\n string minor = value.Substring(6) ?? \"\";\n return string.Format(format, area, major, minor);\n }\n}\n"
},
{
"answer_id": 69243648,
"author": "KuroCoder",
"author_id": 14114788,
"author_profile": "https://Stackoverflow.com/users/14114788",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n {\n Regex phonenumber = new(@\"([0-9]{11})$\");\n Console.WriteLine(\"Enter a Number: \");\n var number = Console.ReadLine();\n if(number.Length == 11)\n {\n if (phonenumber.IsMatch(number))\n {\n Console.WriteLine(\"Your Number is: \"+number);\n }\n else\n Console.WriteLine(\"Nooob...\");\n }\n else\n Console.WriteLine(\"Nooob...\");\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
188,532
|
<p>I want to make sure that a set of functions have the same signature in some C code. Ideally I would be able to define a new type that described the return value and arguments of a function and then declare my set of functions using this new type. </p>
<p>Additionally, is there a way to specify default values for the arguments to this function typedef?</p>
|
[
{
"answer_id": 188559,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": true,
"text": "/* define a typedef for function_t - functions that return void */\n/* and take an int and char parameter */\n\ntypedef void function_t( int param1, char param2);\n\n/* declare some functions that use that signature */\n\nfunction_t foo;\nfunction_t bar;\n void foo( int x, char c)\n{\n /* do some stuff */\n\n return;\n}\n\n/* this will result in a compiler error */\nint bar( int x, char c)\n{\n /* do some stuff */\n\n return 1;\n}\n"
},
{
"answer_id": 188567,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 0,
"selected": false,
"text": " // Declaration of function with int arg returning int\n typedef int (*CALLBACK)(int);\n\n //Definition\n int myFunc(int arg)\n {\n return 0;\n }\n\n // Function pointer usage\n CALLBACK pFunc = myFunc;\n"
},
{
"answer_id": 188572,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "typedef void (*MethodSig)(int, int);\n\nstatic MethodSig x[] = { fnA, fnB, ... };\n #define MyFunc(X) void X(int a, int b)\n"
},
{
"answer_id": 188595,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "typedef unsigned short (*id_for_allowed_functions)(int, char*);\n void calling_function (id_for_allowed_function x) { (*x)(3, \"bla\"); }\n unsigned short foo(int x, char* y) { /* ... */ }\ncalling_function(&foo);\n"
},
{
"answer_id": 7739336,
"author": "Henry Rusted",
"author_id": 989271,
"author_profile": "https://Stackoverflow.com/users/989271",
"pm_score": 0,
"selected": false,
"text": "typedef GenList *(*DBLISTLOADER)(Database *pDB, char *quellCD, char *profilName);\ntypedef ObjDescription *(*DBCOLUMNLOADER)();\n\ntypedef struct dbinfo\n{\n char *dbName;\n DBLISTLOADER dbListLoader;\n DBCOLUMNLOADER dbColumnLoader;\n char *options;\n} DBINFO;\n DBINFO dbInfoList[] =\n{\n { \"SRCDOC\", loadSRCDOC, colSRCDOC, \"q\" },\n { \"PRF_CD\", loadPRF_CD, colPRF_CD, \"\" },\n { \"MEDIA\", loadMEDIA, colMEDIA, \"\" },\n\n { NULL, NULL, NULL }\n};\n while (dbInfoList[i].dbName != NULL)\n{\n if (strcmp(dbInfoList[i].dbName, szDatabase) == 0)\n {\n return (dbInfoList[i].dbListLoader)(pDB, quellCD, profilName);\n }\n\n i++;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26551/"
] |
188,545
|
<p>I was looking for a way to remove text from and RTF string and I found the following regex:</p>
<pre><code>({\\)(.+?)(})|(\\)(.+?)(\b)
</code></pre>
<p>However the resulting string has two right angle brackets "}"</p>
<p><strong>Before:</strong> <code>{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}{\f1\fnil MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 can u send me info for the call pls\f1\par }</code></p>
<p><strong>After:</strong> <code>} can u send me info for the call pls }</code></p>
<p>Any thoughts on how to improve the regex?</p>
<p><strong>Edit:</strong> A more complicated string such as this one does not work: <code>{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\test\\myapp\\Apps\\\{3423234-283B-43d2-BCE6-A324B84CC70E\}\par }</code></p>
|
[
{
"answer_id": 188667,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "({\\\\)(.+?)(}+)|(\\\\)(.+?)(\\b)\n ^\n plus sign added here\n ({\\\\)(.+?)(})|(\\\\)(.+?)(\\b)|}$\n ^\n this checks if there is a curly brace at the end\n"
},
{
"answer_id": 188725,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 3,
"selected": false,
"text": "\\\\\\w+|\\{.*?\\}|}\n"
},
{
"answer_id": 188877,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 6,
"selected": false,
"text": "\\{\\*?\\\\[^{}]+}|[{}]|\\\\\\n?[A-Za-z]+\\n?(?:-?\\d+)?[ ]?\n def striprtf(text):\n pattern = re.compile(r\"\\\\([a-z]{1,32})(-?\\d{1,10})?[ ]?|\\\\'([0-9a-f]{2})|\\\\([^a-z])|([{}])|[\\r\\n]+|(.)\", re.I)\n # control words which specify a \"destionation\".\n destinations = frozenset((\n 'aftncn','aftnsep','aftnsepc','annotation','atnauthor','atndate','atnicn','atnid',\n 'atnparent','atnref','atntime','atrfend','atrfstart','author','background',\n 'bkmkend','bkmkstart','blipuid','buptim','category','colorschememapping',\n 'colortbl','comment','company','creatim','datafield','datastore','defchp','defpap',\n 'do','doccomm','docvar','dptxbxtext','ebcend','ebcstart','factoidname','falt',\n 'fchars','ffdeftext','ffentrymcr','ffexitmcr','ffformat','ffhelptext','ffl',\n 'ffname','ffstattext','field','file','filetbl','fldinst','fldrslt','fldtype',\n 'fname','fontemb','fontfile','fonttbl','footer','footerf','footerl','footerr',\n 'footnote','formfield','ftncn','ftnsep','ftnsepc','g','generator','gridtbl',\n 'header','headerf','headerl','headerr','hl','hlfr','hlinkbase','hlloc','hlsrc',\n 'hsv','htmltag','info','keycode','keywords','latentstyles','lchars','levelnumbers',\n 'leveltext','lfolevel','linkval','list','listlevel','listname','listoverride',\n 'listoverridetable','listpicture','liststylename','listtable','listtext',\n 'lsdlockedexcept','macc','maccPr','mailmerge','maln','malnScr','manager','margPr',\n 'mbar','mbarPr','mbaseJc','mbegChr','mborderBox','mborderBoxPr','mbox','mboxPr',\n 'mchr','mcount','mctrlPr','md','mdeg','mdegHide','mden','mdiff','mdPr','me',\n 'mendChr','meqArr','meqArrPr','mf','mfName','mfPr','mfunc','mfuncPr','mgroupChr',\n 'mgroupChrPr','mgrow','mhideBot','mhideLeft','mhideRight','mhideTop','mhtmltag',\n 'mlim','mlimloc','mlimlow','mlimlowPr','mlimupp','mlimuppPr','mm','mmaddfieldname',\n 'mmath','mmathPict','mmathPr','mmaxdist','mmc','mmcJc','mmconnectstr',\n 'mmconnectstrdata','mmcPr','mmcs','mmdatasource','mmheadersource','mmmailsubject',\n 'mmodso','mmodsofilter','mmodsofldmpdata','mmodsomappedname','mmodsoname',\n 'mmodsorecipdata','mmodsosort','mmodsosrc','mmodsotable','mmodsoudl',\n 'mmodsoudldata','mmodsouniquetag','mmPr','mmquery','mmr','mnary','mnaryPr',\n 'mnoBreak','mnum','mobjDist','moMath','moMathPara','moMathParaPr','mopEmu',\n 'mphant','mphantPr','mplcHide','mpos','mr','mrad','mradPr','mrPr','msepChr',\n 'mshow','mshp','msPre','msPrePr','msSub','msSubPr','msSubSup','msSubSupPr','msSup',\n 'msSupPr','mstrikeBLTR','mstrikeH','mstrikeTLBR','mstrikeV','msub','msubHide',\n 'msup','msupHide','mtransp','mtype','mvertJc','mvfmf','mvfml','mvtof','mvtol',\n 'mzeroAsc','mzeroDesc','mzeroWid','nesttableprops','nextfile','nonesttables',\n 'objalias','objclass','objdata','object','objname','objsect','objtime','oldcprops',\n 'oldpprops','oldsprops','oldtprops','oleclsid','operator','panose','password',\n 'passwordhash','pgp','pgptbl','picprop','pict','pn','pnseclvl','pntext','pntxta',\n 'pntxtb','printim','private','propname','protend','protstart','protusertbl','pxe',\n 'result','revtbl','revtim','rsidtbl','rxe','shp','shpgrp','shpinst',\n 'shppict','shprslt','shptxt','sn','sp','staticval','stylesheet','subject','sv',\n 'svb','tc','template','themedata','title','txe','ud','upr','userprops',\n 'wgrffmtfilter','windowcaption','writereservation','writereservhash','xe','xform',\n 'xmlattrname','xmlattrvalue','xmlclose','xmlname','xmlnstbl',\n 'xmlopen',\n ))\n # Translation of some special characters.\n specialchars = {\n 'par': '\\n',\n 'sect': '\\n\\n',\n 'page': '\\n\\n',\n 'line': '\\n',\n 'tab': '\\t',\n 'emdash': u'\\u2014',\n 'endash': u'\\u2013',\n 'emspace': u'\\u2003',\n 'enspace': u'\\u2002',\n 'qmspace': u'\\u2005',\n 'bullet': u'\\u2022',\n 'lquote': u'\\u2018',\n 'rquote': u'\\u2019',\n 'ldblquote': u'\\201C',\n 'rdblquote': u'\\u201D', \n }\n stack = []\n ignorable = False # Whether this group (and all inside it) are \"ignorable\".\n ucskip = 1 # Number of ASCII characters to skip after a unicode character.\n curskip = 0 # Number of ASCII characters left to skip\n out = [] # Output buffer.\n for match in pattern.finditer(text):\n word,arg,hex,char,brace,tchar = match.groups()\n if brace:\n curskip = 0\n if brace == '{':\n # Push state\n stack.append((ucskip,ignorable))\n elif brace == '}':\n # Pop state\n ucskip,ignorable = stack.pop()\n elif char: # \\x (not a letter)\n curskip = 0\n if char == '~':\n if not ignorable:\n out.append(u'\\xA0')\n elif char in '{}\\\\':\n if not ignorable:\n out.append(char)\n elif char == '*':\n ignorable = True\n elif word: # \\foo\n curskip = 0\n if word in destinations:\n ignorable = True\n elif ignorable:\n pass\n elif word in specialchars:\n out.append(specialchars[word])\n elif word == 'uc':\n ucskip = int(arg)\n elif word == 'u':\n c = int(arg)\n if c < 0: c += 0x10000\n if c > 127: out.append(unichr(c))\n else: out.append(chr(c))\n curskip = ucskip\n elif hex: # \\'xx\n if curskip > 0:\n curskip -= 1\n elif not ignorable:\n c = int(hex,16)\n if c > 127: out.append(unichr(c))\n else: out.append(chr(c))\n elif tchar:\n if curskip > 0:\n curskip -= 1\n elif not ignorable:\n out.append(tchar)\n return ''.join(out)\n {\\* }"
},
{
"answer_id": 2229443,
"author": "Orian",
"author_id": 269517,
"author_profile": "https://Stackoverflow.com/users/269517",
"pm_score": 1,
"selected": false,
"text": "FareRule = Encoding.ASCII.GetString(FareRuleInfoRS.Data);\n System.Windows.Forms.RichTextBox rtf = new System.Windows.Forms.RichTextBox();\n rtf.Rtf = FareRule;\n FareRule = rtf.Text;\n"
},
{
"answer_id": 3577127,
"author": "Steven King",
"author_id": 198457,
"author_profile": "https://Stackoverflow.com/users/198457",
"pm_score": 3,
"selected": false,
"text": " /// <summary>\n /// Strip RichTextFormat from the string\n /// </summary>\n /// <param name=\"rtfString\">The string to strip RTF from</param>\n /// <returns>The string without RTF</returns>\n public static string StripRTF(string rtfString)\n {\n string result = rtfString;\n\n try\n {\n if (IsRichText(rtfString))\n {\n // Put body into a RichTextBox so we can strip RTF\n using (System.Windows.Forms.RichTextBox rtfTemp = new System.Windows.Forms.RichTextBox())\n {\n rtfTemp.Rtf = rtfString;\n result = rtfTemp.Text;\n }\n }\n else\n {\n result = rtfString;\n }\n }\n catch\n {\n throw;\n }\n\n return result;\n }\n\n /// <summary>\n /// Checks testString for RichTextFormat\n /// </summary>\n /// <param name=\"testString\">The string to check</param>\n /// <returns>True if testString is in RichTextFormat</returns>\n public static bool IsRichText(string testString)\n {\n if ((testString != null) &&\n (testString.Trim().StartsWith(\"{\\\\rtf\")))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n"
},
{
"answer_id": 14351163,
"author": "FiniteLooper",
"author_id": 79677,
"author_profile": "https://Stackoverflow.com/users/79677",
"pm_score": 3,
"selected": false,
"text": "function stripRtf(str){\n var basicRtfPattern = /\\{\\*?\\\\[^{}]+;}|[{}]|\\\\[A-Za-z]+\\n?(?:-?\\d+)?[ ]?/g;\n var newLineSlashesPattern = /\\\\\\n/g;\n var ctrlCharPattern = /\\n\\\\f[0-9]\\s/g;\n\n //Remove RTF Formatting, replace RTF new lines with real line breaks, and remove whitespace\n return str\n .replace(ctrlCharPattern, \"\")\n .replace(basicRtfPattern, \"\")\n .replace(newLineSlashesPattern, \"\\n\")\n .trim();\n}\n .trim()"
},
{
"answer_id": 21987039,
"author": "KevHun",
"author_id": 3346537,
"author_profile": "https://Stackoverflow.com/users/3346537",
"pm_score": 2,
"selected": false,
"text": "{\\*?\\\\.+(;})|\\s?\\\\[A-Za-z0-9]+|\\s?{\\s?\\\\[A-Za-z0-9]+\\s?|\\s?}\\s?\n"
},
{
"answer_id": 42572518,
"author": "Malvineous",
"author_id": 308237,
"author_profile": "https://Stackoverflow.com/users/308237",
"pm_score": 1,
"selected": false,
"text": "SELECT REGEXP_REPLACE(\n REGEXP_REPLACE(\n CONTENT,\n '\\\\(fcharset|colortbl)[^;]+;', ''\n ),\n '(\\\\[^ ]+ ?)|[{}]', ''\n) TEXT\nFROM EXAMPLE WHERE CONTENT LIKE '{\\rtf%';\n \\{ \\} { } \\fcharset \\colourtbl ; \\xxx { }"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324/"
] |
188,547
|
<p>Is it possible for Eclipse to read stdin from a file?</p>
|
[
{
"answer_id": 188654,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 6,
"selected": false,
"text": "System.setIn(new FileInputStream(filename));\n"
},
{
"answer_id": 6004393,
"author": "lanoxx",
"author_id": 474034,
"author_profile": "https://Stackoverflow.com/users/474034",
"pm_score": 4,
"selected": false,
"text": "C:\\myprogramm < file.txt ./myprogramm < file.txt -d ${resource_loc:/MyProject/file}\n -d path/to/file or -d C:\\path\\to\\file\n"
},
{
"answer_id": 10872607,
"author": "Vlad",
"author_id": 878537,
"author_profile": "https://Stackoverflow.com/users/878537",
"pm_score": 2,
"selected": false,
"text": "< ${workspace_loc:/MyProject/file}\n"
},
{
"answer_id": 10957131,
"author": "Scott",
"author_id": 311525,
"author_profile": "https://Stackoverflow.com/users/311525",
"pm_score": 3,
"selected": false,
"text": " Scanner in;\n if (args!=null && args.length>0 && args[0].equals(\"-d\")){\n in = new Scanner(new File(args[1]));\n } else {\n in = new Scanner(System.in);\n }\n"
},
{
"answer_id": 15626780,
"author": "drverboten",
"author_id": 1324444,
"author_profile": "https://Stackoverflow.com/users/1324444",
"pm_score": 0,
"selected": false,
"text": "res\\in.txt res\\out.txt build.xml <project basedir=\".\" default=\"run\" name=\"Tests\">\n<target name=\"clean\">\n<delete dir=\"bin\"/>\n</target>\n\n<target name=\"compile\">\n<mkdir dir=\"bin\"/>\n<javac srcdir=\"src\" destdir=\"bin\" includeantruntime=\"false\"/>\n</target>\n\n<target name=\"build\" depends=\"clean,compile\"/>\n\n<target name=\"run\" depends=\"build\">\n<java classname=\"Main\" input=\"res\\in.txt\" output=\"res\\out.txt\" classpath=\"bin\" />\n</target>\n</project>\n Run->External Tools->External Tools Configurations->Ant Build-> New Launch Configuration Section Main ${workspace_loc:/Tests/build.xml} ${workspace_loc:/Tests}"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
188,569
|
<p>Just starting out in asp.net.
Have just created a login.aspx page in my site and stuck on a asp login control - that's all I did. Now my Welcome.aspx page won't show as the start page of my site when I debug - even though it is set as this.
Plus I have even edited my web.config - (see below) - and it still does the same thing. How do I make it work so I have my Welcome.aspx page start up as default?</p>
<pre><code><authentication mode="Forms">
<forms defaultUrl="~/Welcome.aspx" loginUrl="~/login.aspx" timeout="1440" ></forms>
</authentication>
</code></pre>
|
[
{
"answer_id": 188614,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 3,
"selected": true,
"text": "<authorization><allow users=\"?\" /></authorization>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
188,584
|
<p>In c#, how can I check to see if a link button has been clicked in the page load method? </p>
<p>I need to know if it was clicked before the click event is fired.</p>
|
[
{
"answer_id": 188605,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 6,
"selected": true,
"text": "if( IsPostBack ) \n{\n // get the target of the post-back, will be the name of the control\n // that issued the post-back\n string eTarget = Request.Params[\"__EVENTTARGET\"].ToString();\n}\n"
},
{
"answer_id": 28184452,
"author": "RealSteel",
"author_id": 2027813,
"author_profile": "https://Stackoverflow.com/users/2027813",
"pm_score": 2,
"selected": false,
"text": "UseSubmitBehavior=\"false\""
},
{
"answer_id": 34094176,
"author": "Miguel",
"author_id": 416255,
"author_profile": "https://Stackoverflow.com/users/416255",
"pm_score": 1,
"selected": false,
"text": "<asp:Button id=\"btnExport\" runat=\"server\" Text=\"Export\" UseSubmitBehavior=\"false\"/>\n if(IsPostBack){\n var eventTarget = Request.Params[\"__EVENTTARGET\"]\n // Then check for the id but keep in mind that the name could be \n // something like ctl00$ContainerName$btnExport \n // if the button was clicked or null so take precautions against null\n // ... so it could be something like this\n var buttonClicked = eventTarget.Substring(eventTarget.LastIndexOf(\"$\") + 1).Equals(\"btnExport\")\n\n}\n"
},
{
"answer_id": 43508155,
"author": "Wang Jijun",
"author_id": 6388629,
"author_profile": "https://Stackoverflow.com/users/6388629",
"pm_score": 0,
"selected": false,
"text": " <Button Style=\"display: none\" ID=\"F2\" runat=\"server\" Text=\"F2:Cancel\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F2_Click\" />\n <Button Style=\"display: none\" ID=\"F3\" runat=\"server\" Text=\"F3:Return\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F3_Click\" />\n <Button Style=\"display: none\" ID=\"F6\" runat=\"server\" Text=\"F6:Run\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F6_Click\" />\n <Button Style=\"display: none\" ID=\"F12\" runat=\"server\" Text=\"F12:Finish\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F12_Click\" />\n Dictionary<string, string> dic = new Dictionary<string, string>();\nforeach(var id in new string[]{\"F2\",\"F3\",\"F6\",\"F12\"})\n{\n foreach (var key in Request.Params.AllKeys)\n {\n if (key != null && key.ToString().Contains(id))\n dic.Add(id, Request[key.ToString()].ToString()); \n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13053/"
] |
188,591
|
<p>Is there a fix or a workaround for the memory leak in getpwnam?</p>
|
[
{
"answer_id": 266785,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 4,
"selected": true,
"text": "getpwnam() getpwnam_r() malloc() free() std::tr1::shared_ptr<> free() scandir() asprintf() vasprintf()"
},
{
"answer_id": 11520218,
"author": "Daniel",
"author_id": 1531346,
"author_profile": "https://Stackoverflow.com/users/1531346",
"pm_score": 2,
"selected": false,
"text": "daniel@senap:~/dev/tryouts$ uname -a\nLinux senap 3.2.0-24-generic #39-Ubuntu SMP Mon May 21 16:52:17 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux\ndaniel@senap:~/dev/tryouts$ cat getpwnam-leak.c \n#include <sys/types.h>\n#include <pwd.h>\n\nextern void __libc_freeres(void);\n\nint main()\n{\n char buf[1024];\n struct passwd pw, *result;\n getpwnam_r(\"root\", &pw, buf, sizeof(buf), &result);\n __libc_freeres();\n}\ndaniel@senap:~/dev/tryouts$ valgrind --leak-check=full ./getpwnam-leak\n==6951== Memcheck, a memory error detector\n==6951== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.\n==6951== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info\n==6951== Command: ./getpwnam-leak\n==6951== \n==6951== \n==6951== HEAP SUMMARY:\n==6951== in use at exit: 300 bytes in 11 blocks\n==6951== total heap usage: 69 allocs, 58 frees, 9,234 bytes allocated\n==6951== \n==6951== 300 (60 direct, 240 indirect) bytes in 1 blocks are definitely lost in loss record 11 of 11\n==6951== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) \n==6951== by 0x4F35D94: nss_parse_service_list (nsswitch.c:678)\n==6951== by 0x4F36855: __nss_database_lookup (nsswitch.c:175)\n==6951== by 0x55F32A4: ???\n==6951== by 0x4EEF1AC: getpwnam_r@@GLIBC_2.2.5 (getXXbyYY_r.c:256)\n==6951== by 0x400607: main (in /home/daniel/dev/tryouts/getpwnam-leak)\n==6951== \n==6951== LEAK SUMMARY:\n==6951== definitely lost: 60 bytes in 1 blocks\n==6951== indirectly lost: 240 bytes in 10 blocks\n==6951== possibly lost: 0 bytes in 0 blocks\n==6951== still reachable: 0 bytes in 0 blocks\n==6951== suppressed: 0 bytes in 0 blocks\n==6951== \n==6951== For counts of detected and suppressed errors, rerun with: -v\n==6951== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)\ndaniel@senap:~/dev/tryouts$ \n"
},
{
"answer_id": 12558364,
"author": "Carlo Pires",
"author_id": 236499,
"author_profile": "https://Stackoverflow.com/users/236499",
"pm_score": 0,
"selected": false,
"text": "sudo sed -i s/compat/files/g /etc/nsswitch.conf\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26592/"
] |
188,625
|
<p>I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:</p>
<p>Console.WriteLine(objectF);</p>
<p>This prints out only the name of the class to the console:</p>
<pre><code>F
</code></pre>
<p>I want to overload this somehow so that I can instead print out some useful information about the object and its properties.</p>
<p>I have a workaround already: To overload the ToString method in my class and then call:
Console.WriteLine(objectF.ToString());</p>
<p>But I would rather have the simpler syntax. Any ideas?</p>
|
[
{
"answer_id": 188630,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 4,
"selected": true,
"text": "ToString ToString public override string ToString()\n{\n // replace the line below with your code\n return base.ToString();\n}\n"
},
{
"answer_id": 188633,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "Console.WriteLine(objectF)\n"
},
{
"answer_id": 188656,
"author": "Kevin P.",
"author_id": 18542,
"author_profile": "https://Stackoverflow.com/users/18542",
"pm_score": 1,
"selected": false,
"text": "public override string ToString()\n{\n ///Do stuff...\n return string;\n}\n"
},
{
"answer_id": 189297,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "public static class ObjectUtility\n{\n public static string ToDebug(this object obj)\n {\n if (obj == null)\n return \"<null>\";\n\n var type = obj.GetType();\n var props = type.GetProperties();\n\n var sb = new StringBuilder(props.Length * 20 + type.Name.Length);\n sb.Append(type.Name);\n sb.Append(\"\\r\\n\");\n\n foreach (var property in props)\n {\n if (!property.CanRead)\n continue;\n // AppendFormat defeats the point\n sb.Append(property.Name);\n sb.Append(\": \");\n sb.Append(property.GetValue(obj, null));\n sb.Append(\"\\r\\n\");\n }\n\n return sb.ToString();\n }\n}\n var f = new F();\nConsole.WriteLine(f.ToDebug());\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18542/"
] |
188,631
|
<p>How can I tell if an assembly is in use by any process?</p>
|
[
{
"answer_id": 1089035,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 2,
"selected": false,
"text": "if ( Get-Process | ? { $_.Modules | ? {$_.ModuleName -eq \"AssemblyName.dll\" } })\n{\n \"in use\"\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26553/"
] |
188,636
|
<p>I'm trying to find a way to force Windows to reboot, and I am running into issues. I've tried </p>
<p><pre><code><code>Set OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," _
& "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where "_
& "Primary=true")
for each OpSys in OpSysSet
retVal = OpSys.Reboot()
next</code></pre></code></p>
<p>I've also tried using the <code>shutdown -f -r</code> command, and in both cases I sometimes get no response, and if I try again I get an error saying "Action could not complete because the system is shutting down" even though no matter how long I leave it it doesn't shut down, it still allows me to start new programs, and doing a <code>shutdown -a</code> gives the same error. How can a script be used to force Windows to reboot?</p>
|
[
{
"answer_id": 188796,
"author": "Mike L",
"author_id": 12085,
"author_profile": "https://Stackoverflow.com/users/12085",
"pm_score": 2,
"selected": false,
"text": "Dim oShell \nSet oShell = CreateObject(\"WScript.Shell\")\n\n'restart, wait 5 seconds, force running apps to close\noShell.Run \"%comspec% /c shutdown /r /t 5 /f\", , TRUE\n"
},
{
"answer_id": 188836,
"author": "Matt Hanson",
"author_id": 5473,
"author_profile": "https://Stackoverflow.com/users/5473",
"pm_score": 4,
"selected": true,
"text": "retVal = OpSys.Reboot()\n retVal = OpSys.Win32Shutdown(6)\n"
},
{
"answer_id": 6273593,
"author": "Ossama ",
"author_id": 788499,
"author_profile": "https://Stackoverflow.com/users/788499",
"pm_score": 2,
"selected": false,
"text": "'*********************************************************\n\nOption Explicit\n\nDim objShell\n\nSet objShell = WScript.CreateObject(\"WScript.Shell\")\n\nobjShell.Run \"C:\\WINDOWS\\system32\\shutdown.exe -r -t 0\"\n\n'*********************************************************\n"
},
{
"answer_id": 55630318,
"author": "Hakan ÇELİK",
"author_id": 11345553,
"author_profile": "https://Stackoverflow.com/users/11345553",
"pm_score": 0,
"selected": false,
"text": "Set Reset= WScript.CreateObject (\"WScript.Shell\")\n\nReset.run \"shutdown -r -t 0\", 0, True\n Shell \"shutdown -r -f -t 0\" ' for restart\n\nShell \"shutdown -s -f -t 0\" ' for Shutdown\n\nShell \"shutdown -l -f -t 0\" ' for log off\n\nShell \"shutdown -a \" ' for abort\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14092/"
] |
188,639
|
<p>I normally don't work on Windows development, and am completely unfamiliar with the toolchain and build system. My embedded product includes some Windows DLLs from a third party in its filesystem (which are used by a Windows machine which mounts the filesystem).</p>
<p>I have a problem: the most recent release of these DLLs have tripled in size compared to previous builds, and they no longer fit in the filesystem. There have not been many changes in the functionality of the DLLs, so I suspect the developers simply forgot to strip debug symbols in this drop. I will ask them, but getting an answer often takes days due to timezone and language differences.</p>
<p>Could someone explain, using simple steps for someone unfamiliar with VisualC, how to determine if a DLL still contains debugging information and how to strip it out?</p>
|
[
{
"answer_id": 188721,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "*.pdb MSVCRT.DLL MSVCRTD.DLL dumpbin /imports whatever.dll\n whatever.dll"
},
{
"answer_id": 200379,
"author": "Chris Becke",
"author_id": 27491,
"author_profile": "https://Stackoverflow.com/users/27491",
"pm_score": 3,
"selected": false,
"text": "rebase -i 0x10000000 -a -x .\\ -p \n"
},
{
"answer_id": 10457286,
"author": "0xC0000022L",
"author_id": 476371,
"author_profile": "https://Stackoverflow.com/users/476371",
"pm_score": 0,
"selected": false,
"text": "link.exe /PDB:filename\n /PDBSTRIPPED:filename\n ASSERT binplace.exe"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4761/"
] |
188,663
|
<p>I'm curious as to if there are any best practices relating to JQuery when constructing encapsulated code blocks.</p>
<p>Generally, when I construct a page I like to encapsulate the functions used within that page inside an object. This allows me some encapsulation when building applications. There's nothing I hate more than seeing a JavaScript file with a bunch of this</p>
<pre><code>function doSomethingOnlyRelevantOnThisPage() {
// do some stuff
}
</code></pre>
<p>I this makes for messy design, and doesn't really encapsulate functionality nicely.</p>
<p>Commonly in many frameworks, there is a standard that is used to perform this encapsulation. </p>
<p>In Mootools they favor the Object Literal Notation:</p>
<pre><code>var Site = {
// properties and methods
}
</code></pre>
<p>In YUI they favor the Self Executing Function notation:</p>
<pre><code>(function() { // properties and methods })()
</code></pre>
<p>The nice thing about the second example is that a closure is created, thus allowing you to define private properties and methods.</p>
<p>My question is this: Do any JQuery aficionados have any best practices for creating these cleanly encapsulated structures? What is the rationale behind their use?</p>
|
[
{
"answer_id": 188713,
"author": "Tsvetomir Tsonev",
"author_id": 25449,
"author_profile": "https://Stackoverflow.com/users/25449",
"pm_score": 1,
"selected": false,
"text": "MyFunction = function(param1, param2)\n{\n this.property1 = param1;\n // etc.\n}\n\nMyFunction.prototype =\n{\n memberOne: function(param1)\n {\n // ...\n },\n\n memberTwo: function(param2)\n {\n }\n}\n"
},
{
"answer_id": 188761,
"author": "Dan Hulton",
"author_id": 8327,
"author_profile": "https://Stackoverflow.com/users/8327",
"pm_score": 2,
"selected": false,
"text": "/*global YAHOO, $ */\n\n// Create the public-scope accessable namespace for this page\nYAHOO.namespace('Project');\n\nYAHOO.Project.page = function() {\n // Private members\n\n var self = {};\n\n // Public members\n var pub = {};\n\n pub.init = function() {\n\n };\n\n return pub;\n} ();\n\n// When the DOM is loaded, initialize this module\n$(document).ready(YAHOO.Project.page.init);\n self.funcName() self size_of()"
},
{
"answer_id": 1710006,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 5,
"selected": true,
"text": ";(function($) { \n var myPrivateFunction = function() {\n };\n\n var init = function() {\n myPrivateFunction();\n };\n\n $(init);\n})(jQuery);\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769/"
] |
188,669
|
<p>I have a page being loaded with jQuery. The initial load includes 100 records with 6 icons per record. Needless to say, it takes a few seconds to load and I want to give the user a "loading" prompt/animation. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 26079543,
"author": "Buturca Marius",
"author_id": 2823942,
"author_profile": "https://Stackoverflow.com/users/2823942",
"pm_score": 0,
"selected": false,
"text": "<div class=\"pulse\"></div>\n .pulse {\n width: 32px;\n height: 32px;\n margin: 25% auto;\n background-color: #303030;\n -webkit-border-radius: 16px;\n -moz-border-radius: 16px;\n -ms-border-radius: 16px;\n -o-border-radius: 16px;\n border-radius: 16px;\n -webkit-animation: scaleout 1.0s infinite ease-in-out;\n animation: scaleout 1.0s infinite ease-in-out;\n}\n@-webkit-keyframes scaleout{\n 0%{\n -webkit-transform:scale(0)\n }\n 100%{\n -webkit-transform:scale(1);\n opacity:0\n }\n}\n@-moz-keyframes scaleout{\n 0%{\n -moz-transform:scale(0)\n }\n 100%{\n -moz-transform:scale(1);\n opacity:0\n }\n}\n@-ms-keyframes scaleout{\n 0%{\n -ms-transform:scale(0)\n }\n 100%{\n -ms-transform:scale(1);\n opacity:0\n }\n}\n@-o-keyframes scaleout{\n 0%{\n -o-transform:scale(0)\n }\n 100%{\n -o-transform:scale(1);\n opacity:0\n }\n}\n@keyframes scaleout{\n 0%{\n transform:scale(0);\n -webkit-transform:scale(0)\n }\n 100%{\n transform:scale(1);\n -webkit-transform:scale(1);\n opacity:0\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
188,679
|
<p>I have found that my HTML is, to be honest, very clunky. Small, simple pages are OK. But there comes a point when between indenting and the kinds of tags I have, it's impossible to keep lines short. Is there a W3C (or otherwise "official" or well accepted) formatting guide for clean, maintainable HTML? If not, what suggestions can the community provide?</p>
|
[
{
"answer_id": 188710,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>\n This is my <b>fancy</b> code block of text here. This will\n typically wrap forever and <div class=\"SarcasticStyle\">EVER</div> until\n I run out of things to say.\n <br/>\n Yeah, I think that's it.\n</p>\n"
},
{
"answer_id": 190175,
"author": "cowgod",
"author_id": 6406,
"author_profile": "https://Stackoverflow.com/users/6406",
"pm_score": 1,
"selected": false,
"text": "<label> <a> <a href=\"https://rads.stackoverflow.com/amzn/click/com/1430209879\" rel=\"nofollow noreferrer\"More Joel on Software: Further Thoughts on Diverse and\n Occasionally Related Matters That Will Prove of Interest to\n Software Developers, Designers, and ... Luck, Work with Them\n in Some Capacity (Pro) (Paperback)\">Another Joel on Software book</a>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
188,680
|
<p>If a person is looking to batch convert a large number of raster images into vector graphics, are there any tools out there that do that well?</p>
<p>For an example, think of just about any diagram that has standard shapes (ellipses, rectangles) and text.</p>
|
[
{
"answer_id": 39953648,
"author": "Andras",
"author_id": 6947836,
"author_profile": "https://Stackoverflow.com/users/6947836",
"pm_score": 0,
"selected": false,
"text": "java -jar ImageTracer.jar smiley.png for file in *.png; do java -jar ImageTracer.jar \"$file\" outfilename \"${file/%ext/svg}\"; done"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
188,687
|
<p>Is there a way to change the way asp.net generates elements in the WSDL generated from a .asmx file? Specifically, it seems to mark all elements minoccurs="0" and there are some elements that I want to be minoccurs="1" (aka required fields). </p>
<p>One of these is an argument to the web service (e.g. foo(arg1, arg2) where I want arg2 to be generated in the WSDL as minoccurs="1") the other is a particular field in the class that corresponds to arg1. Do I have to forego auto WSDL generation and take a "contract first" approach?</p>
|
[
{
"answer_id": 189160,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": false,
"text": "XmlElement(IsNullable = true) using System.Xml.Serialization;\n\n[WebMethod]\npublic string MyService([XmlElement(IsNullable = true)] string arg)\n{\n return \"1\";\n}\n Imports System.Xml.Serialization\n\nPublic Function MyService(<XmlElement(IsNullable:=True)> ByVal arg As String) As String\n Return (\"1\")\nEnd Function\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7243/"
] |
188,688
|
<p>I am looking at some code and it has this statement: </p>
<pre><code>~ConnectionManager()
{
Dispose(false);
}
</code></pre>
<p>The class implements the <code>IDisposable</code> interface, but I do not know if that is part of that the tilde(~) is used for.</p>
|
[
{
"answer_id": 188712,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "IntPtr SafeHandle IDisposable"
},
{
"answer_id": 188715,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 9,
"selected": true,
"text": "Close() Dispose() GC.SuppressFinalize()"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
188,691
|
<p>I want to write something that acts just like confirm() in javascript, but I want to write it myself so I can skin the dialog box. In having trouble thinking through how I would basically force the javascript thread to wait until the user responds and then return true or false.</p>
|
[
{
"answer_id": 188708,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": true,
"text": "function askUserYesOrNo() {\n var myDialog = $('<div class=\"mydialog\"><p>Yes or No?</p><input type=\"button\" id=\"yes\" value=\"Yes\"/><input type=\"button\" id=\"no\" value=\"No\"/></div>');\n $(\"#yes\").click(handleYes);\n $(\"#no\").click(handleNo);\n myDialog.modal(); //This would have to be replaced by whatever syntax the modal framework uses\n}\n\nfunction handleYes() {\n //handle yes...\n}\n\nfunction handleNo() {\n //handle no...\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
188,692
|
<p>I recall reading, on multiple occasions and in multiple locations, that when firing the typical event:</p>
<pre><code>protected virtual OnSomethingHappened()
{
this.SomethingHappened(this, EventArgs.Empty);
}
</code></pre>
<p>e should be EventArgs.Empty if there are no interesting event args, not null.</p>
<p>I've followed the guidance in my code, but I realized that I'm not clear on why that's the preferred technique. Why does the stated contract prefer EventArgs.Empty over null?</p>
|
[
{
"answer_id": 188737,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "EventHandler object sender EventArgs e e.ToString()"
},
{
"answer_id": 188743,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 3,
"selected": false,
"text": "EventArgs.Empty EventArgs.Empty string.Empty newString = \"\"; or newString = \" \"; or newString = null; EventArgs.Empty new EventArgs() EventArgs"
},
{
"answer_id": 947677,
"author": "Martin Konicek",
"author_id": 90998,
"author_profile": "https://Stackoverflow.com/users/90998",
"pm_score": 5,
"selected": false,
"text": "EventArgs.Empty"
},
{
"answer_id": 22455441,
"author": "Bobak_KS",
"author_id": 2539385,
"author_profile": "https://Stackoverflow.com/users/2539385",
"pm_score": 0,
"selected": false,
"text": "\"in order to avoid unnecessarily instantiating an instance of EventArgs.\""
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6932/"
] |
188,693
|
<p>Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')</p>
|
[
{
"answer_id": 188722,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "using System;\n\nclass Test\n{\n Test()\n {\n throw new Exception();\n }\n\n ~Test()\n {\n Console.WriteLine(\"Finalized\");\n }\n\n static void Main()\n {\n try\n {\n new Test();\n }\n catch {}\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n"
},
{
"answer_id": 188882,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": true,
"text": "struct Class\n{\n Class() ;\n ~Class() ;\n \n Thing * m_pThing ;\n Object m_aObject ;\n Gizmo * m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n{\n this->m_pThing = new Thing() ;\n this->m_pGizmo = new Gizmo() ;\n}\n Class pClass = new Class() ;\n struct Class\n{\n Class() ;\n ~Class() ;\n \n std::auto_ptr<Thing> m_pThing ;\n Object m_aObject ;\n std::auto_ptr<Gizmo> m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n : m_pThing(new Thing())\n , m_pGizmo(new Gizmo())\n{\n}\n Class::Class()\n{\n this->m_pThing.reset(new Thing()) ;\n this->m_pGizmo.reset(new Gizmo()) ;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22820/"
] |
188,719
|
<p>A friend and I are about to embark on creating a machine that performs some image comparison for sorting. I know about histogram comparison and am generally confident that a small grid of histograms per image precalculated and stored in columns in a database table will generally give us pretty good matches on the first pass because we are matching like things.</p>
<p>The second comparison we want to perform is to use a <a href="http://tinyurl.com/4lo8nl" rel="nofollow noreferrer">color coherence vector</a> (CCV) of images which passed the histogram match test from our subject image to the candidate images. I know that this sort of comparison is more precise.</p>
<p>My friend is confident that he can develop CCV in C# using the <a href="http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx" rel="nofollow noreferrer">C# wrapper</a> to <a href="http://sourceforge.net/projects/opencvlibrary/" rel="nofollow noreferrer">OpenCV</a>. I am pretty sure he can too. However I would like to know:</p>
<ol>
<li>Has anyone already done this in C# and released the source code? Or a C# wrapper?</li>
<li>Are we barking up the wrong tree? (Should we just use CCV and forgo histogram comparisons at the database level? Or is CCV too much?)</li>
</ol>
|
[
{
"answer_id": 188722,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "using System;\n\nclass Test\n{\n Test()\n {\n throw new Exception();\n }\n\n ~Test()\n {\n Console.WriteLine(\"Finalized\");\n }\n\n static void Main()\n {\n try\n {\n new Test();\n }\n catch {}\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n"
},
{
"answer_id": 188882,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": true,
"text": "struct Class\n{\n Class() ;\n ~Class() ;\n \n Thing * m_pThing ;\n Object m_aObject ;\n Gizmo * m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n{\n this->m_pThing = new Thing() ;\n this->m_pGizmo = new Gizmo() ;\n}\n Class pClass = new Class() ;\n struct Class\n{\n Class() ;\n ~Class() ;\n \n std::auto_ptr<Thing> m_pThing ;\n Object m_aObject ;\n std::auto_ptr<Gizmo> m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n : m_pThing(new Thing())\n , m_pGizmo(new Gizmo())\n{\n}\n Class::Class()\n{\n this->m_pThing.reset(new Thing()) ;\n this->m_pGizmo.reset(new Gizmo()) ;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645/"
] |
188,720
|
<p>Is there any way in the SQL language or in MySQL (or other DBMA) to transfer a value from one cell to another? For example, say there is a table called user_cars with the following structure:</p>
<pre><code>|id| |user_name| |num_cars|
</code></pre>
<p>Bob has 5 cars, and John has 3 cars. Is there any way to in one query subtract 2 cars from Bob and add 2 to John? I know this can be done with two update queries, but I'd just like to know if there was a more efficient way.</p>
|
[
{
"answer_id": 188756,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 3,
"selected": true,
"text": " UPDATE user_cars\n SET num_cars = num_cars +\n CASE WHEN user_name='Bob' THEN -2\n WHEN user_name='John' THEN +2\n END\n WHERE user_name IN ( 'Bob', 'John' )\n"
},
{
"answer_id": 188764,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "UPDATE USER_CARS UC\nSET\n NUM_CARS = NUM_CARS + CASE WHEN UC.USER_NAME = 'Bob'\n THEN -2 --take from bob\n WHEN UC.USER_NAME = 'John'\n THEN 2 --give to John\n ELSE 0 --no change for anybody else\n END\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26603/"
] |
188,738
|
<p>People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?</p>
|
[
{
"answer_id": 188763,
"author": "derby",
"author_id": 11790,
"author_profile": "https://Stackoverflow.com/users/11790",
"pm_score": 6,
"selected": true,
"text": "#!/usr/bin/perl\n\nuse Carp;\n\nfoo();\nbar();\nbaz();\n\nsub foo {\n warn \"foo\";\n}\n\nsub bar {\n carp \"bar\";\n}\n\nsub baz {\n foo();\n bar(); \n}\n foo at ./foo.pl line 9.\nbar at ./foo.pl line 13\n main::bar() called at ./foo.pl line 6\nfoo at ./foo.pl line 10.\nbar at ./foo.pl line 14\n main::bar() called at ./foo.pl line 19\n main::baz() called at ./foo.pl line 7\n"
},
{
"answer_id": 188846,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 5,
"selected": false,
"text": "warn Carp Carp Carp warn"
},
{
"answer_id": 188920,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "Carp warn carp warn cluck"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
188,769
|
<p>I'm trying to show someone a use for interfaces in a crazy situation they've created. They have several unrelated objects in lists, and need to perform an operation on two string properties in each object. I'm pointing out that if they define the properties as part of an interface, they can use the interface object as the type for a method parameter that acts on it; for example:</p>
<pre><code>void PrintProperties(IEnumerable<ISpecialProperties> list)
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}</code></pre>
<p>This seems like it's all good, but the lists that need to be worked on aren't (and shouldn't) be declared with the interface as the type parameter. However, it doesn't seem like you can cast to a different type parameter. For example, this fails and I can't understand why:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Test> myList = new List<Test>();
for (int i = 0; i < 5; i++)
{
myList.Add(new Test());
}
PrintList((IEnumerable<IDoSomething>)myList);
}
static void PrintList(IEnumerable<IDoSomething> list)
{
foreach (IDoSomething item in list)
{
item.DoSomething();
}
}
}
interface IDoSomething
{
void DoSomething();
}
public class Test : IDoSomething
{
public void DoSomething()
{
Console.WriteLine("Test did it!");
}
}
}</code></pre>
<p>I <em>can</em> use the <code>Enumerable.Cast<T></code> member to do this, but I was looking for a method that might work in .NET 2.0 as well. It seems like this should be possible; what am I missing? </p>
|
[
{
"answer_id": 188797,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "void PrintProperties<SP>(IEnumerable<SP> list) where SP: ISpecialProperties\n{\n foreach (var item in list)\n {\n Console.WriteLine(\"{0} {1}\", item.Prop1, item.Prop2);\n }\n}\n"
},
{
"answer_id": 188801,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<TBase> SafeConvert<TBase, TDerived>(IEnumerable<TDerived> source)\n where TDerived : TBase\n{\n foreach (TDerived element in source)\n {\n yield return element; // Implicit conversion to TBase\n }\n}\n"
},
{
"answer_id": 188812,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 1,
"selected": false,
"text": "foreach foreach List<Test> myList = new List<Test>();\nfor (int i = 0; i < 5; i++)\n{\n myList.Add(new Test());\n}\n\nforeach (IDoSomething item in myList)\n{\n item.DoSomething();\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
] |
188,787
|
<p>I need to find occurrences of "(+)" in my sql scripts, (i.e., Oracle outer join expressions). Realizing that "+", "(", and ")" are all special regex characters, I tried:</p>
<pre>
grep "\(\+\)" *
</pre>
<p>Now this does return occurrences of "(+)", but other lines as well. (Seemingly anything with open and close parens on the same line.) Recalling that parens are only special for extended grep, I tried:</p>
<pre>
grep "(\+)" *
grep "(\\+)" *
</pre>
<p>Both of these returned only lines that contain "()". So assuming that "+" can't be escaped, I tried an old trick:</p>
<pre>
grep "([+])" *
</pre>
<p>That works. I cross-checked the result with a non-regex tool.</p>
<p><strong>Question</strong>: Can someone explain what exactly is going on with the "+" character? Is there a less kludgy way to match on "(+)"?</p>
<p>(I am using the cygwin grep command.)</p>
<p><strong>EDIT</strong>: Thanks for the solutions. -- And now I see that, per the GNU grep manual that Bruno referenced, "<code>\+</code>" when used in a <em>basic</em> expression gives "+" its <em>extended</em> meaning, and therefore matches one-or-more "("s followed by a ")". And in my files that's always "()".</p>
|
[
{
"answer_id": 188795,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 1,
"selected": false,
"text": "grep \"(+)\""
},
{
"answer_id": 188837,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 4,
"selected": true,
"text": "grep egrep grep -E ? + { | ( ) \\? \\+ \\{ \\| \\( \\) ( + ) grep \"(+)\" * # Basic\negrep \"\\(\\+\\)\" * # Extended\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
188,793
|
<p>What I'm trying to do is encode a gif file, to include in an XML document.
This is what I have now, but it doesn't seem to work.</p>
<pre><code>Function gifToBase64(strGifFilename)
On Error Resume Next
Dim strBase64
Set inputStream = WScript.CreateObject("ADODB.Stream")
inputStream.LoadFromFile strGifFilename
strBase64 = inputStream.Text
Set inputStream = Nothing
gifToBase64 = strBase64
End Function
</code></pre>
|
[
{
"answer_id": 189340,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "Function Base64Encode(rabyt)\n\n Dim dom: Set dom = CreateObject(\"MSXML2.DOMDocument.3.0\")\n Dim elem: Set elem = dom.appendChild(dom.createElement(\"root\"))\n elem.dataType = \"bin.base64\"\n elem.nodeTypedValue = rabyt\n\n Base64Encode = elem.Text\n\nEnd Function\n"
},
{
"answer_id": 19131358,
"author": "Chris West",
"author_id": 657132,
"author_profile": "https://Stackoverflow.com/users/657132",
"pm_score": 2,
"selected": false,
"text": "Public Function convertImageToBase64(filePath)\n Dim inputStream\n Set inputStream = CreateObject(\"ADODB.Stream\")\n inputStream.Open\n inputStream.Type = 1 ' adTypeBinary\n inputStream.LoadFromFile filePath\n Dim bytes: bytes = inputStream.Read\n Dim dom: Set dom = CreateObject(\"Microsoft.XMLDOM\")\n Dim elem: Set elem = dom.createElement(\"tmp\")\n elem.dataType = \"bin.base64\"\n elem.nodeTypedValue = bytes\n convertImageToBase64 = \"data:image/png;base64,\" & Replace(elem.text, vbLf, \"\")\nEnd Function\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
188,808
|
<p>I have a Winform application built with C# and .Net 2.0. I have a textbox set with the MultiLine property.</p>
<p>The problem is when someone writes text with multiple lines (press few enters), presses the save button, and then closes and loads the form again, all the new lines disappear (the text is there at least).</p>
<p>For example, if the textbox had this in it:</p>
<pre><code>Line1
Line3
</code></pre>
<p>It will look like this after I save and load:</p>
<pre><code>Line1 Line3
</code></pre>
<p>Any idea why?</p>
<p><strong>Update</strong></p>
<p>The database is PostGres and when I use PGAdmin I can see all the line AND the "enters". So the persistence seem to have save all the line... the problem seem to be when I put back the string in the Textbox.</p>
|
[
{
"answer_id": 188838,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 3,
"selected": true,
"text": "textBox1.Lines = foo.Split(new String[] {\"\\n\"},StringSplitOptions.RemoveEmptyEntries);\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
188,828
|
<p>I've just learned ( yesterday ) to use "exists" instead of "in".</p>
<pre><code> BAD
select * from table where nameid in (
select nameid from othertable where otherdesc = 'SomeDesc' )
GOOD
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
</code></pre>
<p>And I have some questions about this:</p>
<p>1) The explanation as I understood was: <em>"The reason why this is better is because only the matching values will be returned instead of building a massive list of possible results"</em>. Does that mean that while the first subquery might return 900 results the second will return only 1 ( yes or no )?</p>
<p>2) In the past I have had the RDBMS complainin: "only the first 1000 rows might be retrieved", this second approach would solve that problem?</p>
<p>3) What is the scope of the alias in the second subquery?... does the alias only lives in the parenthesis? </p>
<p>for example </p>
<pre><code> select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
AND
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeOtherDesc' )
</code></pre>
<p>That is, if I use the same alias ( o for table othertable ) In the second "exist" will it present any problem with the first exists? or are they totally independent?</p>
<p>Is this something Oracle only related or it is valid for most RDBMS?</p>
<p>Thanks a lot</p>
|
[
{
"answer_id": 188849,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 3,
"selected": true,
"text": "select t.* \nfrom table t \njoin othertable o on t.nameid = o.nameid \n and o.otherdesc in ('SomeDesc','SomeOtherDesc');\n"
},
{
"answer_id": 188851,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "SELECT t.*\nFROM yourTable t\n INNER JOIN otherTable ot\n ON (t.nameid = ot.nameid AND ot.otherdesc = 'SomeDesc')\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
188,833
|
<p>Why am I getting a textbox that returns undefined list of variables?</p>
<p>When I run this code:</p>
<pre><code>var query = (from tisa in db.TA_Info_Step_Archives
where tisa.ta_Serial.ToString().StartsWith(prefixText)
select tisa.TA_Serial.ToString()).Distinct().Take(Convert.ToInt32(count));
return query.ToList<string>().ToArray();
</code></pre>
<p>I get this XML file:</p>
<pre><code><string>200700160</string>
<string>200700161</string>
<string>200700162</string>
<string>200700163</string>
<string>200700164</string>
<string>200700170</string>
<string>200700171</string>
<string>200700172</string>
<string>200700173</string>
<string>200700174</string>
<string>200700175</string>
<string>200700176</string>
<string>200700177</string>
<string>200700178</string>
<string>200700179</string>
<string>200700180</string>
<string>200700181</string>
<string>200700182</string>
<string>200700183</string>
<string>200700184</string>
</code></pre>
<p>BUT, the textbox returns a list of <code>undefined</code>....</p>
<p>Help please?</p>
|
[
{
"answer_id": 188907,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 0,
"selected": false,
"text": "<cc1:AutoCompleteExtender ID=\"Result\" runat=\"server\" TargetControlID=\"txtSearch\" ServiceMethod=\"YourMethodHere\"\n ServicePath=\"~/Service/YourWebServiceHere.asmx\" CompletionInterval=\"500\"\n EnableCaching=\"false\" CompletionListCssClass=\"AutoComplete_List\" CompletionSetCount=\"10\">\n</cc1:AutoCompleteExtender>\n"
},
{
"answer_id": 255135,
"author": "Joel",
"author_id": 33235,
"author_profile": "https://Stackoverflow.com/users/33235",
"pm_score": 0,
"selected": false,
"text": "...\nda.Fill(dt);\n string[] items = new string[dt.Rows.Count];\n int i = 0;\n foreach (DataRow dr in dt.Rows)\n {\n items.SetValue(Convert.ToString(dr[\"somenumber\"]), i);\n i++;\n }\n...\n ...\nda.Fill(dt);\n string[] items = new string[dt.Rows.Count];\n int i = 0;\n foreach (DataRow dr in dt.Rows)\n {\n items.SetValue(Convert.ToString(dr[\"somenumber\"]+\"foo\"), i);\n i++;\n }\n...\n"
},
{
"answer_id": 259268,
"author": "Joel",
"author_id": 33235,
"author_profile": "https://Stackoverflow.com/users/33235",
"pm_score": 3,
"selected": true,
"text": " foreach (DataRow dr in dt.Rows)\n {\n items.SetValue(\"\\\"\" + dr[\"somenumber\"].ToString() + \"\\\"\", i);\n i++;\n }\n"
},
{
"answer_id": 771504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "items.SetValue(\"'\"+dr[\"somenumber\"]+\"'\", i);\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
188,834
|
<p>I need to dynamically construct an XPath query for an element attribute, where the attribute value is provided by the user. I'm unsure how to go about cleaning or sanitizing this value to prevent the XPath equivalent of a SQL injection attack. For example (in PHP):</p>
<pre><code><?php
function xPathQuery($attr) {
$xml = simplexml_load_file('example.xml');
return $xml->xpath("//myElement[@content='{$attr}']");
}
xPathQuery('This should work fine');
# //myElement[@content='This should work fine']
xPathQuery('As should "this"');
# //myElement[@content='As should "this"']
xPathQuery('This\'ll cause problems');
# //myElement[@content='This'll cause problems']
xPathQuery('\']/../privateElement[@content=\'private data');
# //myElement[@content='']/../privateElement[@content='private data']
</code></pre>
<p>The last one in particular is reminiscent to the SQL injection attacks of yore.</p>
<p>Now, I know for a fact there will be attributes containing single quotes and attributes containing double quotes. Since these are provided as an argument to a function, what would be the ideal way to sanitize the input for these?</p>
|
[
{
"answer_id": 188858,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": -1,
"selected": false,
"text": "function xPathQuery($attr) {\n $xml = simplexml_load_file('example.xml');\n $to_encode = array('&', '\"');\n $to_replace = array('&','"');\n $attr = replace($to_encode, $to_replace, $attr);\n return $xml->xpath(\"//myElement[@content=\\\"{$attr}\\\"]\");\n}\n"
},
{
"answer_id": 194071,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 3,
"selected": false,
"text": "$varname >>> from lxml import etree\n>>> n = etree.fromstring('<n a=\\'He said \"I'm here\"\\'/>')\n>>> n.xpath(\"@a=$maybeunsafe\", maybeunsafe='He said \"I\\'m here\"')\nTrue\n def safe_xpath_string(strvar):\n if \"'\" in strvar:\n return \"',\\\"'\\\",'\".join(strvar.split(\"'\")).join((\"concat('\",\"')\"))\n return strvar.join(\"''\")\n >>> print safe_xpath_string(\"basic\")\n'basic'\n>>> print safe_xpath_string('He said \"I\\'m here\"')\nconcat('He said \"I',\"'\",'m here\"')\n ' function safe_xpath_string($value)\n{\n $quote = \"'\";\n if (FALSE === strpos($value, $quote))\n return $quote.$value.$quote;\n else\n return sprintf(\"concat('%s')\", implode(\"', \\\"'\\\", '\", explode($quote, $value)));\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
188,839
|
<p>I use a structure of function pointers to implement an interface for different backends. The signatures are very different, but the return values are almost all void, void * or int.</p>
<pre><code>
struct my_interface {
void (*func_a)(int i);
void *(*func_b)(const char *bla);
...
int (*func_z)(char foo);
};
</code></pre>
<p>But it is not required that a backends supports functions for every interface function. So I have two possibilities, first option is to check before every call if the pointer is unequal NULL. I don't like that very much, because of the readability and because I fear the performance impacts (I haven't measured it, however). The other option is to have a dummy function, for the rare cases an interface function doesn't exist.</p>
<p>Therefore I'd need a dummy function for every signature, I wonder if it is possible to have only one for the different return values. And cast it to the given signature.</p>
<pre><code>
#include <stdio.h>
int nothing(void) {return 0;}
typedef int (*cb_t)(int);
int main(void)
{
cb_t func;
int i;
func = (cb_t) nothing;
i = func(1);
printf("%d\n", i);
return 0;
}
</code></pre>
<p>I tested this code with gcc and it works. But is it sane? Or can it corrupt the stack or can it cause other problems?</p>
<p>EDIT: Thanks to all the answers, I learned now much about calling conventions, after a bit of further reading. And have now a much better understanding of what happens under the hood.</p>
|
[
{
"answer_id": 188860,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "extern \"C\" __cdecl printf()"
},
{
"answer_id": 188905,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 2,
"selected": false,
"text": "nothing()"
},
{
"answer_id": 189126,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 5,
"selected": true,
"text": "func = (cb_t)nothing;\nfunc(1);\n abort"
},
{
"answer_id": 345689,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": -1,
"selected": false,
"text": "void void_int_NULL(int n) { (void)n; abort(); }\n if (my_thing->func_a != void_int_NULL) my_thing->func_a(99);\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
] |
188,844
|
<p>If I had a Canvas with n number of Visual objects of any shape or size, how would I highlight/outline a Visual object programmatically? </p>
<p>Is there something built into WPF to help me? </p>
|
[
{
"answer_id": 189061,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 4,
"selected": true,
"text": "BitmapEffects BitmapEffects BitmapEffect System.Windows.Media.Effects.Effect Visual.VisualEffect"
},
{
"answer_id": 189099,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 3,
"selected": false,
"text": "<Path\n x:Name=\"mouseOverEffect\"\n Width=\"80\"\n Height=\"43.916\"\n Stretch=\"None\"\n Fill=\"#FFFFFFFF\"\n Opacity=\"0\"\n>\n <Path.Data>\n <PathGeometry FillRule=\"Nonzero\">\n <PathFigure IsClosed=\"True\" StartPoint=\"39.9592899612151,25.9913931634531\">\n <LineSegment Point=\"80.0000001464848,43.9159987905149\"/>\n <LineSegment Point=\"39.9513899394755,4.97379893856246E-14\"/>\n <LineSegment Point=\"1.77635636294422E-15,43.9159987905149\"/>\n <LineSegment Point=\"39.9592899612151,25.9913931634531\"/>\n </PathFigure>\n </PathGeometry>\n </Path.Data>\n <Path.Effect>\n <DropShadowEffect\n Color=\"#FFFFFFFF\"\n BlurRadius=\"10\"\n ShadowDepth=\"0\"\n />\n </Path.Effect>\n</Path> \n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4580/"
] |
188,850
|
<p>I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs.</p>
<p>So far I have something like this:</p>
<pre><code>start "~\iexplore.exe" "url1"
start "~\iexplore.exe" "url2"
</code></pre>
<p>What I get is one instance of Internet Explorer with only the second URL loaded. Seems the second is replacing the second. I seem to remember a syntax where I would load a new command line window and pass the command to execute on load, but can't find the reference.</p>
<p>As a second part of the question: what is a good reference URL to keep for the times you need to write a quick batch file?</p>
<p>Edit: I have marked an answer, because it does work. I now have two windows open, one for each URL. (thanks!) The funny thing is that without the /d approach using my original syntax I get different results based on whether I have a pre-existing Internet Explorer instance open. </p>
<ul>
<li>If I do I get two new tabs added for
my two URLs (sweet!) </li>
<li>If not I get only one final tab for the second URL I passed in.</li>
</ul>
|
[
{
"answer_id": 188930,
"author": "Rodger Cooley",
"author_id": 5667,
"author_profile": "https://Stackoverflow.com/users/5667",
"pm_score": 6,
"selected": true,
"text": "@echo off\nstart /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.google.com\nstart /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.yahoo.com\n"
},
{
"answer_id": 1314704,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@echo off\n\nstart /d \"\" IEXPLORE.EXE www.google.com\n\nstart /d \"\" IEXPLORE.EXE www.yahoo.com\n"
},
{
"answer_id": 2683332,
"author": "Sam M",
"author_id": 322330,
"author_profile": "https://Stackoverflow.com/users/322330",
"pm_score": 1,
"selected": false,
"text": "start /d IEXPLORE.EXE www.google.com\nstart /d IEXPLORE.EXE www.yahoo.com\n start /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.google.com\nstart /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.yahoo.com\n"
},
{
"answer_id": 3689762,
"author": "Marcelo",
"author_id": 444926,
"author_profile": "https://Stackoverflow.com/users/444926",
"pm_score": 0,
"selected": false,
"text": "@echo off\nstart /d iexplore.exe http://google.com\nPING 1.1.1.1 -n 1 -w 2000 >NUL\nSTART /d iexplore.exe blablabla\n"
},
{
"answer_id": 3990606,
"author": "Emi",
"author_id": 483380,
"author_profile": "https://Stackoverflow.com/users/483380",
"pm_score": 0,
"selected": false,
"text": "start iexplore.exe website\nPING 1.1.1.1 -n 1 -w 2000 >NUL \nSTART /d iexplore.exe website\n"
},
{
"answer_id": 25169091,
"author": "Kevin Fegan",
"author_id": 606539,
"author_profile": "https://Stackoverflow.com/users/606539",
"pm_score": 3,
"selected": false,
"text": "var navOpenInNewWindow = 0x1;\nvar navOpenInNewTab = 0x800;\nvar navOpenInBackgroundTab = 0x1000;\n\nvar intLoop = 0;\nvar intArrUBound = 0;\nvar navFlags = navOpenInBackgroundTab;\nvar arrstrUrl = new Array(3);\nvar objIE;\n\n intArrUBound = arrstrUrl.length;\n\n arrstrUrl[0] = \"http://bing.com/\";\n arrstrUrl[1] = \"http://google.com/\";\n arrstrUrl[2] = \"http://msn.com/\";\n arrstrUrl[3] = \"http://yahoo.com/\";\n\n objIE = new ActiveXObject(\"InternetExplorer.Application\");\n objIE.Navigate2(arrstrUrl[0]);\n\n for (intLoop=1;intLoop<=intArrUBound;intLoop++) {\n\n objIE.Navigate2(arrstrUrl[intLoop], navFlags);\n\n }\n\n objIE.Visible = true;\n objIE = null;\n Option Explicit\n\nConst navOpenInNewWindow = &h1\nConst navOpenInNewTab = &h800\nConst navOpenInBackgroundTab = &h1000\n\nDim intLoop : intLoop = 0\nDim intArrUBound : intArrUBound = 0\nDim navFlags : navFlags = navOpenInBackgroundTab\n\nDim arrstrUrl(3)\nDim objIE\n\n intArrUBound = UBound(arrstrUrl)\n\n arrstrUrl(0) = \"http://bing.com/\"\n arrstrUrl(1) = \"http://google.com/\"\n arrstrUrl(2) = \"http://msn.com/\"\n arrstrUrl(3) = \"http://yahoo.com/\"\n\n set objIE = CreateObject(\"InternetExplorer.Application\")\n objIE.Navigate2 arrstrUrl(0)\n\n For intLoop = 1 to intArrUBound\n\n objIE.Navigate2 arrstrUrl(intLoop), navFlags\n\n Next\n\n objIE.Visible = True\n set objIE = Nothing\n cscript //nologo urls.vbs\ncscript //nologo urls.js\n var navOpenInNewWindow = 0x1;\nvar navOpenInNewTab = 0x800;\nvar navOpenInBackgroundTab = 0x1000;\n\nvar intLoop = 0;\nvar navFlags = navOpenInBackgroundTab;\nvar objIE;\nvar intArgsLength = WScript.Arguments.Length;\n\n if (intArgsLength == 0) {\n\n WScript.Echo(\"Missing parameters\");\n WScript.Quit(1);\n\n }\n\n objIE = new ActiveXObject(\"InternetExplorer.Application\");\n objIE.Navigate2(WScript.Arguments(0));\n\n for (intLoop=1;intLoop<intArgsLength;intLoop++) {\n\n objIE.Navigate2(WScript.Arguments(intLoop), navFlags);\n\n }\n\n objIE.Visible = true;\n objIE = null;\n Option Explicit\n\nConst navOpenInNewWindow = &h1\nConst navOpenInNewTab = &h800\nConst navOpenInBackgroundTab = &h1000\n\nDim intLoop\nDim navFlags : navFlags = navOpenInBackgroundTab\nDim objIE\n\n If WScript.Arguments.Count = 0 Then\n\n WScript.Echo \"Missing parameters\"\n WScript.Quit(1)\n\n End If\n\n set objIE = CreateObject(\"InternetExplorer.Application\")\n objIE.Navigate2 WScript.Arguments(0)\n\n For intLoop = 1 to (WScript.Arguments.Count-1)\n\n objIE.Navigate2 WScript.Arguments(intLoop), navFlags\n\n Next\n\n objIE.Visible = True\n set objIE = Nothing\n %errorlevel%=1 %errorlevel%=0 cscript //nologo urls.js \"http://bing.com/\" \"http://google.com/\" \"http://msn.com/\" \"http://yahoo.com/\"\ncscript //nologo urls.vbs \"http://bing.com/\" \"http://google.com/\" \"http://msn.com/\" \"http://yahoo.com/\"\n cscript //nologo urls.js \"bing.com\" \"google.com\" \"msn.com\" \"yahoo.com\"\ncscript //nologo urls.vbs \"bing.com\" \"google.com\" \"msn.com\" \"yahoo.com\"\n start /w \"\" wscript //nologo urls.js \"url1\" \"url2\" ...\nstart /w \"\" wscript //nologo urls.vbs \"url1\" \"url2\" ...\n JavaScript VB Script batch URLs cscript //nologo urls.vbs \"bing.com\" \"google.com\" \"msn.com\" \"yahoo.com\"\n"
},
{
"answer_id": 28475477,
"author": "Zlelik",
"author_id": 2940920,
"author_profile": "https://Stackoverflow.com/users/2940920",
"pm_score": 2,
"selected": false,
"text": "iexplore.exe\" -noframemerging http://google.com\niexplore.exe\" -noframemerging http://gmail.com\n -noframemerging -noframemerging -noframemerging -nomerge \"c:\\Program Files (x86)\\Internet Explorer\\iexplore.exe\" -noframemerging %1\n start run_ie.bat http://google.com\nstart run_ie.bat http://yahoo.com\n"
},
{
"answer_id": 62289934,
"author": "Daniel Hudsky",
"author_id": 7952824,
"author_profile": "https://Stackoverflow.com/users/7952824",
"pm_score": 0,
"selected": false,
"text": "start /d \"~\\iexplore.exe\" \"www.google.com\" & \nstart /d \"~\\iexplore.exe\" \"www.yahoo.com\" &\nstart /d \"~\\iexplore.exe\" \"www.blackholesurfer.com\" &\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10552/"
] |
188,853
|
<p>IIS is literally sending <code><?php ... ?></code> code to the browser rather then executing it.</p>
<p>But, only for the root <code>http://domain.com/index.php</code> file.</p>
<p>All other .php files in that folder and index.php files in subfolders execute as expected.</p>
<p>How can I get my root index.php code to execute?</p>
<hr>
<p>Update: "index.php" is a Default Document of my Web Site...</p>
<p><a href="http://img412.imageshack.us/img412/4130/defaultdocumentmt9.gif" rel="nofollow noreferrer">alt text http://img412.imageshack.us/img412/4130/defaultdocumentmt9.gif</a></p>
|
[
{
"answer_id": 188910,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 2,
"selected": false,
"text": "<? ... ?> short_open_tag = On"
},
{
"answer_id": 190877,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 3,
"selected": true,
"text": "index.php"
},
{
"answer_id": 7682810,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 2,
"selected": false,
"text": "<?"
},
{
"answer_id": 59555828,
"author": "crtr2012",
"author_id": 12637777,
"author_profile": "https://Stackoverflow.com/users/12637777",
"pm_score": 1,
"selected": false,
"text": "<%@ Page Language=\"C#\" %>\n\n<!DOCTYPE html>\n\n<script runat=\"server\">\n protected override void OnLoad(EventArgs e) {\n Response.Redirect(\"index.php\");\n }\n</script>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n<title>Title Of Your Website Here</title>\n</head>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
188,864
|
<p>So C# now allows you to use <code>default(Foo)</code> to get a recognized "not filled in yet"/empty instance of a class -- I'm not sure if it is exactly the same as <code>new Foo()</code> or not. Many library classes also implement a <code>Foo.Empty</code> property, which returns a similar instance. And of course any reference type can point to <code>null</code>. So really, what's the difference? When is one right or wrong? What's more consistent, or performs better? What tests should I use when checking if an object is conceptually "not ready for prime time"? Not everybody has <code>Foo.IsNullOrEmpty()</code>.</p>
|
[
{
"answer_id": 188893,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "default(Foo) New Foo(), null Foo.Empty() null"
},
{
"answer_id": 188932,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 5,
"selected": true,
"text": "default(Foo) Foo Foo Foo default() Foo default(Foo) SomeClass<T> MyMethod<T> String.Empty \"\""
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26286/"
] |
188,870
|
<p>Is there a library or acceptable method for sanitizing the input to an html page?</p>
<p>In this case I have a form with just a name, phone number, and email address. </p>
<p>Code must be C#.</p>
<p>For example:</p>
<p><code>"<script src='bobs.js'>John Doe</script>"</code> should become <code>"John Doe"</code></p>
|
[
{
"answer_id": 188984,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "string sql = \"UPDATE UserRecord SET FirstName='\" + txtFirstName.Text + \"' WHERE UserID=\" + UserID;\n SqlCommand cmd = new SqlCommand(\"UPDATE UserRecord SET FirstName= @FirstName WHERE UserID= @UserID\");\ncmd.Parameters.Add(\"@FirstName\", SqlDbType.VarChar, 50).Value = txtFirstName.Text;\ncmd.Parameters.Add(\"@UserID\", SqlDbType.Integer).Value = UserID;\n"
},
{
"answer_id": 19188104,
"author": "Jeremy Cook",
"author_id": 1945957,
"author_profile": "https://Stackoverflow.com/users/1945957",
"pm_score": 3,
"selected": false,
"text": "<script src='bobs.js'>John Doe</script> <script>"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2424/"
] |
188,886
|
<p>After my <code>form.Form</code> validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.</p>
<p>Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?</p>
<p>One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.</p>
|
[
{
"answer_id": 188904,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "_errors"
},
{
"answer_id": 188906,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "Form._errors ErrorList from django.forms.utils import ErrorList\nerrors = form._errors.setdefault(\"myfield\", ErrorList())\nerrors.append(u\"My error here\")\n django.forms.forms.NON_FIELD_ERRORS \"__all__\" \"myfield\""
},
{
"answer_id": 28058268,
"author": "rstuart85",
"author_id": 1713202,
"author_profile": "https://Stackoverflow.com/users/1713202",
"pm_score": 7,
"selected": false,
"text": "form.add_error() form._errors"
},
{
"answer_id": 60258267,
"author": "Muhammad Faizan Fareed",
"author_id": 7300865,
"author_profile": "https://Stackoverflow.com/users/7300865",
"pm_score": 3,
"selected": false,
"text": "form.add_error('fieldName', 'error description')\n form.add_error(None, 'error description')\n#Only pass None instead of field name\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
188,889
|
<p>how do I pass additional information to the service method returning the collection of items? I'll attempt to explain what I mean, I have 2 text boxes on a form, I need to fill out names, based of a specific account id in a database. so, I need to pass an integer to the getNamesForDropDown method. I couldn't figure out what to do, so I did the wrong thing, and used the CompletionSetCount to actually pass the information I needed:</p>
<pre><code>[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] getNamesForDropDown(string prefixText, int count)
{
String sql = "Select fldName From idAccountReps Where idAccount = " + count.ToString();
//... rest of the method removed, this should be enough code to understand
//... the evil wrongness I did.
}
</code></pre>
<p>in my front side aspx file, i set the CompletionSetCount based off the Account id the user is currently viewing on that page. </p>
<pre><code><ajaxtk:AutoCompleteExtender
runat="server"
ID="AC1"
TargetControlID="txtAccName"
ServiceMethod="getNamesForDropDown"
ServicePath="AccountInfo.asmx"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount='<%# Eval("idAccount") %>'
/>
</code></pre>
<p>So, that's definitely a wrong way... what would be the right way?</p>
|
[
{
"answer_id": 188903,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 2,
"selected": false,
"text": "string[] arguments = prefixText.Split(':'); \nint id = Int32.Parse(arguments[0]);\nstring text = arguments[1]; \n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
] |
188,892
|
<p>Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I'd like to match using UNIX style (glob) wildcards (* = any number of any character). </p>
<p>I'd like to use this for a end-user facing control. I fear that permitting all RegEx capabilities will be very confusing.</p>
|
[
{
"answer_id": 190297,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 6,
"selected": true,
"text": "Regex.Escape( wildcardExpression ).Replace( @\"\\*\", \".*\" ).Replace( @\"\\?\", \".\" );\n"
},
{
"answer_id": 3408256,
"author": "Doug Clutter",
"author_id": 340568,
"author_profile": "https://Stackoverflow.com/users/340568",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Text.RegularExpressions;\n\npublic class FileWildcard\n{\n Regex mRegex;\n\n public FileWildcard(string wildcard)\n {\n string pattern = string.Format(\"^{0}$\", Regex.Escape(wildcard)\n .Replace(@\"\\*\", \".*\").Replace(@\"\\?\", \".\"));\n mRegex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);\n }\n public bool IsMatch(string filenameToCompare)\n {\n return mRegex.IsMatch(filenameToCompare);\n }\n}\n FileWildcard w = new FileWildcard(\"*.txt\");\nif (w.IsMatch(\"Doug.Txt\"))\n Console.WriteLine(\"We have a match\");\n"
},
{
"answer_id": 3562062,
"author": "Dan Mangiarelli",
"author_id": 91993,
"author_profile": "https://Stackoverflow.com/users/91993",
"pm_score": 4,
"selected": false,
"text": "GetFiles() EnumerateDirectories() * ? class GlobTestMain\n{\n static void Main(string[] args)\n {\n string[] exes = Directory.GetFiles(Environment.CurrentDirectory, \"*.exe\");\n foreach (string file in exes)\n {\n Console.WriteLine(Path.GetFileName(file));\n }\n }\n}\n GlobTest.exe\nGlobTest.vshost.exe\n GetFiles() GetDirectories() GetFileSystemEntries() Enumerate"
},
{
"answer_id": 4146349,
"author": "mindplay.dk",
"author_id": 283851,
"author_profile": "https://Stackoverflow.com/users/283851",
"pm_score": 6,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nnamespace Whatever\n{\n public static class StringExtensions\n {\n /// <summary>\n /// Compares the string against a given pattern.\n /// </summary>\n /// <param name=\"str\">The string.</param>\n /// <param name=\"pattern\">The pattern to match, where \"*\" means any sequence of characters, and \"?\" means any single character.</param>\n /// <returns><c>true</c> if the string matches the given pattern; otherwise <c>false</c>.</returns>\n public static bool Like(this string str, string pattern)\n {\n return new Regex(\n \"^\" + Regex.Escape(pattern).Replace(@\"\\*\", \".*\").Replace(@\"\\?\", \".\") + \"$\",\n RegexOptions.IgnoreCase | RegexOptions.Singleline\n ).IsMatch(str);\n }\n }\n}\n if (File.Name.Like(\"*.jpg\"))\n{\n ....\n}\n"
},
{
"answer_id": 8094334,
"author": "Tony Edgecombe",
"author_id": 57094,
"author_profile": "https://Stackoverflow.com/users/57094",
"pm_score": 3,
"selected": false,
"text": "public static class Globber\n{\n public static bool Glob(this string value, string pattern)\n {\n int pos = 0;\n\n while (pattern.Length != pos)\n {\n switch (pattern[pos])\n {\n case '?':\n break;\n\n case '*':\n for (int i = value.Length; i >= pos; i--)\n {\n if (Glob(value.Substring(i), pattern.Substring(pos + 1)))\n {\n return true;\n }\n }\n return false;\n\n default:\n if (value.Length == pos || char.ToUpper(pattern[pos]) != char.ToUpper(value[pos]))\n {\n return false;\n }\n break;\n }\n\n pos++;\n }\n\n return value.Length == pos;\n }\n}\n Assert.IsTrue(\"text.txt\".Glob(\"*.txt\"));\n"
},
{
"answer_id": 37611277,
"author": "cleftheris",
"author_id": 61577,
"author_profile": "https://Stackoverflow.com/users/61577",
"pm_score": 5,
"selected": false,
"text": "dotnet core Microsoft.Extensions.FileSystemGlobbing wwwroot/app/**/*.module.js wwwroot/app/**/*.js .gitignore"
},
{
"answer_id": 39024810,
"author": "Bill Menees",
"author_id": 1882616,
"author_profile": "https://Stackoverflow.com/users/1882616",
"pm_score": 2,
"selected": false,
"text": "using Microsoft.VisualBasic;\nusing Microsoft.VisualBasic.CompilerServices;\n...\nbool isMatch = LikeOperator.LikeString(\"I love .NET!\", \"I love *\", CompareMethod.Text);\n// isMatch should be true.\n"
},
{
"answer_id": 42609077,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Matches files from folder _dir using glob file pattern.\n/// In glob file pattern matching * reflects to any file or folder name, ** refers to any path (including sub-folders).\n/// ? refers to any character.\n/// \n/// There exists also 3-rd party library for performing similar matching - 'Microsoft.Extensions.FileSystemGlobbing'\n/// but it was dragging a lot of dependencies, I've decided to survive without it.\n/// </summary>\n/// <returns>List of files matches your selection</returns>\nstatic public String[] matchFiles( String _dir, String filePattern )\n{\n if (filePattern.IndexOfAny(new char[] { '*', '?' }) == -1) // Speed up matching, if no asterisk / widlcard, then it can be simply file path.\n {\n String path = Path.Combine(_dir, filePattern);\n if (File.Exists(path))\n return new String[] { filePattern };\n return new String[] { };\n }\n\n String dir = Path.GetFullPath(_dir); // Make it absolute, just so we can extract relative path'es later on.\n String[] pattParts = filePattern.Replace(\"/\", \"\\\\\").Split('\\\\');\n List<String> scanDirs = new List<string>();\n scanDirs.Add(dir);\n\n //\n // By default glob pattern matching specifies \"*\" to any file / folder name, \n // which corresponds to any character except folder separator - in regex that's \"[^\\\\]*\"\n // glob matching also allow double astrisk \"**\" which also recurses into subfolders. \n // We split here each part of match pattern and match it separately.\n //\n for (int iPatt = 0; iPatt < pattParts.Length; iPatt++)\n {\n bool bIsLast = iPatt == (pattParts.Length - 1);\n bool bRecurse = false;\n\n String regex1 = Regex.Escape(pattParts[iPatt]); // Escape special regex control characters (\"*\" => \"\\*\", \".\" => \"\\.\")\n String pattern = Regex.Replace(regex1, @\"\\\\\\*(\\\\\\*)?\", delegate (Match m)\n {\n if (m.ToString().Length == 4) // \"**\" => \"\\*\\*\" (escaped) - we need to recurse into sub-folders.\n {\n bRecurse = true;\n return \".*\";\n }\n else\n return @\"[^\\\\]*\";\n }).Replace(@\"\\?\", \".\");\n\n if (pattParts[iPatt] == \"..\") // Special kind of control, just to scan upper folder.\n {\n for (int i = 0; i < scanDirs.Count; i++)\n scanDirs[i] = scanDirs[i] + \"\\\\..\";\n\n continue;\n }\n\n Regex re = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);\n int nScanItems = scanDirs.Count;\n for (int i = 0; i < nScanItems; i++)\n {\n String[] items;\n if (!bIsLast)\n items = Directory.GetDirectories(scanDirs[i], \"*\", (bRecurse) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n else\n items = Directory.GetFiles(scanDirs[i], \"*\", (bRecurse) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n\n foreach (String path in items)\n {\n String matchSubPath = path.Substring(scanDirs[i].Length + 1);\n if (re.Match(matchSubPath).Success)\n scanDirs.Add(path);\n }\n }\n scanDirs.RemoveRange(0, nScanItems); // Remove items what we have just scanned.\n } //for\n\n // Make relative and return.\n return scanDirs.Select( x => x.Substring(dir.Length + 1) ).ToArray();\n} //matchFiles\n"
},
{
"answer_id": 43209839,
"author": "Jon",
"author_id": 7319955,
"author_profile": "https://Stackoverflow.com/users/7319955",
"pm_score": 0,
"selected": false,
"text": " /// <summary>\n /// Finds files for the given glob path. It supports ** * and ? operators. It does not support !, [] or ![] operators\n /// </summary>\n /// <param name=\"path\">the path</param>\n /// <returns>The files that match de glob</returns>\n private ICollection<FileInfo> FindFiles(string path)\n {\n List<FileInfo> result = new List<FileInfo>();\n //The name of the file can be any but the following chars '<','>',':','/','\\','|','?','*','\"'\n const string folderNameCharRegExp = @\"[^\\<\\>:/\\\\\\|\\?\\*\" + \"\\\"]\";\n const string folderNameRegExp = folderNameCharRegExp + \"+\";\n //We obtain the file pattern\n string filePattern = Path.GetFileName(path);\n List<string> pathTokens = new List<string>(Path.GetDirectoryName(path).Split('\\\\', '/'));\n //We obtain the root path from where the rest of files will obtained \n string rootPath = null;\n bool containsWildcardsInDirectories = false;\n for (int i = 0; i < pathTokens.Count; i++)\n {\n if (!pathTokens[i].Contains(\"*\")\n && !pathTokens[i].Contains(\"?\"))\n {\n if (rootPath != null)\n rootPath += \"\\\\\" + pathTokens[i];\n else\n rootPath = pathTokens[i];\n pathTokens.RemoveAt(0);\n i--;\n }\n else\n {\n containsWildcardsInDirectories = true;\n break;\n }\n }\n if (Directory.Exists(rootPath))\n {\n //We build the regular expression that the folders should match\n string regularExpression = rootPath.Replace(\"\\\\\", \"\\\\\\\\\").Replace(\":\", \"\\\\:\").Replace(\" \", \"\\\\s\");\n foreach (string pathToken in pathTokens)\n {\n if (pathToken == \"**\")\n {\n regularExpression += string.Format(CultureInfo.InvariantCulture, @\"(\\\\{0})*\", folderNameRegExp);\n }\n else\n {\n regularExpression += @\"\\\\\" + pathToken.Replace(\"*\", folderNameCharRegExp + \"*\").Replace(\" \", \"\\\\s\").Replace(\"?\", folderNameCharRegExp);\n }\n }\n Regex globRegEx = new Regex(regularExpression, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);\n string[] directories = Directory.GetDirectories(rootPath, \"*\", containsWildcardsInDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n foreach (string directory in directories)\n {\n if (globRegEx.Matches(directory).Count > 0)\n {\n DirectoryInfo directoryInfo = new DirectoryInfo(directory);\n result.AddRange(directoryInfo.GetFiles(filePattern));\n }\n }\n\n }\n return result;\n }\n"
},
{
"answer_id": 68931309,
"author": "Ryan",
"author_id": 2266345,
"author_profile": "https://Stackoverflow.com/users/2266345",
"pm_score": 0,
"selected": false,
"text": ".Replace(\"\\*\", \".*\") Regex.Match ? * ** static string GlobbedPathToRegex(ReadOnlySpan<char> pattern, ReadOnlySpan<char> dirSeparatorChars)\n{\n StringBuilder builder = new StringBuilder();\n builder.Append('^');\n\n ReadOnlySpan<char> remainder = pattern;\n\n while (remainder.Length > 0)\n {\n int specialCharIndex = remainder.IndexOfAny('*', '?');\n\n if (specialCharIndex >= 0)\n {\n ReadOnlySpan<char> segment = remainder.Slice(0, specialCharIndex);\n\n if (segment.Length > 0)\n {\n string escapedSegment = Regex.Escape(segment.ToString());\n builder.Append(escapedSegment);\n }\n\n char currentCharacter = remainder[specialCharIndex];\n char nextCharacter = specialCharIndex < remainder.Length - 1 ? remainder[specialCharIndex + 1] : '\\0';\n\n switch (currentCharacter)\n {\n case '*':\n if (nextCharacter == '*')\n {\n // We have a ** glob expression\n // Match any character, 0 or more times.\n builder.Append(\"(.*)\");\n\n // Skip over **\n remainder = remainder.Slice(specialCharIndex + 2);\n }\n else\n {\n // We have a * glob expression\n // Match any character that isn't a dirSeparatorChar, 0 or more times.\n if(dirSeparatorChars.Length > 0) {\n builder.Append($\"([^{Regex.Escape(dirSeparatorChars.ToString())}]*)\");\n }\n else {\n builder.Append(\"(.*)\");\n }\n\n // Skip over *\n remainder = remainder.Slice(specialCharIndex + 1);\n }\n break;\n case '?':\n builder.Append(\"(.)\"); // Regex equivalent of ?\n\n // Skip over ?\n remainder = remainder.Slice(specialCharIndex + 1);\n break;\n }\n }\n else\n {\n // No more special characters, append the rest of the string\n string escapedSegment = Regex.Escape(remainder.ToString());\n builder.Append(escapedSegment);\n remainder = ReadOnlySpan<char>.Empty;\n }\n }\n\n builder.Append('$');\n\n return builder.ToString();\n}\n string testGlobPathInput = \"/Hello/Test/Blah/**/test*123.fil?\";\nstring globPathRegex = GlobbedPathToRegex(testGlobPathInput, \"/\"); // Could use \"\\\\/\" directory separator chars on Windows\n\nConsole.WriteLine($\"Globbed path: {testGlobPathInput}\");\nConsole.WriteLine($\"Regex conversion: {globPathRegex}\");\n\nstring testPath = \"/Hello/Test/Blah/All/Hail/The/Hypnotoad/test_somestuff_123.file\";\nConsole.WriteLine($\"Test Path: {testPath}\");\nvar regexGlobPathMatch = Regex.Match(testPath, globPathRegex);\n\nConsole.WriteLine($\"Match: {regexGlobPathMatch.Success}\");\n\nfor(int i = 0; i < regexGlobPathMatch.Groups.Count; i++) {\n Console.WriteLine($\"Group [{i}]: {regexGlobPathMatch.Groups[i]}\");\n}\n Globbed path: /Hello/Test/Blah/**/test*123.fil?\nRegex conversion: ^/Hello/Test/Blah/(.*)/test([^/]*)123\\.fil(.)$\nTest Path: /Hello/Test/Blah/All/Hail/The/Hypnotoad/test_somestuff_123.file\nMatch: True\nGroup [0]: /Hello/Test/Blah/All/Hail/The/Hypnotoad/test_somestuff_123.file\nGroup [1]: All/Hail/The/Hypnotoad\nGroup [2]: _somestuff_\nGroup [3]: e\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
188,894
|
<p>I have a .NET WinForms textbox for a phone number field. After allowing free-form text, I'd like to format the text as a "more readable" phone number after the user leaves the textbox. (Outlook has this feature for phone fields when you create/edit a contact)</p>
<ul>
<li>1234567 becomes 123-4567</li>
<li>1234567890 becomes (123) 456-7890</li>
<li>(123)456.7890 becomes (123) 456-7890</li>
<li>123.4567x123 becomes 123-4567 x123</li>
<li>etc</li>
</ul>
|
[
{
"answer_id": 188962,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 2,
"selected": false,
"text": "Regex regex = new Regex(@\"(?<areaCode>([\\d]{3}))?[\\s.-]?(?<leadingThree>([\\d]{3}))[\\s.-]?(?<lastFour>([\\d]{4}))[x]?(?<extension>[\\d]{1,})?\");\nstring phoneNumber = \"701 123-4567x324\";\n\nMatch phoneNumberMatch = regex.Match(phoneNumber);\nif(phoneNumberMatch.Success)\n{\n if (phoneNumberMatch.Groups[\"areaCode\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"areaCode\"].Value);\n }\n if (phoneNumberMatch.Groups[\"leadingThree\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"leadingThree\"].Value);\n }\n if (phoneNumberMatch.Groups[\"lastFour\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"lastFour\"].Value);\n }\n if (phoneNumberMatch.Groups[\"extension\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"extension\"].Value);\n }\n}\n"
},
{
"answer_id": 190180,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 1,
"selected": false,
"text": "Start: 123.4567x123\nLop: 123.4567\nStrip: 1234567\nFormat: 123-4567\nAdd: 123-4567 x123\n"
},
{
"answer_id": 1117478,
"author": "dividius",
"author_id": 133013,
"author_profile": "https://Stackoverflow.com/users/133013",
"pm_score": 0,
"selected": false,
"text": "public static string FormatPhoneNumber(string phone)\n{\n phone = Regex.Replace(phone, @\"[^\\d]\", \"\");\n if (phone.Length == 10)\n return Regex.Replace(phone,\n \"(?<ac>\\\\d{3})(?<pref>\\\\d{3})(?<num>\\\\d{4})\",\n \"(${ac}) ${pref}-${num}\");\n else if ((phone.Length < 16) && (phone.Length > 10))\n return Regex.Replace(phone,\n \"(?<ac>\\\\d{3})(?<pref>\\\\d{3})(?<num>\\\\d{4})(?<ext>\\\\d{1,5})\", \n \"(${ac}) ${pref}-${num} x${ext}\");\n else\n return string.Empty;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247/"
] |
188,896
|
<p>This has been driving me crazy. We have IIS (6) and windows 2008 and ActiveState Perl 5.10. For some reason whenever we do a warn or a carp it eventually corrupts the app pool. Of course, that's a pretty big deal since it means that our errors actually cause problems.</p>
<p>This happened with the previous version of Perl (5.8) and Windows (2003) and IIS (5.) Anyway, basically I put in a <code>carp</code> or a <code>warn</code> and I get an error message and then some garbage text. Any thoughts?</p>
|
[
{
"answer_id": 193496,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 0,
"selected": false,
"text": "BEGIN {\n open STDERR, '>> c:/iisError.log'\n or die \"Can't write to c:/issError.log: $!\\n\";\n binmode STDERR;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
188,913
|
<p>Is there a tool, method or setting in the standard VBA Editor to warn about variables that have been <code>Dim</code>'med, but aren't being used?</p>
|
[
{
"answer_id": 43231349,
"author": "Greedo",
"author_id": 6609896,
"author_profile": "https://Stackoverflow.com/users/6609896",
"pm_score": 4,
"selected": false,
"text": "Option Explicit Dim Dim Option Explicit"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
188,940
|
<p>I have a project with a formidable data access layer using LinqtoSQL for just about anything touching our databases. I needed to build a helper class that bridges some common crud operations from CLSA objects to LinqToSql ones. Everything has been operating swimmingly until I needed to do a truncate on a table and all I had were “delete” methods.</p>
<p>Uh-oh. A quick search reveals that some people are using YourContext.ExecuteCommand(), which is nice and all, but I am trying to go “t-sql-less” as much as possible these days.</p>
<p>Is there a LINQ way to perform a <a href="http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx" rel="nofollow noreferrer">truncate on a table</a>? Or am I just <a href="http://en.wikipedia.org/wiki/Clueless_(film)" rel="nofollow noreferrer">clueless</a>?</p>
|
[
{
"answer_id": 189023,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "yourDataContext.ExecuteCommand(\"TRUNCATE TABLE YourTable\");\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2213/"
] |
188,942
|
<p>I'm writing some cross-platform code between Windows and Mac.</p>
<p>If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse backwards?</p>
<p>This code workson the Mac but not on Windows (can't decrement beyond first element):</p>
<pre><code>list<DVFGfxObj*>::iterator iter = m_Objs.end();
for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?
{
}
</code></pre>
<p>this works on Windows:</p>
<pre><code>list<DVFGfxObj*>::iterator iter = m_Objs.end();
do{
iter--;
} while (*iter != *m_Objs.begin());
</code></pre>
<p>Is there another way to traverse backward that could be implemented in a for loop?</p>
|
[
{
"answer_id": 188948,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 7,
"selected": true,
"text": "reverse_iterator iterator rbegin() rend() begin() end() BOOST_FOREACH BOOST_REVERSE_FOREACH"
},
{
"answer_id": 188959,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 4,
"selected": false,
"text": "list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();\nfor( ; iter != m_Objs.rend(); ++iter)\n{\n}\n"
},
{
"answer_id": 188983,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 3,
"selected": false,
"text": "for (std::list<int>::reverse_iterator i = s.rbegin(); i != s.rend(); ++i)\n"
},
{
"answer_id": 188985,
"author": "steffenj",
"author_id": 15328,
"author_profile": "https://Stackoverflow.com/users/15328",
"pm_score": 3,
"selected": false,
"text": "list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();\nfor (; iter!= m_Objs.rend(); iter++)\n{\n}\n"
},
{
"answer_id": 223405,
"author": "mmocny",
"author_id": 29701,
"author_profile": "https://Stackoverflow.com/users/29701",
"pm_score": 4,
"selected": false,
"text": " reference\n operator*() const\n {\n_Iterator __tmp = current;\nreturn *--__tmp;\n }\n for ( iterator current = end() ; current != begin() ; /* Do nothing */ )\n{\n --current; // Unfortunately, you now need this here\n /* Do work */\n cout << *current << endl;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8761/"
] |
188,963
|
<p>I find it odd that in Visual C# 2008 Express edition, when you use the database explorer, your options are:</p>
<ol>
<li>Microsoft Access</li>
<li>SQL Server Compact 3.5, and </li>
<li>SQL Server Database File. </li>
</ol>
<p>BUT if you use Visual Web Developer 2008 Express, you can connect to a regular SQL Server, Oracle, ODBC, etc.</p>
<p>For people developing command-line or other C# apps that need to talk to a SQL Server database, do you really need to build your LINQ/Data Access code with one IDE (Visual Web Developer) and your program in another (Visual C#)? </p>
<p>It's not a hard workaround, but it seems weird. If Microsoft wanted to force you to upgrade to Visual Studio to connect to SQL Server, why would they include that feature in one of their free IDEs but not the other? I feel like I might be missing something (like how to do it all in Visual C#).</p>
|
[
{
"answer_id": 189058,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "system.data.SqlClient"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26624/"
] |
188,967
|
<p>I want to do this in code, not with ALT+F1.</p>
|
[
{
"answer_id": 188981,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 5,
"selected": false,
"text": "sp_help tablename \n Identity Seed Increment Not For Replication \n ----------- ------- ------------ ---------------------- \n userid 15500 1 0 \n"
},
{
"answer_id": 189025,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": false,
"text": "WHERE select\n a.name as TableName,\n b.name as IdentityColumn\nfrom\n sysobjects a inner join syscolumns b on a.id = b.id\nwhere\n columnproperty(a.id, b.name, 'isIdentity') = 1\n and objectproperty(a.id, 'isTable') = 1\n"
},
{
"answer_id": 189032,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 7,
"selected": true,
"text": "select columnproperty(object_id('mytable'),'mycolumn','IsIdentity')\n"
},
{
"answer_id": 38591783,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 1,
"selected": false,
"text": "select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns \njoin sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id\nwhere sys.all_objects.name = 'system_files'\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
188,968
|
<p>I would like a constraint on a SQL Server 2000 table column that is sort of a combination of a foreign key and a check constraint. The value of my column must exist in the other table, but I am only concerned with values in the other table where one of its columns equal a specified value. The simplified tables are:</p>
<pre>
import_table:
part_number varchar(30)
quantity int
inventory_master:
part_number varchar(30)
type char(1)
</pre>
<p>So I want to ensure the <code>part_number</code> exists in <code>inventory_master</code>, but only if the type is 'C'. Is this possible? Thanks.</p>
|
[
{
"answer_id": 188981,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 5,
"selected": false,
"text": "sp_help tablename \n Identity Seed Increment Not For Replication \n ----------- ------- ------------ ---------------------- \n userid 15500 1 0 \n"
},
{
"answer_id": 189025,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": false,
"text": "WHERE select\n a.name as TableName,\n b.name as IdentityColumn\nfrom\n sysobjects a inner join syscolumns b on a.id = b.id\nwhere\n columnproperty(a.id, b.name, 'isIdentity') = 1\n and objectproperty(a.id, 'isTable') = 1\n"
},
{
"answer_id": 189032,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 7,
"selected": true,
"text": "select columnproperty(object_id('mytable'),'mycolumn','IsIdentity')\n"
},
{
"answer_id": 38591783,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 1,
"selected": false,
"text": "select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns \njoin sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id\nwhere sys.all_objects.name = 'system_files'\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23976/"
] |
189,031
|
<p>Is there any way to set the same icon to all my forms without having to change one by one?
Something like when you setup <code>GlobalAssemblyInfo</code> for all your projects inside your solution.</p>
|
[
{
"answer_id": 189050,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": ": Form : System.Windows.Forms.Form : MyCustomForm"
},
{
"answer_id": 189618,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 3,
"selected": false,
"text": "public MyCustomForm()\n{\n Icon = GetExecutableIcon();\n}\n\npublic Icon GetExecutableIcon()\n{\n IntPtr large;\n IntPtr small;\n ExtractIconEx(Application.ExecutablePath, 0, out large, out small, 1);\n return Icon.FromHandle(small);\n}\n\n[DllImport(\"Shell32\")]\npublic static extern int ExtractIconEx(\n string sFile,\n int iIndex,\n out IntPtr piLargeVersion,\n out IntPtr piSmallVersion,\n int amountIcons);\n"
},
{
"answer_id": 199970,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": -1,
"selected": false,
"text": "form.icon = MainFrom.Icon\n Icon = MainFrom.Icon\n"
},
{
"answer_id": 7298614,
"author": "Loathing",
"author_id": 904156,
"author_profile": "https://Stackoverflow.com/users/904156",
"pm_score": 1,
"selected": false,
"text": "Owner public new Form Owner {\n set {\n this.Icon = (value == null ? null : value.Icon);\n base.Owner = value;\n }\n\n get {\n return base.Owner;\n }\n}\n"
},
{
"answer_id": 16559342,
"author": "Josua",
"author_id": 948287,
"author_profile": "https://Stackoverflow.com/users/948287",
"pm_score": 6,
"selected": false,
"text": "_Load this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);\n"
},
{
"answer_id": 30576632,
"author": "mbdavis",
"author_id": 2310450,
"author_profile": "https://Stackoverflow.com/users/2310450",
"pm_score": 2,
"selected": false,
"text": "public static class MyExtensionMethods\n{\n public static void SetAppIcon(this Form form)\n {\n form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);\n }\n}\n this.SetAppIcon();\n"
},
{
"answer_id": 42630079,
"author": "Roberto B",
"author_id": 2641447,
"author_profile": "https://Stackoverflow.com/users/2641447",
"pm_score": 3,
"selected": false,
"text": "FormUtils.SetDefaultIcon();\n static class Program\n{\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main(string[] args)\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n\n //Here it is.\n FormUtils.SetDefaultIcon();\n\n Application.Run(new Form());\n }\n}\n using System.Drawing;\nusing System.Windows.Forms;\n\npublic static class FormUtils\n{\n public static void SetDefaultIcon()\n {\n var icon = Icon.ExtractAssociatedIcon(EntryAssemblyInfo.ExecutablePath);\n typeof(Form)\n .GetField(\"defaultIcon\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)\n .SetValue(null, icon);\n }\n}\n using System.Security;\nusing System.Security.Permissions;\nusing System.Reflection;\nusing System.Diagnostics;\n\npublic static class EntryAssemblyInfo\n{\n private static string _executablePath;\n\n public static string ExecutablePath\n {\n get\n {\n if (_executablePath == null)\n {\n PermissionSet permissionSets = new PermissionSet(PermissionState.None);\n permissionSets.AddPermission(new FileIOPermission(PermissionState.Unrestricted));\n permissionSets.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));\n permissionSets.Assert();\n\n string uriString = null;\n var entryAssembly = Assembly.GetEntryAssembly();\n\n if (entryAssembly == null)\n uriString = Process.GetCurrentProcess().MainModule.FileName;\n else\n uriString = entryAssembly.CodeBase;\n\n PermissionSet.RevertAssert();\n\n if (string.IsNullOrWhiteSpace(uriString))\n throw new Exception(\"Can not Get EntryAssembly or Process MainModule FileName\");\n else\n {\n var uri = new Uri(uriString);\n if (uri.IsFile)\n _executablePath = string.Concat(uri.LocalPath, Uri.UnescapeDataString(uri.Fragment));\n else\n _executablePath = uri.ToString();\n }\n }\n\n return _executablePath;\n }\n }\n}\n"
},
{
"answer_id": 53911325,
"author": "Montfrooij",
"author_id": 2437753,
"author_profile": "https://Stackoverflow.com/users/2437753",
"pm_score": 1,
"selected": false,
"text": "m.set_form_defaults(this, \"Title here\");\n public void set_form_defaults(Form frm,string frmTitle)\n {\n\n frm.Icon = ((System.Drawing.Icon)(Properties.Resources.Logo_V2));\n frm.Text = frmTitle + \" \" + show_current_server();\n\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
189,043
|
<p>Is there any way to change the background color of the Solution Explorer in Visual Studio using a Theme? - or any other way for that matter?</p>
<p>I can change it by changing windows-wide color settings, but obviously that affects too much.</p>
|
[
{
"answer_id": 9183568,
"author": "user1195662",
"author_id": 1195662,
"author_profile": "https://Stackoverflow.com/users/1195662",
"pm_score": 3,
"selected": false,
"text": "#include <windows.h>\n#include \"psapi.h\"\n#include \"shlwapi.h\"\n#include \"commctrl.h\"\n\n\nCOLORREF clr = RGB(220,220,220);\n\nBOOL CALLBACK wenum( HWND hwnd, LPARAM lParam)\n{\n const UINT cb = 261;\n static wchar_t name[] = L\"SysTreeView32\",\n tmp[cb] = {0};\n if( ::GetClassNameW( hwnd, tmp, 260 ) && 0 == _wcsicmp( name, tmp ) )\n {\n ::SendMessageW( hwnd, TVM_SETBKCOLOR, 0, (LPARAM)clr );\n }\n\n return TRUE;\n}\n\nBOOL CALLBACK EnumTops(HWND hwnd, LPARAM lParam) \n{\n DWORD dwThreadId = 0, \n dwProcessId = 0;\n HINSTANCE hInstance;\n static wchar_t derVS[] = L\"devenv.exe\";\n wchar_t name[_MAX_PATH] = {0},\n *exe = 0;\n\n HANDLE hProcess;\n if (!hwnd) return TRUE; // Not a window\n if (!::IsWindowVisible(hwnd)) return TRUE; // Not visible\n\n if (!SendMessage(hwnd, WM_GETTEXT, sizeof(name), (LPARAM)name))\n return TRUE; // No window title\n dwThreadId = GetWindowThreadProcessId(hwnd, &dwProcessId);\n hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);\n if( !GetModuleFileNameEx(hProcess, 0, name, sizeof(name))) goto exit;\n\n exe = ::PathFindFileNameW( name );\n if( (void*)exe == (void*)name ) goto exit; // mhm? maybe not exit?\n\n if( _wcsicmp( derVS, exe ) ) goto exit;\n\n EnumChildWindows( hwnd, wenum, (LPARAM)hProcess );\n\nexit:\n CloseHandle(hProcess);\n int res = GetLastError();\n return res;\n}\n\nint wmain(int argc, wchar_t * argv[]) \n{\n if( argc >= 2 )\n {\n wchar_t *end = 0;\n long l = wcstol( argv[1], &end, 16 );\n clr = (DWORD)l;\n }\n ::EnumWindows(EnumTops, NULL);\n return 0;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410357/"
] |
189,055
|
<p>Typically you will find STL code like this:</p>
<pre><code>for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)
{
}
</code></pre>
<p>But we actually have the recommendation to write it like this:</p>
<pre><code>SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}
</code></pre>
<p>If you're worried about scoping, add enclosing braces:</p>
<pre><code>{
SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}
}
</code></pre>
<p>This is supposed to give a speed and efficiency gain, especially if you are programming consoles, because the .end() function is not called on each iteration of the loop. I just take the performance improvement for granted, it sounds reasonable but i don't know how much and it certainly depends on the type of container and actual STL implementation in use. But having used this style for a couple months now i actually prefer it over the first anyway.</p>
<p>The reason being readability: the for line is neat and tidy. With qualifiers and member variables in real production code it is quite easy to have <strong>really</strong> long for lines if you use the style in the first example. That's why i intentionally made it to have a horizontal scrollbar in this example, just so you see what i'm talking about. ;)</p>
<p>On the other hand, you suddenly introduce the Iter variables to the outer scope of the for loop. But then, at least in the environment i work in, the Iter would have been accessible in the outer scope even in the first example.</p>
<p>What is your take on this? Are there any pro's to the first style other than possibly limiting the scope of Iter?</p>
|
[
{
"answer_id": 189060,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": false,
"text": "typedef SomeClass::SomeContainer::iterator MyIter;\n\nfor (MyIter Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)\n{\n}\n"
},
{
"answer_id": 189068,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 0,
"selected": false,
"text": "for (auto iter = container.begin(); iter != container.end(); ++iter)\n{\n ...\n}\n\nauto iter = container.begin();\nauto endIter = container.end();\nfor (; iter != endIter; ++iter)\n{\n ...\n}\n"
},
{
"answer_id": 189074,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 0,
"selected": false,
"text": "SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(),\n IterEnd = m_SomeMemberContainerVar.end();\n\nfor(...)\n"
},
{
"answer_id": 189077,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 5,
"selected": true,
"text": "iterEnd = container.end() for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(),\n IterEnd = m_SomeMemberContainerVar.end();\n Iter != IterEnd;\n ++Iter)\n{\n}\n"
},
{
"answer_id": 189081,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "typedef SomeClass::SomeContainer::iterator sc_iter_t;\n\nfor (sc_iter_t Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)\n{\n}\n"
},
{
"answer_id": 189134,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 3,
"selected": false,
"text": "BOOST_FOREACH( ContainedType item, m_SomeMemberContainerVar )\n{\n mangle( item );\n}\n"
},
{
"answer_id": 189257,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 1,
"selected": false,
"text": "doStuff(coll.begin(), coll.end())\n template<typename InIt>\nvoid doStuff(InIt first, InIt last)\n{\n for (InIt curr = first; curr!= last; ++curr)\n {\n // Do stuff\n }\n }\n"
},
{
"answer_id": 194245,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "iter.end() end()"
},
{
"answer_id": 195090,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 1,
"selected": false,
"text": "typedef set<Apple> AppleSet;\ntypedef AppleSet::iterator AppleIter;\nAppleSet apples;\n\nfor (AppleIter it = apples.begin (); it != apples.end (); ++it)\n{\n ...\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
] |
189,062
|
<p>When I navigate on a website utilizing MasterPages, does the application know what page I am on? If so, does it store it in an object I can access?</p>
<p>The reason I am asking is so I can replace this:</p>
<pre><code>//masterpage
<div id="nav_main">
<ul><asp:ContentPlaceHolder ID="navigation" runat="server">
</asp:ContentPlaceHolder></ul>
</div>
//content page(s)
<asp:Content ContentPlaceHolderID="navigation" ID="theNav" runat="server">
<li><a href="default.aspx">Home</a></li>
<li id="current"><a href="faq.aspx">FAQ</a></li>
<li><a href="videos.aspx">Videos</a></li>
<li><a href="#">Button 4</a></li>
<li><a href="#">Button 5</a></li>
</asp:Content>
</code></pre>
<p>With a more elegant solution for the navigation, which highlights the link to the page by having the list item's ID set to "current". Currently each page recreates the navigation with its respective link's ID set to current.</p>
|
[
{
"answer_id": 189085,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 0,
"selected": false,
"text": "string type = this.Page.GetType().Name.ToString();\n"
},
{
"answer_id": 189179,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 3,
"selected": false,
"text": "string s = this.Page.Request.FilePath; // \"/Default.aspx\"\n"
},
{
"answer_id": 189258,
"author": "Blumer",
"author_id": 8117,
"author_profile": "https://Stackoverflow.com/users/8117",
"pm_score": 5,
"selected": true,
"text": "Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)\nSelect Cast thisUrl\n Case \"MenuItem1.aspx\"\n lnkMenu1.CssClass = \"Current\"\n Case \"MenuItem2.aspx\"\n lnkMenu2.CssClass = \"Current\"\nEnd Select\n"
},
{
"answer_id": 16061777,
"author": "Kush",
"author_id": 1324789,
"author_profile": "https://Stackoverflow.com/users/1324789",
"pm_score": -1,
"selected": false,
"text": "this.Page.Master\n"
},
{
"answer_id": 17526003,
"author": "Sarim Shekhani",
"author_id": 1178073,
"author_profile": "https://Stackoverflow.com/users/1178073",
"pm_score": 2,
"selected": false,
"text": "Page.ToString().Replace(\"ASP.\",\"\").Replace(\"_\",\".\")\n"
},
{
"answer_id": 23493551,
"author": "Wazi",
"author_id": 3443090,
"author_profile": "https://Stackoverflow.com/users/3443090",
"pm_score": 0,
"selected": false,
"text": "protected void HighlightSelectedMenuItem()\n {\n string s = this.Page.Request.FilePath; // \"/Default.aspx\"\n string nav;\n if (s.Contains(\"~\"))\n {\n s = s.Remove(s.IndexOf(\"~\"), 1);\n }\n\n foreach (MenuItem item in navMenu.Items)\n {\n if (item.NavigateUrl.Contains(\"~\"))\n {\n nav = item.NavigateUrl.Remove(item.NavigateUrl.IndexOf(\"~\"), 1);\n if (s == nav)\n {\n item.Selected = true;\n }\n }\n\n }\n }\n"
},
{
"answer_id": 26190128,
"author": "Meysam Ghorbani",
"author_id": 3988122,
"author_profile": "https://Stackoverflow.com/users/3988122",
"pm_score": 0,
"selected": false,
"text": "string s = this.Page.GetType().FullName;\nstring[] array = s.Split('_');\nint count = array.Count<String>();\nstring currentPage = array[count - 2];\n"
},
{
"answer_id": 50665209,
"author": "eblancode",
"author_id": 8963333,
"author_profile": "https://Stackoverflow.com/users/8963333",
"pm_score": 1,
"selected": false,
"text": "this.Page.Title\n"
},
{
"answer_id": 50741897,
"author": "masoud Cheragee",
"author_id": 720242,
"author_profile": "https://Stackoverflow.com/users/720242",
"pm_score": 1,
"selected": false,
"text": "string thisURL = Request.Url.Segments[Request.Url.Segments.Length - 1];\n if (thisURL.ToLower()== \"default.aspx\") li1.Attributes.Add(\"class\",\"yekan active\");\n if (thisURL.ToLower() == \"experts.aspx\") li2.Attributes.Add(\"class\", \"yekan active\");\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
189,079
|
<p>I'm having some minor problems with some animations I'm trying to set up. I have a couple divs stacked on top of each other kind of like this.</p>
<pre><code><div id="div1">
Stuff...
</div>
<div id="div2">
More Stuff...
</div>
</code></pre>
<p>Each of these divs has a drop shadow applied to it via jQuery plugin (jquery.dropshadow.js).</p>
<p>The problem occurs when I expand one of the divs using some kind of animation. The shadow does not update with the size of the div. I can redraw the shadow in the callback of the animation but still looks pretty joggy.</p>
<p>Is there a way that I can update the status of my shadows periodically throughout the course of the animation or can anyone recommend a better drop shadow library that would fix the problem? It doesn't have to be jQuery plugin.</p>
|
[
{
"answer_id": 189438,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "$('#foo').slideToggle().ready(function(){\n $('#foo').dropShadow(options); \n});\n slideToggle"
},
{
"answer_id": 190158,
"author": "Rudi",
"author_id": 22830,
"author_profile": "https://Stackoverflow.com/users/22830",
"pm_score": 2,
"selected": false,
"text": " <style type=\"text/css\">\n #div1 { width: 50px; }\n </style>\n\n <div id=\"div1\">\n <p>Here is a lot of stuff. Stuff stuff stuff.</p>\n</div>\n\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#div1\").dropShadow();\n $(\"#div1\").click(function() {\n $(\"#div1, #div1 + .dropShadow .dropShadow\").animate({ width: \"400px\" }, 1500);\n });\n });\n </script>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17881/"
] |
189,087
|
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p>
<pre><code>for i in range(len(alist)):
for j in range(len(alist[i])):
if alist[i][j].isWhatever:
blist[i][j].doSomething()
</code></pre>
<p>Is there a nicer way to do something like this?</p>
|
[
{
"answer_id": 189096,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": -1,
"selected": false,
"text": "for d1 in alist\n for d2 in d1\n if d2 = \"whatever\"\n do_my_thing()\n"
},
{
"answer_id": 189111,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "for a_row,b_row in zip(alist, blist):\n for a_item, b_item in zip(a_row,b_row):\n if a_item.isWhatever:\n b_item.doSomething()\n # Initialise 3d list:\nalist = [ [[A(a_args), B(b_args)] for i in xrange(WIDTH)] for j in xrange(HEIGHT)]\n\n# Process it:\nfor row in xlist:\n for a,b in row:\n if a.isWhatever(): \n b.doSomething()\n ( Chance isWhatever is True )\nMethod 100% 50% 10% 1%\n\n3d 3.422 2.151 1.067 0.824\nizip 3.647 2.383 1.282 0.985\noriginal 5.422 3.426 1.891 1.534\n"
},
{
"answer_id": 189165,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 5,
"selected": true,
"text": "def grid_objects(alist, blist):\n for i in range(len(alist)):\n for j in range(len(alist[i])):\n yield(alist[i][j], blist[i][j])\n for (a, b) in grid_objects(alist, blist):\n if a.is_whatever():\n b.do_something()\n"
},
{
"answer_id": 189234,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 2,
"selected": false,
"text": "izip from itertools import izip\nfor a, b in (pair for (aline, bline) in izip(alist, blist) \n for pair in izip(aline, bline)):\n if a.isWhatever:\n b.doSomething()\n for alist blist (aline, bline) izip pair zip izip"
},
{
"answer_id": 189270,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 2,
"selected": false,
"text": "for i, arow in enumerate(alist):\n for j, aval in enumerate(arow):\n if aval.isWhatever():\n blist[i][j].doSomething()\n"
},
{
"answer_id": 189348,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "for a_row, b_row in itertools.izip(alist, blist):\n for a_item, b_item in itertools.izip(a_row, b_row):\n a_item.b_item= b_item\n __slots__ for a_row in alist:\n for a_item in a_row:\n if a_item.isWhatever():\n a_item.b_item.doSomething()\n"
},
{
"answer_id": 189497,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "izip zip zip izip zip from itertools import izip\nfor a_row,b_row in izip(alist, blist):\n for a_item, b_item in izip(a_row,b_row):\n if a_item.isWhatever:\n b_item.doSomething()\n"
},
{
"answer_id": 190904,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 2,
"selected": false,
"text": "from numpy import array, sqrt, float32, newaxis\ndef evolve(points, velocities, edges, timestep=0.01, charge=0.1, mass=1., edgelen=0.5, dampen=0.95):\n \"\"\"Evolve a n body system of electrostatically repulsive nodes connected by\n springs by one timestep.\"\"\"\n velocities *= dampen\n\n # calculate matrix of distance vectors between all points and their lengths squared\n dists = array([[p2 - p1 for p2 in points] for p1 in points])\n l_2 = (dists*dists).sum(axis=2)\n\n # make the diagonal 1's to avoid division by zero\n for i in xrange(points.shape[0]):\n l_2[i,i] = 1\n\n l_2_inv = 1/l_2\n l_3_inv = l_2_inv*sqrt(l_2_inv)\n\n # repulsive force: distance vectors divided by length cubed, summed and multiplied by scale\n scale = timestep*charge*charge/mass\n velocities -= scale*(l_3_inv[:,:,newaxis].repeat(points.shape[1], axis=2)*dists).sum(axis=1)\n\n # calculate spring contributions for each point\n for idx, (point, outedges) in enumerate(izip(points, edges)):\n edgevecs = point - points.take(outedges, axis=0)\n edgevec_lens = sqrt((edgevecs*edgevecs).sum(axis=1))\n scale = timestep/mass\n velocities[idx] += (edgevecs*((((edgelen*scale)/edgevec_lens - scale))[:,newaxis].repeat(points.shape[1],axis=1))).sum(axis=0)\n\n # move points to new positions\n points += velocities*timestep\n"
},
{
"answer_id": 193825,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "a.isWhatever a_index = set((i,j) \n for i,arow in enumerate(a) \n for j,a in enumerate(arow) \n if a.IsWhatever())\n for (i,j) in a_index:\n b[i][j].doSomething()\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25680/"
] |
189,094
|
<p>How can I get list all the files within a folder recursively in Java? </p>
|
[
{
"answer_id": 189108,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": false,
"text": "import java.io.File;\npublic class Test {\n public static void main( String [] args ) {\n File actual = new File(\".\");\n for( File f : actual.listFiles()){\n System.out.println( f.getName() );\n }\n }\n}\n"
},
{
"answer_id": 189739,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 7,
"selected": true,
"text": "public static void main(String[] args) {\n Collection<File> all = new ArrayList<File>();\n addTree(new File(\".\"), all);\n System.out.println(all);\n}\n\nstatic void addTree(File file, Collection<File> all) {\n File[] children = file.listFiles();\n if (children != null) {\n for (File child : children) {\n all.add(child);\n addTree(child, all);\n }\n }\n}\n static void addTree(Path directory, Collection<Path> all)\n throws IOException {\n try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {\n for (Path child : ds) {\n all.add(child);\n if (Files.isDirectory(child)) {\n addTree(child, all);\n }\n }\n }\n}\n static void addTree(Path directory, final Collection<Path> all)\n throws IOException {\n Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)\n throws IOException {\n all.add(file);\n return FileVisitResult.CONTINUE;\n }\n });\n}\n"
},
{
"answer_id": 192001,
"author": "Leonel",
"author_id": 15649,
"author_profile": "https://Stackoverflow.com/users/15649",
"pm_score": 3,
"selected": false,
"text": "FileFilter import java.io.File;\nimport java.io.FileFilter;\n\npublic class ListFiles {\n public File[] findDirectories(File root) { \n return root.listFiles(new FileFilter() {\n public boolean accept(File f) {\n return f.isDirectory();\n }});\n }\n\n public File[] findFiles(File root) {\n return root.listFiles(new FileFilter() {\n public boolean accept(File f) {\n return f.isFile();\n }});\n }\n}\n"
},
{
"answer_id": 10496532,
"author": "Ohad Dan",
"author_id": 1381751,
"author_profile": "https://Stackoverflow.com/users/1381751",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) throws IOException {\n printTree(0, new File(\"START/FROM/DIR\"));\n}\n\nstatic void printTree(int depth, File file) throws IOException { \n StringBuilder indent = new StringBuilder();\n String name = file.getName();\n\n for (int i = 0; i < depth; i++) {\n indent.append(\".\");\n }\n\n //Pretty print for directories\n if (file.isDirectory()) { \n System.out.println(indent.toString() + \"|\");\n if(isPrintName(name)){\n System.out.println(indent.toString() + \"*\" + file.getName() + \"*\");\n }\n }\n //Print file name\n else if(isPrintName(name)) {\n System.out.println(indent.toString() + file.getName()); \n }\n //Recurse children\n if (file.isDirectory()) { \n File[] files = file.listFiles(); \n for (int i = 0; i < files.length; i++){\n printTree(depth + 4, files[i]);\n } \n }\n}\n\n//Exclude some file names\nstatic boolean isPrintName(String name){\n if (name.charAt(0) == '.') {\n return false;\n }\n if (name.contains(\"svn\")) {\n return false;\n }\n //.\n //. Some more exclusions\n //.\n return true;\n}\n"
},
{
"answer_id": 15110811,
"author": "Rohit sharma",
"author_id": 2115098,
"author_profile": "https://Stackoverflow.com/users/2115098",
"pm_score": 2,
"selected": false,
"text": "public static void directory(File dir) {\n File[] files = dir.listFiles();\n for (File file : files) {\n System.out.println(file.getAbsolutePath());\n if (file.listFiles() != null)\n directory(file); \n }\n} \n dir c:\\"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
] |
189,113
|
<p>I moved a <a href="http://en.wikipedia.org/wiki/WordPress" rel="noreferrer">WordPress</a> installation to a new folder on a Windows/<a href="http://en.wikipedia.org/wiki/Internet_Information_Services" rel="noreferrer">IIS</a> server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format:</p>
<pre class="lang-none prettyprint-override"><code>http:://www.example.com/OLD_FOLDER/index.php/post-title/
</code></pre>
<p>I can't figure out how to grab the <code>/post-title/</code> part of the URL.</p>
<p><code>$_SERVER["REQUEST_URI"]</code> - which everyone seems to recommend - is returning an empty string. <code>$_SERVER["PHP_SELF"]</code> is just returning <code>index.php</code>. Why is this, and how can I fix it?</p>
|
[
{
"answer_id": 189123,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": false,
"text": "$_SERVER['REQUEST_URI']"
},
{
"answer_id": 189125,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "$_SERVER['PATH_INFO']\n $_SERVER['REQUEST_URI']"
},
{
"answer_id": 190770,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 2,
"selected": false,
"text": "index.php"
},
{
"answer_id": 1229827,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 3,
"selected": false,
"text": "function get_current_url() {\n\n $protocol = 'http';\n if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {\n $protocol .= 's';\n $protocol_port = $_SERVER['SERVER_PORT'];\n } else {\n $protocol_port = 80;\n }\n\n $host = $_SERVER['HTTP_HOST'];\n $port = $_SERVER['SERVER_PORT'];\n $request = $_SERVER['PHP_SELF'];\n $query = isset($_SERVER['argv']) ? substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1) : '';\n\n $toret = $protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request . (empty($query) ? '' : '?' . $query);\n\n return $toret;\n}\n"
},
{
"answer_id": 1229924,
"author": "Tyler Carter",
"author_id": 58088,
"author_profile": "https://Stackoverflow.com/users/58088",
"pm_score": 6,
"selected": false,
"text": "$pageURL = (@$_SERVER[\"HTTPS\"] == \"on\") ? \"https://\" : \"http://\";\nif ($_SERVER[\"SERVER_PORT\"] != \"80\")\n{\n $pageURL .= $_SERVER[\"SERVER_NAME\"].\":\".$_SERVER[\"SERVER_PORT\"].$_SERVER[\"REQUEST_URI\"];\n} \nelse \n{\n $pageURL .= $_SERVER[\"SERVER_NAME\"].$_SERVER[\"REQUEST_URI\"];\n}\nreturn $pageURL;\n"
},
{
"answer_id": 2084669,
"author": "Joomla Developers",
"author_id": 253024,
"author_profile": "https://Stackoverflow.com/users/253024",
"pm_score": 0,
"selected": false,
"text": "<?php\n function currentPageURL() {\n $curpageURL = 'http';\n if ($_SERVER[\"HTTPS\"] == \"on\") {\n $curpageURL.= \"s\";\n }\n $curpageURL.= \"://\";\n if ($_SERVER[\"SERVER_PORT\"] != \"80\") {\n $curpageURL.= $_SERVER[\"SERVER_NAME\"].\":\".$_SERVER[\"SERVER_PORT\"].$_SERVER[\"REQUEST_URI\"];\n } \n else {\n $curpageURL.= $_SERVER[\"SERVER_NAME\"].$_SERVER[\"REQUEST_URI\"];\n }\n return $curpageURL;\n }\n echo currentPageURL();\n?>\n"
},
{
"answer_id": 3900684,
"author": "Avery",
"author_id": 471563,
"author_profile": "https://Stackoverflow.com/users/471563",
"pm_score": 3,
"selected": false,
"text": "function my_url(){\n $url = (!empty($_SERVER['HTTPS'])) ?\n \"https://\".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :\n \"http://\".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];\n echo $url;\n}\n my_url"
},
{
"answer_id": 4484061,
"author": "Sureshkumar",
"author_id": 547822,
"author_profile": "https://Stackoverflow.com/users/547822",
"pm_score": 3,
"selected": false,
"text": "class VirtualDirectory\n{\n var $protocol;\n var $site;\n var $thisfile;\n var $real_directories;\n var $num_of_real_directories;\n var $virtual_directories = array();\n var $num_of_virtual_directories = array();\n var $baseURL;\n var $thisURL;\n\n function VirtualDirectory()\n {\n $this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';\n $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];\n $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);\n $this->real_directories = $this->cleanUp(explode(\"/\", str_replace($this->thisfile, \"\", $_SERVER['PHP_SELF'])));\n $this->num_of_real_directories = count($this->real_directories);\n $this->virtual_directories = array_diff($this->cleanUp(explode(\"/\", str_replace($this->thisfile, \"\", $_SERVER['REQUEST_URI']))),$this->real_directories);\n $this->num_of_virtual_directories = count($this->virtual_directories);\n $this->baseURL = $this->site . \"/\" . implode(\"/\", $this->real_directories) . \"/\";\n $this->thisURL = $this->baseURL . implode(\"/\", $this->virtual_directories) . \"/\";\n }\n\n function cleanUp($array)\n {\n $cleaned_array = array();\n foreach($array as $key => $value)\n {\n $qpos = strpos($value, \"?\");\n if($qpos !== false)\n {\n break;\n }\n if($key != \"\" && $value != \"\")\n {\n $cleaned_array[] = $value;\n }\n }\n return $cleaned_array;\n }\n}\n\n$virdir = new VirtualDirectory();\necho $virdir->thisURL;\n"
},
{
"answer_id": 6000346,
"author": "beniwal",
"author_id": 753387,
"author_profile": "https://Stackoverflow.com/users/753387",
"pm_score": 2,
"selected": false,
"text": "$_SERVER['REQUEST_URI'] $_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];\n"
},
{
"answer_id": 10133524,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 5,
"selected": false,
"text": "'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']\n HTTP_HOST SERVER_NAME 'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']\n ServerName VirtualHost $_SERVER['HTTP_HOST'] vhost .htaccess RewriteEngine On\nRewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$\nRewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]\n#sometimes u may need to omit this slash ^ depending on your server\n"
},
{
"answer_id": 19483052,
"author": "Gajus",
"author_id": 368691,
"author_profile": "https://Stackoverflow.com/users/368691",
"pm_score": 0,
"selected": false,
"text": "http_build_url($_SERVER['REQUEST_URI']);\n http_build_url REQUEST_URI"
},
{
"answer_id": 20123709,
"author": "SpYk3HH",
"author_id": 900807,
"author_profile": "https://Stackoverflow.com/users/900807",
"pm_score": 1,
"selected": false,
"text": "if (!function_exists('base_url')) {\n function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){\n if (isset($_SERVER['HTTP_HOST'])) {\n $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';\n $hostname = $_SERVER['HTTP_HOST'];\n $dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);\n\n $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);\n $core = $core[0];\n\n $tmplt = $atRoot ? ($atCore ? \"%s://%s/%s/\" : \"%s://%s/\") : ($atCore ? \"%s://%s/%s/\" : \"%s://%s%s\");\n $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);\n $base_url = sprintf( $tmplt, $http, $hostname, $end );\n }\n else $base_url = 'http://localhost/';\n\n if ($parse) {\n $base_url = parse_url($base_url);\n if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';\n }\n\n return $base_url;\n }\n}\n // A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:\n\necho base_url(); // Will produce something like: http://stackoverflow.com/questions/189113/\necho base_url(TRUE); // Will produce something like: http://stackoverflow.com/\necho base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/\n\n// And finally:\necho base_url(NULL, NULL, TRUE);\n// Will produce something like:\n// array(3) {\n// [\"scheme\"]=>\n// string(4) \"http\"\n// [\"host\"]=>\n// string(12) \"stackoverflow.com\"\n// [\"path\"]=>\n// string(35) \"/questions/189113/\"\n// }\n"
},
{
"answer_id": 27585905,
"author": "Hüseyin Yağlı",
"author_id": 531524,
"author_profile": "https://Stackoverflow.com/users/531524",
"pm_score": 0,
"selected": false,
"text": "$_SERVER[\"SCRIPT_URI\"]\n"
},
{
"answer_id": 39231892,
"author": "user1949536",
"author_id": 1949536,
"author_profile": "https://Stackoverflow.com/users/1949536",
"pm_score": 0,
"selected": false,
"text": "5.3 /*\n * Compatibility with multiple host headers.\n * Support of \"Reverse Proxy\" configurations.\n *\n * Michael Jett <mjett@mitre.org>\n */\n\nfunction base_url() {\n\n $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] \n ?: @$_SERVER['REQUEST_SCHEME']\n ?: ((isset($_SERVER[\"HTTPS\"]) && $_SERVER[\"HTTPS\"] == \"on\") ? \"https\" : \"http\");\n\n $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT'])\n ?: @intval($_SERVER[\"SERVER_PORT\"])\n ?: (($protocol === 'https') ? 443 : 80);\n\n $host = @explode(\":\", $_SERVER['HTTP_HOST'])[0]\n ?: @$_SERVER['SERVER_NAME']\n ?: @$_SERVER['SERVER_ADDR'];\n\n // Don't include port if it's 80 or 443 and the protocol matches\n $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;\n\n return sprintf('%s://%s%s/%s', $protocol, $host, $port, @trim(reset(explode(\"?\", $_SERVER['REQUEST_URI'])), '/'));\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19487/"
] |
189,118
|
<p>There are so many little options and settings within Microsoft Visual Studio. Which adjustments do you recommend to others?</p>
|
[
{
"answer_id": 189173,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "Edit.GoToDefinition"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
189,121
|
<p>using MVP, what is the normal order of construction and dependency injection.</p>
<p>normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have:</p>
<ol>
<li>A Service that multiple views need to listen to events on.</li>
<li>Multiple views all pointing to the same data model cache.</li>
</ol>
<p>can someone display a normal flow of info from a user click to data coming back in a service from a server.</p>
|
[
{
"answer_id": 191182,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 5,
"selected": true,
"text": "public interface IView<TPresenter>\n{\n TPresenter Presenter { get; set; }\n}\n\npublic interface IPresenter<TView, TPresenter>\n where TView : IView<TPresenter>\n where TPresenter : IPresenter<TView, TPresenter>\n{\n TView View { get; set; }\n}\n public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter>\n where TView : IView<TPresenter>\n where TPresenter : class, IPresenter<TView, TPresenter>\n{\n protected TView view;\n\n public TView View\n {\n get { return this.view; }\n set\n {\n this.view = value;\n this.view.Presenter = this as TPresenter;\n }\n }\n}\n public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>\n{\n //...\n}\n IMyView IView MyView MyPresenter MyView IMyView MyPresenter MyPresenter AbstractPresenter.View"
},
{
"answer_id": 845750,
"author": "Mike Post",
"author_id": 20788,
"author_profile": "https://Stackoverflow.com/users/20788",
"pm_score": 3,
"selected": false,
"text": "public interface IView\n{\n ...\n event Action SomeEvent;\n event EventHandler Disposed;\n ...\n}\n\n// Note that the IView.Disposed event is implemented by the \n// UserControl.Disposed event. \npublic class View : UserControl, IView\n{\n public event Action SomeEvent;\n\n public View()\n {\n var presenter = new Presenter(this);\n }\n}\n\npublic interface IModel\n{\n ...\n event Action ModelChanged;\n ...\n}\n\npublic class Model : IModel\n{\n ...\n public event Action ModelChanged;\n ...\n}\n\npublic class Presenter\n{\n private IView MyView;\n private IModel MyModel;\n\n public Presenter(View view)\n {\n MyView = view;\n MyView.SomeEvent += RespondToSomeEvent;\n MyView.Disposed += ViewDisposed;\n\n MyModel = new Model();\n MyModel.ModelChanged += RespondToModelChanged;\n }\n\n // You could take this a step further by implementing IDisposable on the\n // presenter and having View.Dispose() trigger Presenter.Dispose().\n private void ViewDisposed(object sender, EventArgs e)\n {\n MyView.SomeEvent -= RespondToSomeEvent;\n MyView.Disposed -= ViewDisposed;\n MyView = null;\n\n MyModel.Modelchanged -= RespondToModelChanged;\n MyModel = null;\n }\n}\n"
},
{
"answer_id": 9917053,
"author": "Pradeep",
"author_id": 1299458,
"author_profile": "https://Stackoverflow.com/users/1299458",
"pm_score": 0,
"selected": false,
"text": "interface IEmployee\n{\n int EmployeeId {get;}\n string FirstName {get;}\n string LastName {get;}\n}\ninterface IEmployeeRepository\n{\n void SaveEmployee(IEmployee employee);\n IEmployee GetEmployeeById(int employeeId);\n IEmployee[] Employees { get; }\n}\ninterface IEmployeeView\n{\n event Action<IEmployee> OnEmployeeSaved;\n}\n\ninterface IEmployeeController\n{\n IEmployeeView View {get;}\n IEmployeeRepository Repository {get;}\n IEmployee[] Employees {get;} \n}\n\npartial class EmployeeView: UserControl, IEmployeeView\n{\n public EmployeeView()\n {\n InitComponent();\n }\n}\nclass EmployeeController:IEmployeeController\n{\n private IEmployeeView view;\n private IEmployeeRepository repository;\n public EmployeeController(IEmployeeView view, IEmployeeRepository repository)\n {\n this.repository = repository;\n this.view = view;\n this.view.OnEmployeeSaved+=new Action<IEmployee>(view_OnEmployeeSaved);\n }\n\n void view_OnEmployeeSaved(IEmployee employee)\n {\n repository.SaveEmployee(employee);\n }\n public IEmployeeView View \n {\n get\n { \n return view;\n }\n }\n public IEmployeeRepository Repository\n {\n get\n {\n return repository;\n }\n }\n\n public IEmployee[] Employees\n {\n get \n {\n return repository.Employees;\n }\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
189,148
|
<p>(See related question: <a href="https://stackoverflow.com/questions/162917/how-do-i-report-an-error-midway-through-a-chunked-http-repsonse-without-closing">How do I report an error midway through a chunked http repsonse without closing the connection?</a>)</p>
<p>In my case, the #1 desire is for the browser to display an error message. No matter how uninformative.</p>
<p>Closing the ServletResponse outputStream obviously doesn't work. Neither does throwing an exception, even if I don't close first (tested on Tomcat 6.0.16). I think that what I want is either a RST packet, FIN in the middle of a chunk, or badly formed chunk headers.</p>
<p>After that I can worry about how various browsers respond.</p>
<p>Edited for clarification: This is for a file download, perhaps several gigabytes of binary data. I can't make certain that all of the data can be successfully read or decrypted before I have to start sending some of it.</p>
|
[
{
"answer_id": 189285,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\"> alert(\"Processing failed!\"); </script>\n"
},
{
"answer_id": 206207,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 2,
"selected": true,
"text": "public class Servlet extends HttpServlet {\n public static final int ARRAY_SIZE = 65536;\n private static final int SEND_COUNT = 100000;\n\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {\n\n String testData = \"This is a fairly long piece of test text, running on and on and on, over and over.\";\n\n final ServletOutputStream outputStream = response.getOutputStream();\n for (int i = 0; i < SEND_COUNT; ++i) {\n outputStream.println(testData);\n }\n throw new ServletException(\"Break it now\");\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22704/"
] |
189,156
|
<p>Running FxCop on my code, I get this warning:</p>
<blockquote>
<p>Microsoft.Maintainability :
'FooBar.ctor is coupled with 99
different types from 9 different
namespaces. Rewrite or refactor the
method to decrease its class coupling,
or consider moving the method to one
of the other types it is tightly
coupled with. A class coupling above
40 indicates poor maintainability, a
class coupling between 40 and 30
indicates moderate maintainability,
and a class coupling below 30
indicates good maintainability.</p>
</blockquote>
<p>My class is a landing zone for all messages from the server. The server can send us messages of different EventArgs types:</p>
<pre><code>public FooBar()
{
var messageHandlers = new Dictionary<Type, Action<EventArgs>>();
messageHandlers.Add(typeof(YouHaveBeenLoggedOutEventArgs), HandleSignOut);
messageHandlers.Add(typeof(TestConnectionEventArgs), HandleConnectionTest);
// ... etc for 90 other types
}
</code></pre>
<p>The "HandleSignOut" and "HandleConnectionTest" methods have little code in them; they usually pass the work off to a function in another class.</p>
<p>How can I make this class better with lower coupling?</p>
|
[
{
"answer_id": 189199,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing Spring.Context.Support;\n\nnamespace Example\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n MessageBroker broker = (MessageBroker) ContextRegistry.GetContext()[\"messageBroker\"];\n broker.Dispatch(null, new Type1EventArgs());\n broker.Dispatch(null, new Type2EventArgs());\n broker.Dispatch(null, new EventArgs());\n }\n }\n\n public class MessageBroker\n {\n private Dictionary<Type, object> handlers;\n\n public Dictionary<Type, object> Handlers\n {\n get { return handlers; }\n set { handlers = value; }\n }\n\n public void Dispatch<T>(object sender, T e) where T : EventArgs\n {\n object entry;\n if (Handlers.TryGetValue(e.GetType(), out entry))\n {\n MessageHandler<T> handler = entry as MessageHandler<T>;\n if (handler != null)\n {\n handler.HandleMessage(sender, e);\n }\n else\n {\n //I'd log an error here\n Console.WriteLine(\"The handler defined for event type '\" + e.GetType().Name + \"' doesn't implement the correct interface!\");\n }\n }\n else\n {\n //I'd log a warning here\n Console.WriteLine(\"No handler defined for event type: \" + e.GetType().Name);\n }\n }\n }\n\n public interface MessageHandler<T> where T : EventArgs\n {\n void HandleMessage(object sender, T message);\n }\n\n public class Type1MessageHandler : MessageHandler<Type1EventArgs>\n {\n public void HandleMessage(object sender, Type1EventArgs args)\n {\n Console.WriteLine(\"Type 1, \" + args.ToString());\n }\n }\n\n public class Type2MessageHandler : MessageHandler<Type2EventArgs>\n {\n public void HandleMessage(object sender, Type2EventArgs args)\n {\n Console.WriteLine(\"Type 2, \" + args.ToString());\n }\n }\n\n public class Type1EventArgs : EventArgs {}\n\n public class Type2EventArgs : EventArgs {}\n}\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <configSections>\n <sectionGroup name=\"spring\">\n <section name=\"context\" type=\"Spring.Context.Support.ContextHandler, Spring.Core\"/>\n <section name=\"objects\" type=\"Spring.Context.Support.DefaultSectionHandler, Spring.Core\"/>\n </sectionGroup>\n </configSections>\n\n <spring>\n <context>\n <resource uri=\"config://spring/objects\"/>\n </context>\n <objects xmlns=\"http://www.springframework.net\">\n\n <object id=\"messageBroker\" type=\"Example.MessageBroker, Example\">\n <property name=\"handlers\">\n <dictionary key-type=\"System.Type\" value-type=\"object\">\n <entry key=\"Example.Type1EventArgs, Example\" value-ref=\"type1Handler\"/>\n <entry key=\"Example.Type2EventArgs, Example\" value-ref=\"type2Handler\"/>\n </dictionary>\n </property>\n </object>\n <object id=\"type1Handler\" type=\"Example.Type1MessageHandler, Example\"/>\n <object id=\"type2Handler\" type=\"Example.Type2MessageHandler, Example\"/>\n </objects>\n </spring>\n</configuration>\n MessageBroker MessageBroker MessageHandler<> MessageHandler<EventArgs>"
},
{
"answer_id": 189208,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": true,
"text": "class EventBroker {\n private Dictionary<Type, Action<EventArgs>> messageHandlers;\n\n void Register<T>(Action<EventArgs> subscriber) where T:EventArgs {\n // may have to combine delegates if more than 1 listener\n messageHandlers[typeof(T)] = subscriber; \n }\n\n void Send<T>(T e) where T:EventArgs {\n var d = messageHandlers[typeof(T)];\n if (d != null) {\n d(e);\n }\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
189,172
|
<p>I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in <a href="https://stackoverflow.com/questions/75538/hidden-features-of-c#75627">this post</a> and also on <a href="http://en.wikipedia.org/wiki/C%2B%2B" rel="noreferrer">wikipedia</a>.</p>
<p>Can you provide a nontrivial example of a computation that exploits this property?</p>
<p>Is this fact useful in practice?</p>
|
[
{
"answer_id": 189204,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "template <int N> struct Factorial\n{\n enum { val = Factorial<N-1>::val * N };\n};\n\ntemplate <> struct Factorial<0>\n{\n enum { val = 1 };\n}\n\nconst int num = Factorial<10>::val; // num set to 10! at compile time.\n"
},
{
"answer_id": 189444,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 8,
"selected": true,
"text": "#include <iostream>\n\ntemplate <int N> struct Factorial\n{\n enum { val = Factorial<N-1>::val * N };\n};\n\ntemplate<>\nstruct Factorial<0>\n{\n enum { val = 1 };\n};\n\nint main()\n{\n // Note this value is generated at compile time.\n // Also note that most compilers have a limit on the depth of the recursion available.\n std::cout << Factorial<4>::val << \"\\n\";\n}\n"
},
{
"answer_id": 275295,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": false,
"text": "#include <iostream>\n\ntemplate<bool C, typename A, typename B>\nstruct Conditional {\n typedef A type;\n};\n\ntemplate<typename A, typename B>\nstruct Conditional<false, A, B> {\n typedef B type;\n};\n\ntemplate<typename...>\nstruct ParameterPack;\n\ntemplate<bool C, typename = void>\nstruct EnableIf { };\n\ntemplate<typename Type>\nstruct EnableIf<true, Type> {\n typedef Type type;\n};\n\ntemplate<typename T>\nstruct Identity {\n typedef T type;\n};\n\n// define a type list \ntemplate<typename...>\nstruct TypeList;\n\ntemplate<typename T, typename... TT>\nstruct TypeList<T, TT...> {\n typedef T type;\n typedef TypeList<TT...> tail;\n};\n\ntemplate<>\nstruct TypeList<> {\n\n};\n\ntemplate<typename List>\nstruct GetSize;\n\ntemplate<typename... Items>\nstruct GetSize<TypeList<Items...>> {\n enum { value = sizeof...(Items) };\n};\n\ntemplate<typename... T>\nstruct ConcatList;\n\ntemplate<typename... First, typename... Second, typename... Tail>\nstruct ConcatList<TypeList<First...>, TypeList<Second...>, Tail...> {\n typedef typename ConcatList<TypeList<First..., Second...>, \n Tail...>::type type;\n};\n\ntemplate<typename T>\nstruct ConcatList<T> {\n typedef T type;\n};\n\ntemplate<typename NewItem, typename List>\nstruct AppendItem;\n\ntemplate<typename NewItem, typename...Items>\nstruct AppendItem<NewItem, TypeList<Items...>> {\n typedef TypeList<Items..., NewItem> type;\n};\n\ntemplate<typename NewItem, typename List>\nstruct PrependItem;\n\ntemplate<typename NewItem, typename...Items>\nstruct PrependItem<NewItem, TypeList<Items...>> {\n typedef TypeList<NewItem, Items...> type;\n};\n\ntemplate<typename List, int N, typename = void>\nstruct GetItem {\n static_assert(N > 0, \"index cannot be negative\");\n static_assert(GetSize<List>::value > 0, \"index too high\");\n typedef typename GetItem<typename List::tail, N-1>::type type;\n};\n\ntemplate<typename List>\nstruct GetItem<List, 0> {\n static_assert(GetSize<List>::value > 0, \"index too high\");\n typedef typename List::type type;\n};\n\ntemplate<typename List, template<typename, typename...> class Matcher, typename... Keys>\nstruct FindItem {\n static_assert(GetSize<List>::value > 0, \"Could not match any item.\");\n typedef typename List::type current_type;\n typedef typename Conditional<Matcher<current_type, Keys...>::value, \n Identity<current_type>, // found!\n FindItem<typename List::tail, Matcher, Keys...>>\n ::type::type type;\n};\n\ntemplate<typename List, int I, typename NewItem>\nstruct ReplaceItem {\n static_assert(I > 0, \"index cannot be negative\");\n static_assert(GetSize<List>::value > 0, \"index too high\");\n typedef typename PrependItem<typename List::type, \n typename ReplaceItem<typename List::tail, I-1,\n NewItem>::type>\n ::type type;\n};\n\ntemplate<typename NewItem, typename Type, typename... T>\nstruct ReplaceItem<TypeList<Type, T...>, 0, NewItem> {\n typedef TypeList<NewItem, T...> type;\n};\n\nenum Direction {\n Left = -1,\n Right = 1\n};\n\ntemplate<typename OldState, typename Input, typename NewState, \n typename Output, Direction Move>\nstruct Rule {\n typedef OldState old_state;\n typedef Input input;\n typedef NewState new_state;\n typedef Output output;\n static Direction const direction = Move;\n};\n\ntemplate<typename A, typename B>\nstruct IsSame {\n enum { value = false }; \n};\n\ntemplate<typename A>\nstruct IsSame<A, A> {\n enum { value = true };\n};\n\ntemplate<typename Input, typename State, int Position>\nstruct Configuration {\n typedef Input input;\n typedef State state;\n enum { position = Position };\n};\n\ntemplate<int A, int B>\nstruct Max {\n enum { value = A > B ? A : B };\n};\n\ntemplate<int n>\nstruct State {\n enum { value = n };\n static char const * name;\n};\n\ntemplate<int n>\nchar const* State<n>::name = \"unnamed\";\n\nstruct QAccept {\n enum { value = -1 };\n static char const* name;\n};\n\nstruct QReject {\n enum { value = -2 };\n static char const* name; \n};\n\n#define DEF_STATE(ID, NAME) \\\n typedef State<ID> NAME ; \\\n NAME :: name = #NAME ;\n\ntemplate<int n>\nstruct Input {\n enum { value = n };\n static char const * name;\n\n template<int... I>\n struct Generate {\n typedef TypeList<Input<I>...> type;\n };\n};\n\ntemplate<int n>\nchar const* Input<n>::name = \"unnamed\";\n\ntypedef Input<-1> InputBlank;\n\n#define DEF_INPUT(ID, NAME) \\\n typedef Input<ID> NAME ; \\\n NAME :: name = #NAME ;\n\ntemplate<typename Config, typename Transitions, typename = void> \nstruct Controller {\n typedef Config config;\n enum { position = config::position };\n\n typedef typename Conditional<\n static_cast<int>(GetSize<typename config::input>::value) \n <= static_cast<int>(position),\n AppendItem<InputBlank, typename config::input>,\n Identity<typename config::input>>::type::type input;\n typedef typename config::state state;\n\n typedef typename GetItem<input, position>::type cell;\n\n template<typename Item, typename State, typename Cell>\n struct Matcher {\n typedef typename Item::old_state checking_state;\n typedef typename Item::input checking_input;\n enum { value = IsSame<State, checking_state>::value && \n IsSame<Cell, checking_input>::value\n };\n };\n typedef typename FindItem<Transitions, Matcher, state, cell>::type rule;\n\n typedef typename ReplaceItem<input, position, typename rule::output>::type new_input;\n typedef typename rule::new_state new_state;\n typedef Configuration<new_input, \n new_state, \n Max<position + rule::direction, 0>::value> new_config;\n\n typedef Controller<new_config, Transitions> next_step;\n typedef typename next_step::end_config end_config;\n typedef typename next_step::end_input end_input;\n typedef typename next_step::end_state end_state;\n enum { end_position = next_step::position };\n};\n\ntemplate<typename Input, typename State, int Position, typename Transitions>\nstruct Controller<Configuration<Input, State, Position>, Transitions, \n typename EnableIf<IsSame<State, QAccept>::value || \n IsSame<State, QReject>::value>::type> {\n typedef Configuration<Input, State, Position> config;\n enum { position = config::position };\n typedef typename Conditional<\n static_cast<int>(GetSize<typename config::input>::value) \n <= static_cast<int>(position),\n AppendItem<InputBlank, typename config::input>,\n Identity<typename config::input>>::type::type input;\n typedef typename config::state state;\n\n typedef config end_config;\n typedef input end_input;\n typedef state end_state;\n enum { end_position = position };\n};\n\ntemplate<typename Input, typename Transitions, typename StartState>\nstruct TuringMachine {\n typedef Input input;\n typedef Transitions transitions;\n typedef StartState start_state;\n\n typedef Controller<Configuration<Input, StartState, 0>, Transitions> controller;\n typedef typename controller::end_config end_config;\n typedef typename controller::end_input end_input;\n typedef typename controller::end_state end_state;\n enum { end_position = controller::end_position };\n};\n\n#include <ostream>\n\ntemplate<>\nchar const* Input<-1>::name = \"_\";\n\nchar const* QAccept::name = \"qaccept\";\nchar const* QReject::name = \"qreject\";\n\nint main() {\n DEF_INPUT(1, x);\n DEF_INPUT(2, x_mark);\n DEF_INPUT(3, split);\n\n DEF_STATE(0, start);\n DEF_STATE(1, find_blank);\n DEF_STATE(2, go_back);\n\n /* syntax: State, Input, NewState, Output, Move */\n typedef TypeList< \n Rule<start, x, find_blank, x_mark, Right>,\n Rule<find_blank, x, find_blank, x, Right>,\n Rule<find_blank, split, find_blank, split, Right>,\n Rule<find_blank, InputBlank, go_back, x, Left>,\n Rule<go_back, x, go_back, x, Left>,\n Rule<go_back, split, go_back, split, Left>,\n Rule<go_back, x_mark, start, x, Right>,\n Rule<start, split, QAccept, split, Left>> rules;\n\n /* syntax: initial input, rules, start state */\n typedef TuringMachine<TypeList<x, x, x, x, split>, rules, start> double_it;\n static_assert(IsSame<double_it::end_input, \n TypeList<x, x, x, x, split, x, x, x, x>>::value, \n \"Hmm... This is borky!\");\n}\n"
},
{
"answer_id": 2222729,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 4,
"selected": false,
"text": "constexpr constexpr unsigned int fac (unsigned int u) {\n return (u<=1) ? (1) : (u*fac(u-1));\n}\n constexpr constexpr bool f(){\n char array[1+int(1+0.2-0.1-0.1)]; //Must be evaluated during translation\n int size=1+int(1+0.2-0.1-0.1); //May be evaluated at runtime\n return sizeof(array)==size;\n}\n"
},
{
"answer_id": 36113234,
"author": "Victor Komarov",
"author_id": 3046221,
"author_profile": "https://Stackoverflow.com/users/3046221",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n\n#pragma mark - Tape\n\nconstexpr int Blank = -1;\n\ntemplate<int... xs>\nclass Tape {\npublic:\n using type = Tape<xs...>;\n constexpr static int length = sizeof...(xs);\n};\n\n#pragma mark - Print\n\ntemplate<class T>\nvoid print(T);\n\ntemplate<>\nvoid print(Tape<>) {\n std::cout << std::endl;\n}\n\ntemplate<int x, int... xs>\nvoid print(Tape<x, xs...>) {\n if (x == Blank) {\n std::cout << \"_ \";\n } else {\n std::cout << x << \" \";\n }\n print(Tape<xs...>());\n}\n\n#pragma mark - Concatenate\n\ntemplate<class, class>\nclass Concatenate;\n\ntemplate<int... xs, int... ys>\nclass Concatenate<Tape<xs...>, Tape<ys...>> {\npublic:\n using type = Tape<xs..., ys...>;\n};\n\n#pragma mark - Invert\n\ntemplate<class>\nclass Invert;\n\ntemplate<>\nclass Invert<Tape<>> {\npublic:\n using type = Tape<>;\n};\n\ntemplate<int x, int... xs>\nclass Invert<Tape<x, xs...>> {\npublic:\n using type = typename Concatenate<\n typename Invert<Tape<xs...>>::type,\n Tape<x>\n >::type;\n};\n\n#pragma mark - Read\n\ntemplate<int, class>\nclass Read;\n\ntemplate<int n, int x, int... xs>\nclass Read<n, Tape<x, xs...>> {\npublic:\n using type = typename std::conditional<\n (n == 0),\n std::integral_constant<int, x>,\n Read<n - 1, Tape<xs...>>\n >::type::type;\n};\n\n#pragma mark - N first and N last\n\ntemplate<int, class>\nclass NLast;\n\ntemplate<int n, int x, int... xs>\nclass NLast<n, Tape<x, xs...>> {\npublic:\n using type = typename std::conditional<\n (n == sizeof...(xs)),\n Tape<xs...>,\n NLast<n, Tape<xs...>>\n >::type::type;\n};\n\ntemplate<int, class>\nclass NFirst;\n\ntemplate<int n, int... xs>\nclass NFirst<n, Tape<xs...>> {\npublic:\n using type = typename Invert<\n typename NLast<\n n, typename Invert<Tape<xs...>>::type\n >::type\n >::type;\n};\n\n#pragma mark - Write\n\ntemplate<int, int, class>\nclass Write;\n\ntemplate<int pos, int x, int... xs>\nclass Write<pos, x, Tape<xs...>> {\npublic:\n using type = typename Concatenate<\n typename Concatenate<\n typename NFirst<pos, Tape<xs...>>::type,\n Tape<x>\n >::type,\n typename NLast<(sizeof...(xs) - pos - 1), Tape<xs...>>::type\n >::type;\n};\n\n#pragma mark - Move\n\ntemplate<int, class>\nclass Hold;\n\ntemplate<int pos, int... xs>\nclass Hold<pos, Tape<xs...>> {\npublic:\n constexpr static int position = pos;\n using tape = Tape<xs...>;\n};\n\ntemplate<int, class>\nclass Left;\n\ntemplate<int pos, int... xs>\nclass Left<pos, Tape<xs...>> {\npublic:\n constexpr static int position = typename std::conditional<\n (pos > 0),\n std::integral_constant<int, pos - 1>,\n std::integral_constant<int, 0>\n >::type();\n\n using tape = typename std::conditional<\n (pos > 0),\n Tape<xs...>,\n Tape<Blank, xs...>\n >::type;\n};\n\ntemplate<int, class>\nclass Right;\n\ntemplate<int pos, int... xs>\nclass Right<pos, Tape<xs...>> {\npublic:\n constexpr static int position = pos + 1;\n\n using tape = typename std::conditional<\n (pos < sizeof...(xs) - 1),\n Tape<xs...>,\n Tape<xs..., Blank>\n >::type;\n};\n\n#pragma mark - States\n\ntemplate <int>\nclass Stop {\npublic:\n constexpr static int write = -1;\n template<int pos, class tape> using move = Hold<pos, tape>;\n template<int x> using next = Stop<x>;\n};\n\n#define ADD_STATE(_state_) \\\ntemplate<int> \\\nclass _state_ { };\n\n#define ADD_RULE(_state_, _read_, _write_, _move_, _next_) \\\ntemplate<> \\\nclass _state_<_read_> { \\\npublic: \\\n constexpr static int write = _write_; \\\n template<int pos, class tape> using move = _move_<pos, tape>; \\\n template<int x> using next = _next_<x>; \\\n};\n\n#pragma mark - Machine\n\ntemplate<template<int> class, int, class>\nclass Machine;\n\ntemplate<template<int> class State, int pos, int... xs>\nclass Machine<State, pos, Tape<xs...>> {\n constexpr static int symbol = typename Read<pos, Tape<xs...>>::type();\n using state = State<symbol>;\n\n template<int x>\n using nextState = typename State<symbol>::template next<x>;\n\n using modifiedTape = typename Write<pos, state::write, Tape<xs...>>::type;\n using move = typename state::template move<pos, modifiedTape>;\n\n constexpr static int nextPos = move::position;\n using nextTape = typename move::tape;\n\npublic:\n using step = Machine<nextState, nextPos, nextTape>;\n};\n\n#pragma mark - Run\n\ntemplate<class>\nclass Run;\n\ntemplate<template<int> class State, int pos, int... xs>\nclass Run<Machine<State, pos, Tape<xs...>>> {\n using step = typename Machine<State, pos, Tape<xs...>>::step;\n\npublic:\n using type = typename std::conditional<\n std::is_same<State<0>, Stop<0>>::value,\n Tape<xs...>,\n Run<step>\n >::type::type;\n};\n\nADD_STATE(A);\nADD_STATE(B);\nADD_STATE(C);\nADD_STATE(D);\n\nADD_RULE(A, Blank, 1, Right, B);\nADD_RULE(A, 1, 1, Left, B);\n\nADD_RULE(B, Blank, 1, Left, A);\nADD_RULE(B, 1, Blank, Left, C);\n\nADD_RULE(C, Blank, 1, Right, Stop);\nADD_RULE(C, 1, 1, Left, D);\n\nADD_RULE(D, Blank, 1, Right, D);\nADD_RULE(D, 1, Blank, Right, A);\n\nusing tape = Tape<Blank>;\nusing machine = Machine<A, 0, tape>;\nusing result = Run<machine>::type;\n\nint main() {\n print(result());\n return 0;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
189,190
|
<p>It needs to be graphical. No sed, awk, grep, perl, whatever. I know how to use those and I do use them now, but I need to cherry-pick each replace in 300+ files.</p>
<p>I want a tool where I can:</p>
<ul>
<li>type a search string</li>
<li>type a replace string</li>
<li>select a directory and file extension</li>
</ul>
<p>and it would recursively go into each file in that directory and its sub-directories, open it and scroll to the place where search string is and offer two options:</p>
<ul>
<li>replace (and find next)</li>
<li>find next</li>
</ul>
<p>Nothing more. Reg.exp. support is a plus, but not required.</p>
<p>SOLVED: Regexxer is exactly what I needed. In case someone needs it on Slackware, <a href="http://swoes.blogspot.com/2008/10/regexxer-on-slackware-121.html" rel="noreferrer">here's</a> what you need to download and how to compile it (choosing correct version of each dependency can be a PITA)</p>
|
[
{
"answer_id": 189409,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 2,
"selected": false,
"text": ":tabdo %s/foo/bar/gc\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] |
189,209
|
<p>For a long time ago, I have thought that, in java, reversing the domain you own for package naming is silly and awkward.</p>
<p>Which do you use for package naming in your projects?</p>
|
[
{
"answer_id": 193459,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 2,
"selected": false,
"text": "[company].[project].[sub].xyz(.abc)\n sub client common server project oak.lang.Object\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
] |
189,213
|
<p>Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique.</p>
<pre><code>select chargeId, chargeType, serviceMonth from invoice
CHARGEID CHARGETYPE SERVICEMONTH
1 101 R 8/1/2008
2 161 N 2/1/2008
3 101 R 2/1/2008
4 101 R 3/1/2008
5 101 R 4/1/2008
6 101 R 5/1/2008
7 101 R 6/1/2008
8 101 R 7/1/2008
</code></pre>
<p>Desired:</p>
<pre><code> CHARGEID CHARGETYPE SERVICEMONTH
1 101 R 8/1/2008
2 161 N 2/1/2008
</code></pre>
|
[
{
"answer_id": 189221,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 8,
"selected": true,
"text": "SELECT\n CHARGEID,\n CHARGETYPE,\n MAX(SERVICEMONTH) AS \"MostRecentServiceMonth\"\nFROM INVOICE\nGROUP BY CHARGEID, CHARGETYPE\n"
},
{
"answer_id": 189227,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 4,
"selected": false,
"text": "SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth \nFROM invoice\nGROUP BY chargeId, chargeType\n"
},
{
"answer_id": 189264,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( \n SELECT chargeId,MAX(serviceMonth) AS serviceMonth\n FROM invoice\n GROUP BY chargeId) x \n JOIN invoice t ON x.chargeId =t.chargeId\n AND x.serviceMonth = t.serviceMonth\n"
},
{
"answer_id": 38122817,
"author": "pari elanchezhiyan",
"author_id": 6533361,
"author_profile": "https://Stackoverflow.com/users/6533361",
"pm_score": 1,
"selected": false,
"text": "select to.chargeid,t0.po,i.chargetype from invoice i\ninner join\n(select chargeid,max(servicemonth)po from invoice \ngroup by chargeid)t0\non i.chargeid=t0.chargeid\n"
},
{
"answer_id": 39016684,
"author": "sujeet",
"author_id": 2144484,
"author_profile": "https://Stackoverflow.com/users/2144484",
"pm_score": 3,
"selected": false,
"text": "select a.chargeId, a.chargeType, a.serviceMonth \nfrom invoice a\nleft outer join invoice b\non a.chargeId=b.chargeId and a.serviceMonth <b.serviceMonth \nwhere b.chargeId is null\norder by a.serviceMonth desc\n"
},
{
"answer_id": 72804170,
"author": "Bozon",
"author_id": 4879179,
"author_profile": "https://Stackoverflow.com/users/4879179",
"pm_score": 0,
"selected": false,
"text": "select \n chargeid, \n chargetype,\n SERVICEMONTH\nfrom invoice t0\nwhere t0.SERVICEMONTH = (\n select max(SERVICEMONTH) \n from invoice t1 \n where t1.chargeid = t0.chargeid\n and t1.chargetype = t0.chargetype\n);\n with w_o as (\n select\n chargeid, \n chargetype,\n SERVICEMONTH,\n row_number() OVER (PARTITION BY chargeid, chargetype ORDER BY SERVICEMONTH DESC) rn\n from invoice\n)\nselect\n chargeid, \n chargetype,\n SERVICEMONTH\nfrom w_o\nwhere rn = 1;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16345/"
] |
189,228
|
<p>When writing async method implementations using the BeginInvoke/EndInvoke pattern the code might look something like the following (and to save you guessing this is an async wrapper around a cache):</p>
<pre><code>IAsyncResult BeginPut(string key, object value)
{
Action<string, object> put = this.cache.Put;
return put.BeginInvoke(key, value, null, null);
}
void EndPut(IAsyncResult asyncResult)
{
var put = (Action<string, object>)((AsyncResult)asyncResult).AsyncDelegate;
put.EndInvoke(asyncResult);
}
</code></pre>
<p>This works perfectly well because it's known what the type of delegate is, so it can be cast. However it starts to get messy when you have two <code>Put</code> methods, because although the method returns void you seemingly have to cast it to a strongly typed delegate to end the invocation, e.g.</p>
<pre><code>IAsyncResult BeginPut(string key, object value)
{
Action<string, object> put = this.cache.Put;
return put.BeginInvoke(key, value, null, null);
}
IAsyncResult BeginPut(string region, string key, object value)
{
Action<string, string, object> put = this.cache.Put;
return put.BeginInvoke(region, key, value, null, null);
}
void EndPut(IAsyncResult asyncResult)
{
var put = ((AsyncResult)asyncResult).AsyncDelegate;
var put1 = put as Action<string, object>;
if (put1 != null)
{
put1.EndInvoke(asyncResult);
return;
}
var put2 = put as Action<string, string, object>;
if (put2 != null)
{
put2.EndInvoke(asyncResult);
return;
}
throw new ArgumentException("Invalid async result", "asyncResult");
}
</code></pre>
<p>I'm hoping there is a cleaner way to do this, because the only thing I care about the delegate is the return type (in this case void) and not the arguments that were supplied to it. But I've racked my brains and asked others in the office, and nobody can think of the answer.</p>
<p>I know one solution is to write a custom <code>IAsyncResult</code>, but that's such a difficult task with the potential threading issues around things like lazy instantiation of the <code>WaitHandle</code> that I'd rather have this slightly hacky looking code than go down that route.</p>
<p>Any ideas on how to end the invocation without a cascading set of <code>is</code> checks?</p>
|
[
{
"answer_id": 189266,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "IAsyncResult BeginPut(string key, object value) {\n return this.BeginPut(null, key, value);\n}\n\nIAsyncResult BeginPut(string region, string key, object value) {\n Action<string, string, object> put = this.Put;\n return put.BeginInvoke(region, key, value, null, null);\n}\n\nvoid EndPut(IAsyncResult asyncResult) {\n var put = (Action<string, string, object>)((AsyncResult)asyncResult).AsyncDelegate;\n put.EndInvoke(asyncResult);\n}\n"
},
{
"answer_id": 189292,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 0,
"selected": false,
"text": "EndPut EndPut put BeginInvoke() EndInvoke() Delegate EndInvoke() switch asyncResult.AsyncState.GetType() put"
},
{
"answer_id": 189325,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "Action( IAsyncResult ) EndInvoke() EndPut() IAsyncResult BeginPut( string key, object value ) {\n Action<string, object> put = this.Put;\n return put.BeginInvoke( key, value, EndPut,\n new Action<IAsyncResult>( put.EndInvoke ) );\n}\n\nIAsyncResult BeginPut( string region, string key, object value ) {\n Action<string, string, object> put = this.Put;\n return put.BeginInvoke( region, key, value, EndPut,\n new Action<IAsyncResult>( put.EndInvoke ) );\n}\n void EndPut( IAsyncResult asyncResult ) {\n var del = asyncResult.AsyncState as Action<IAsyncResult>;\n del( asyncResult );\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13552/"
] |
189,280
|
<p>I use NHibernate for my dataacess, and for awhile not I've been using SQLite for local integration tests. I've been using a file, but I thought I would out the :memory: option. When I fire up any of the integration tests, the database seems to be created (NHibernate spits out the table creation sql) but interfacting with the database causes an error.</p>
<p>Has anyone every gotten NHibernate working with an in memory database? Is it even possible? The connection string I'm using is this:</p>
<pre><code>Data Source=:memory:;Version=3;New=True
</code></pre>
|
[
{
"answer_id": 196979,
"author": "Stefan Steinegger",
"author_id": 2658202,
"author_profile": "https://Stackoverflow.com/users/2658202",
"pm_score": 3,
"selected": false,
"text": "file::memory:?cache=shared"
},
{
"answer_id": 4501759,
"author": "Julien Bérubé",
"author_id": 309236,
"author_profile": "https://Stackoverflow.com/users/309236",
"pm_score": 3,
"selected": false,
"text": " <hibernate-configuration xmlns=\"urn:nhibernate-configuration-2.2\">\n <reflection-optimizer use=\"true\" />\n <session-factory>\n <property name=\"connection.connection_string_name\">testSqlLiteDB</property>\n <property name=\"connection.driver_class\">NHibernate.Driver.SQLite20Driver</property>\n <property name=\"connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n <property name=\"connection.release_mode\">on_close</property>\n <property name=\"dialect\">NHibernate.Dialect.SQLiteDialect</property>\n <property name=\"proxyfactory.factory_class\">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>\n <property name=\"query.substitutions\">true=1;false=0</property>\n </session-factory>\n </hibernate-configuration>\n"
},
{
"answer_id": 15574248,
"author": "decates",
"author_id": 792525,
"author_profile": "https://Stackoverflow.com/users/792525",
"pm_score": 4,
"selected": false,
"text": "FullUri=file:memorydb.db?mode=memory&cache=shared\n [TestClass]\npublic static class SampleAssemblySetup\n{\n private const string ConnectionString = \"FullUri=file:memorydb.db?mode=memory&cache=shared\";\n private static SQLiteConnection _connection;\n\n [AssemblyInitialize]\n public static void AssemblyInit(TestContext context)\n {\n var configuration = Fluently.Configure()\n .Database(SQLiteConfiguration.Standard.ConnectionString(ConnectionString))\n .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load(\"MyMappingsAssembly\")))\n .ExposeConfiguration(x => x.SetProperty(\"current_session_context_class\", \"call\"))\n .BuildConfiguration();\n\n // Create the schema in the database\n // Because it's an in-memory database, we hold this connection open until all the tests are finished\n var schemaExport = new SchemaExport(configuration);\n _connection = new SQLiteConnection(ConnectionString);\n _connection.Open();\n schemaExport.Execute(false, true, false, _connection, null);\n }\n\n [AssemblyCleanup]\n public static void AssemblyTearDown()\n {\n if (_connection != null)\n {\n _connection.Dispose();\n _connection = null;\n }\n }\n}\n public class TestBase\n{\n [TestInitialize]\n public virtual void Initialize()\n {\n NHibernateBootstrapper.InitializeSession();\n var transaction = SessionFactory.Current.GetCurrentSession().BeginTransaction();\n }\n\n [TestCleanup]\n public virtual void Cleanup()\n {\n var currentSession = SessionFactory.Current.GetCurrentSession();\n if (currentSession.Transaction != null)\n {\n currentSession.Transaction.Rollback();\n currentSession.Close();\n }\n\n NHibernateBootstrapper.CleanupSession();\n }\n}\n"
},
{
"answer_id": 17012018,
"author": "Drexter",
"author_id": 2341271,
"author_profile": "https://Stackoverflow.com/users/2341271",
"pm_score": 0,
"selected": false,
"text": "FullUri=file:memorydb.db?mode=memory&cache=shared\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
189,293
|
<p>I have a subroutine that takes a filehandle as an argument. How do I make a filehandle from a file path specified on the command line? I don't want to do any processing of this file myself, I just want to pass it off to this other subroutine, which returns an array of hashes with all the parsed data from the file.</p>
<p>Here's what the command line input I'm using looks like:</p>
<p><code>$ ./getfile.pl /path/to/some/file.csv</code></p>
<p>Here's what the beginning of the subroutine I'm calling looks like:</p>
<pre><code>sub parse {
my $handle = shift;
my @data = <$handle>;
while (my $line = shift(@data)) {
# do stuff
}
}
</code></pre>
|
[
{
"answer_id": 189314,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": -1,
"selected": false,
"text": "open($fh, \"<$ARGV[0]\") or die \"couldn't open $ARGV[0]: $!\";\ndo_something_with_fh($fh);\nclose($fh);\n"
},
{
"answer_id": 189316,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 5,
"selected": true,
"text": "@ARGV open my $file = shift @ARGV;\nopen(my $fh, '<', $file) or die \"Can't read file '$file' [$!]\\n\";\nparse($fh);\n or die... open $!"
},
{
"answer_id": 189842,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": false,
"text": "parse(*ARGV) <> ARGV @ARGV STDIN @ARGV perldoc perlop <> <> <> @ARGV $ARGV[0] \"-\" @ARGV while (<>) {\n ... # code for each line\n}\n unshift(@ARGV, '-') unless @ARGV;\nwhile ($ARGV = shift) {\n open(ARGV, $ARGV);\n while (<ARGV>) {\n ... # code for each line\n }\n}\n @ARGV $ARGV ARGV <> <ARGV> <ARGV> <> while my $data = <> my @data = <>; *ARGV"
},
{
"answer_id": 192889,
"author": "Steve Klabnik",
"author_id": 24817,
"author_profile": "https://Stackoverflow.com/users/24817",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/perl -n\n\n#do stuff\n #!/usr/bin/perl -n\n\nBEGIN {\n my $accumulator;\n}\n\n# do stuff\n\nEND {\n print process_total($accumulator);\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6406/"
] |
189,308
|
<h2>Problem</h2>
<p>Our web host provider is changing the IP address of one of the servers we are on. We have been given a time frame for when the switch will take place, but no exact details. Therefore, our current <em>poor man's</em> check requires a periodic page refresh on a browser to see if our website is still there.</p>
<h2>Question</h2>
<p>We are all programmers here and this is killing me that any manual checking is required. I would know how to do this in other languages, but want to know if there is a way to write a script in <strong>PowerShell</strong> to tackle this problem. Does anyone know how I might going about this?</p>
|
[
{
"answer_id": 189653,
"author": "aphoria",
"author_id": 2441,
"author_profile": "https://Stackoverflow.com/users/2441",
"pm_score": 0,
"selected": false,
"text": "Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property IPAddress\n"
},
{
"answer_id": 189794,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 3,
"selected": true,
"text": "$ip = 192.168.1.1\n$webclient = new-object System.Net.WebClient\n$regex = 'regular expression to match something on your page'\n$ping = new-object System.Net.NetworkInformation.Ping\n\n\ndo \n{\n $result = $ping.Send($ip)\n if ($result.status -ne 'TimedOut' )\n {\n $page = $webclient.downloadstring(\"http://$ip\")\n if (($page -notmatch $regex) -or ($page -match '404') -or ($page -eq $null))\n { break}\n }\n} while ($true)\n\nwrite-host \"The website has moved\"\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] |
189,339
|
<p>I've just got a fresh Drupal 6 install. The CSS didn't work. Then I realized that a "?U" was appended, and Drupal couldn't find it. Does anyone know where to unset this? </p>
<pre><code><link type="text/css" rel="stylesheet" media="all" href="/modules/node/node.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/admin.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/defaults.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system-menus.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/user/user.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/themes/bluemarine/style.css?U" />
</code></pre>
|
[
{
"answer_id": 189413,
"author": "Nick Sergeant",
"author_id": 22468,
"author_profile": "https://Stackoverflow.com/users/22468",
"pm_score": 0,
"selected": false,
"text": "http://domain.com/drupal\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11927/"
] |
189,350
|
<p>Is there a way to find out what gcc flags a particular binary was compiled with?</p>
|
[
{
"answer_id": 191875,
"author": "Chris Matta",
"author_id": 6356,
"author_profile": "https://Stackoverflow.com/users/6356",
"pm_score": 2,
"selected": false,
"text": "smb -b"
},
{
"answer_id": 340828,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 4,
"selected": false,
"text": "diciu$ gcc -O2 /tmp/tt.c -o /tmp/a.out.o2\ndiciu$ gcc -O3 /tmp/tt.c -o /tmp/a.out.o3\ndiciu$ diff /tmp/a.out.o3 /tmp/a.out.o2 \ndiciu$\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
] |
189,363
|
<p>How do I write a regular expression to find all lines containing 665 and not having .pdf</p>
<p>I can't seem to find how to do not in regex. This is for Notepad++ syntax if it matters.</p>
<p>Thanks</p>
|
[
{
"answer_id": 189383,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 2,
"selected": false,
"text": "665(?!.*\\.pdf)\n"
},
{
"answer_id": 190086,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 3,
"selected": true,
"text": ".pdf 665 665(?!.*\\.pdf) /665/ && !/\\.pdf/\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
189,368
|
<p>Here's my situation - I want to create a resized jpeg image from a user uploaded image, and then send it to S3 for storage, but am looking to avoid writing the resized jpeg to the disk and then reloading it for the S3 request.</p>
<p>Is there a way to do this completely in memory, with the image data JPEG formatted, saved in a variable?</p>
|
[
{
"answer_id": 189410,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "// Manipulate image - assume ImageMagick, so $im is image object\n$im = new Imagick();\n// Get image source data\n$im->readimageblob($image_source);\n\n// Upload an object from a resource (requires size):\n$s3->putObject($s3->inputResource($im->getimageblob(), $im->getSize()), \n $bucketName, $uploadName, S3::ACL_PUBLIC_READ);\n s3->inputResource"
},
{
"answer_id": 404337,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 3,
"selected": false,
"text": "//$image contains the GD image resource you want to store\n\nob_start();\nimagejpeg($image);\n$jpeg_file_contents = ob_get_contents();\nob_end_clean();\n\n//now send $jpeg_file_contents to S3\n"
},
{
"answer_id": 404358,
"author": "Jacco",
"author_id": 22674,
"author_profile": "https://Stackoverflow.com/users/22674",
"pm_score": 4,
"selected": false,
"text": "<?php\n\n// assuming your uploaded file was 'userFileName'\n\nif ( ! is_uploaded_file(validateFilePath($_FILES[$userFileName]['tmp_name'])) ) {\n trigger_error('not an uploaded file', E_USER_ERROR);\n}\n$srcImage = imagecreatefromjpeg( $_FILES[$userFileName]['tmp_name'] );\n\n// Resize your image (copy from srcImage to dstImage)\nimagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT, imagesx($srcImage), imagesy($srcImage));\n\n// Storing your resized image in a variable\nob_start(); // start a new output buffer\n imagejpeg( $dstImage, NULL, JPEG_QUALITY);\n $resizedJpegData = ob_get_contents();\nob_end_clean(); // stop this output buffer\n\n// free up unused memmory (if images are expected to be large)\nunset($srcImage);\nunset($dstImage);\n\n// your resized jpeg data is now in $resizedJpegData\n// Use your Undesigned method calls to store the data.\n\n// (Many people want to send it as a Hex stream to the DB:)\n$dbHandle->storeResizedImage( $resizedJpegData );\n?>\n"
},
{
"answer_id": 11218549,
"author": "benipsen",
"author_id": 296073,
"author_profile": "https://Stackoverflow.com/users/296073",
"pm_score": 3,
"selected": false,
"text": "$headers = array(\n 'Content-Type' => 'image/jpeg'\n);\n$s3->putObjectString($im->getImageBlob(), $bucket, $file_name, S3::ACL_PUBLIC_READ, array(), $headers);\n"
},
{
"answer_id": 19335120,
"author": "Bart",
"author_id": 158651,
"author_profile": "https://Stackoverflow.com/users/158651",
"pm_score": 3,
"selected": false,
"text": "require_once('vendor/aws/aws-autoloader.php');\n\nuse Aws\\Common\\Aws;\n\ndefine('AWS_BUCKET', 'your-bucket-name-here');\n\n// Configure AWS factory \n$aws = Aws::factory(array(\n 'key' => 'your-key-here',\n 'secret' => 'your-secret-here',\n 'region' => 'your-region-here'\n));\n\n// Create reference to S3\n$s3 = $aws->get('S3');\n$s3->createBucket(array('Bucket' => AWS_BUCKET));\n$s3->waitUntilBucketExists(array('Bucket' => AWS_BUCKET));\n$s3->registerStreamWrapper();\n\n// Do your GD resizing here (omitted for brevity)\n\n// Capture image stream in output buffer\nob_start();\nimagejpeg($imageRes);\n$imageFileContents = ob_get_contents();\nob_end_clean();\n\n// Send stream to S3\n$context = stream_context_create(\n array(\n 's3' => array(\n 'ContentType'=> 'image/jpeg'\n )\n )\n);\n$s3Stream = fopen('s3://'.AWS_BUCKET.'/'.$filename, 'w', false, $context);\nfwrite($s3Stream, $imageFileContents);\nfclose($s3Stream);\n\nunset($context, $imageFileContents, $s3Stream);\n"
},
{
"answer_id": 46008439,
"author": "Julien Fastré",
"author_id": 1572236,
"author_profile": "https://Stackoverflow.com/users/1572236",
"pm_score": 1,
"selected": false,
"text": "ob_start ob_end_clean // $image is a resource created by gd2\nvar_dump($image); // resource(2) of type (gd)\n\n// we create a resource in memory + temp file \n$tmp = fopen('php://temp', '$r+');\n\n// we write the image into our resource\n\\imagejpeg($image, $tmp);\n\n// the image is now in $tmp, and you can handle it as a stream\n// you can, then, upload it as a stream (not tested but mentioned in doc http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html#uploading-from-a-stream)\n$s3->putObject(array(\n 'Bucket' => $bucket,\n 'Key' => 'data_from_stream.txt',\n 'Body' => $tmp\n));\n\n// or, for the ones who prefers php-opencloud :\n$container->createObject([\n 'name' => 'data_from_stream.txt',\n 'stream' => \\Guzzle\\Psr7\\stream_for($tmp),\n 'contentType' => 'image/jpeg'\n]);\n php://temp"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24694/"
] |
189,375
|
<p>With a view to avoiding the construction of further barriers to migration whilst
enhancing an existing vb6 program.
Is there a way to achieve the same functionality as control arrays in vb6 without using them?</p>
|
[
{
"answer_id": 191406,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 2,
"selected": true,
"text": "Private Sub MyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,Button2.Click\n\n Dim Btn As Button = CType(sender, Button)\n Dim Index As Integer = CType(Btn.Tag, Integer)\n' Do whatever you were doing in VB6 with the Index property\n\nEnd Sub\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6164/"
] |
189,391
|
<p>I am looking for a way to take a user uploaded image that is currently put in a temporary location ex: /tmp/jkhjkh78 and create a php image from it, autodetecting the format.</p>
<p>Is there a more clever way to do this than a bunch of try/catching with imagefromjpeg, imagefrompng, etc?</p>
|
[
{
"answer_id": 189400,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 0,
"selected": false,
"text": "file kender@eira:~$ file a\na: JPEG image data, EXIF standard 2.2\n"
},
{
"answer_id": 189412,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 2,
"selected": false,
"text": "finfo_file() mime_content_type() getimagesize()"
},
{
"answer_id": 2351353,
"author": "searbe",
"author_id": 283105,
"author_profile": "https://Stackoverflow.com/users/283105",
"pm_score": 3,
"selected": false,
"text": "exif_imagetype()"
},
{
"answer_id": 23682132,
"author": "MastermanSachin",
"author_id": 3169845,
"author_profile": "https://Stackoverflow.com/users/3169845",
"pm_score": 3,
"selected": false,
"text": " //Image Processing\n $cover = $_FILES['cover']['name'];\n $cover_tmp_name = $_FILES['cover']['tmp_name'];\n $cover_img_path = '/images/';\n $type = exif_imagetype($cover_tmp_name);\n\nif ($type == (IMAGETYPE_PNG || IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_BMP)) {\n $cover_pre_name = md5($cover); //Just to make a image name random and cool :D\n/**\n * @description : possible exif_imagetype() return values in $type\n * 1 - gif image\n * 2 - jpg image\n * 3 - png image\n * 6 - bmp image\n */\n switch ($type) { #There are more type you can choose. Take a look in php manual -> http://www.php.net/manual/en/function.exif-imagetype.php\n case '1' :\n $cover_format = 'gif';\n break;\n case '2' :\n $cover_format = 'jpg';\n break;\n case '3' :\n $cover_format = 'png';\n break;\n case '6' :\n $cover_format = 'bmp';\n break;\n\n default :\n die('There is an error processing the image -> please try again with a new image');\n break;\n }\n $cover_name = $cover_pre_name . '.' . $cover_format;\n //Checks whether the uploaded file exist or not\n if (file_exists($cover_img_path . $cover_name)) {\n $extra = 1;\n while (file_exists($cover_img_path . $cover_name)) {\n $cover_name = md5($cover) . $extra . '.' . $cover_format;\n $extra++;\n }\n }\n //Image Processing Ends\n"
},
{
"answer_id": 46382153,
"author": "Vladimir Kornea",
"author_id": 2407309,
"author_profile": "https://Stackoverflow.com/users/2407309",
"pm_score": 0,
"selected": false,
"text": "getimagesize() getimagesize() finfo_file() string finfo_file ( resource $finfo , string $file_name = NULL \n [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )\n file_name text/html image/gif application/vnd.ms-excel"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24694/"
] |
189,392
|
<p>I'm trying to return a transparent GIF from an .aspx page for display within a web page. I am trying to get the image to have transparency, but I just keep getting Black being where the image should be Transparent.</p>
<p>Does anyone know what I'm doing wrong?</p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
'' Change the response headers to output a GIF image.
Response.Clear()
Response.ContentType = "image/gif"
Dim width = 110
Dim height = width
'' Create a new 32-bit bitmap image
Dim b = New Bitmap(width, height)
'' Create Grahpics object for drawing
Dim g = Graphics.FromImage(b)
Dim rect = New Rectangle(0, 0, width - 1, height - 1)
'' Fill in with Transparent
Dim tbrush = New System.Drawing.SolidBrush(Color.Transparent)
g.FillRectangle(tbrush, rect)
'' Draw Circle Border
Dim bPen = Pens.Red
g.DrawPie(bPen, rect, 0, 365)
'' Fill in Circle
Dim cbrush = New SolidBrush(Color.LightBlue)
g.FillPie(cbrush, rect, 0, 365)
'' Clean up
g.Flush()
g.Dispose()
'' Make Transparent
b.MakeTransparent()
b.Save(Response.OutputStream, Imaging.ImageFormat.Gif)
Response.Flush()
Response.End()
End Sub
</code></pre>
|
[
{
"answer_id": 189480,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 3,
"selected": false,
"text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _\n Handles Me.Load\n '' Change the response headers to output a JPEG image.\n Response.Clear()\n Response.ContentType = \"image/png\"\n\n Dim width = 11\n Dim height = width\n\n '' Create a new 32-bit bitmap image\n Dim b = New Bitmap(width, height)\n\n '' Create Grahpics object for drawing\n Dim g = Graphics.FromImage(b)\n\n '' Fill the image with a color to be made Transparent after drawing is finished.\n g.Clear(Color.Gray)\n\n '' Get rectangle where the Circle will be drawn\n Dim rect = New Rectangle(0, 0, width - 1, height - 1)\n\n '' Draw Circle Border\n Dim bPen = Pens.Black\n g.DrawPie(bPen, rect, 0, 365)\n\n '' Fill in Circle\n Dim cbrush = New SolidBrush(Color.Red)\n g.FillPie(cbrush, rect, 0, 365)\n\n '' Clean up\n g.Flush()\n g.Dispose()\n\n '' Make Transparent\n b.MakeTransparent(Color.Gray)\n\n '' Write PNG to Memory Stream then write to OutputStream\n Dim ms = New MemoryStream()\n b.Save(ms, Imaging.ImageFormat.Png)\n ms.WriteTo(Response.OutputStream)\n\n Response.Flush()\n Response.End()\nEnd Sub\n"
},
{
"answer_id": 2140779,
"author": "Grégoire Lafortune",
"author_id": 259380,
"author_profile": "https://Stackoverflow.com/users/259380",
"pm_score": 2,
"selected": false,
"text": "imagePath = System.Web.HttpContext.Current.Request.MapPath(libraryPath + reqImageFile);\nSystem.Drawing.Image image = null;\nBitmap resizedImage = null;\n\nif (reqWidth == 0) { reqWidth = image.Width; }\nif (reqHeight == 0) { reqHeight = image.Height; }\nimage = System.Drawing.Image.FromFile(imagePath);\nreqWidth = image.Width;\nreqHeight = image.Height;\n\n//here is the transparency 'special' treatment\nresizedImage = new Bitmap(reqWidth, reqHeight, PixelFormat.Format8bppIndexed);\nColorPalette pal = resizedImage.Palette;\nfor (int i = 0; i < pal.Entries.Length; i++)\n{\n Color col = pal.Entries[i];\n pal.Entries[i] = Color.FromArgb(0, col.R, col.G, col.B);\n}\nresizedImage.Palette = pal;\nBitmapData src = ((Bitmap)image).LockBits(new Rectangle(0, 0, reqWidth, reqHeight), ImageLockMode.ReadOnly, image.PixelFormat);\nBitmapData dst = resizedImage.LockBits(new Rectangle(0, 0, resizedImage.Width, resizedImage.Height),\nImageLockMode.WriteOnly, resizedImage.PixelFormat);\n((Bitmap)image).UnlockBits(src);\nresizedImage.UnlockBits(dst);\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] |
189,415
|
<p>I have the following string:</p>
<p><code>$_='364*84252';</code></p>
<p>The question is: how to replace <code>*</code> in the string with something else? I've tried <code>s/\*/$i/</code>, but there is an error: <code>Quantifier follows nothing in regex</code>. On the other hand <code>s/'*'/$i/</code> doesn't cause any errors, but it also doesn't seem to have any effect at all.</p>
|
[
{
"answer_id": 189428,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "~> cat test.pl\n$a = \"234*343\";\n$i = \"FOO\";\n\n$a =~ s/\\*/$i/;\nprint $a;\n\n~> perl test.pl\n234FOO343\n ~> cat test.pl\n$a = \"234*343\";\n$i = \"*4\";\n\n$a =~ m/$i/;\nprint $a;\n\n~> perl test.pl\nQuantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE 4/ at test.pl line 4.\n \\Q \\E ~> cat test.pl\n$a = \"234*343\";\n$i = \"*4\";\n\n$a =~ m/\\Q$i\\E/;\nprint $a;\n\n~> perl test.pl\n234*343\n"
},
{
"answer_id": 189439,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 2,
"selected": false,
"text": "$ perl -le '$_=\"364*84252\";s/\\*/xx/;print'\n364xx84252\n"
},
{
"answer_id": 189440,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$i s/\\*/foo/"
},
{
"answer_id": 189488,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "s/\\\\*/$i/"
},
{
"answer_id": 4330084,
"author": "Ryan Speight",
"author_id": 527294,
"author_profile": "https://Stackoverflow.com/users/527294",
"pm_score": 0,
"selected": false,
"text": "$VARIABLE =~ s/\\Q*\\E//;\n"
},
{
"answer_id": 4330117,
"author": "Ryan Speight",
"author_id": 527294,
"author_profile": "https://Stackoverflow.com/users/527294",
"pm_score": 1,
"selected": false,
"text": "$InputLine =~ s/\\Q*\\E//g; \n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
189,422
|
<p>I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?</p>
|
[
{
"answer_id": 189431,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": true,
"text": "sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] \n [ , [ @provider= ] 'provider_name' ]\n [ , [ @datasrc= ] 'data_source' ] \n [ , [ @location= ] 'location' ] \n [ , [ @provstr= ] 'provider_string' ] \n [ , [ @catalog= ] 'catalog' ] \n"
},
{
"answer_id": 189432,
"author": "Kalid",
"author_id": 109,
"author_profile": "https://Stackoverflow.com/users/109",
"pm_score": 5,
"selected": false,
"text": "exec sp_addlinkedserver @server='10.0.0.51'\n exec sp_linkedservers\n [10.0.0.51].DatabaseName.dbo.TableName\n"
},
{
"answer_id": 31883344,
"author": "MrSimpleMind",
"author_id": 1223532,
"author_profile": "https://Stackoverflow.com/users/1223532",
"pm_score": 4,
"selected": false,
"text": "exec sp_addlinkedserver @server='10.10.0.10\\MyDS'; exec sp_addlinkedsrvlogin '10.10.0.10\\MyDS', 'false', null, 'adm', 'pwd'; exec sp_linkedservers; select * from sys.servers; select * from sys.linked_logins; select * from [10.10.0.10\\MyDS].MyDB.dbo.TestTable; exec sp_dropserver '10.10.0.10\\MyDS', 'droplogins'; -- drops server and logins"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109/"
] |
189,430
|
<p>How to detect the Internet connection is offline in JavaScript?</p>
|
[
{
"answer_id": 189443,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 8,
"selected": true,
"text": "ping"
},
{
"answer_id": 189456,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 5,
"selected": false,
"text": "onerror img <img src=\"http://www.example.com/singlepixel.gif\" onerror=\"alert('Connection dead');\" />"
},
{
"answer_id": 189457,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 6,
"selected": false,
"text": "Image() <img> true false false true"
},
{
"answer_id": 992716,
"author": "karim79",
"author_id": 70393,
"author_profile": "https://Stackoverflow.com/users/70393",
"pm_score": 4,
"selected": false,
"text": "error textStatus function (XMLHttpRequest, textStatus, errorThrown) {\n // typically only one of textStatus or errorThrown \n // will have info\n this; // the options for this ajax request\n}\n $.ajax({\n type: \"GET\",\n url: \"keepalive.php\",\n success: function(msg){\n alert(\"Connection active!\")\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n if(textStatus == 'timeout') {\n alert('Connection seems dead!');\n }\n }\n });\n"
},
{
"answer_id": 1309061,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "navigator.onLine online offline navigator.onLine"
},
{
"answer_id": 1643423,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "network: function() {\n var state = navigator.onLine ? \"online\" : \"offline\";\n return state;\n}\n"
},
{
"answer_id": 4067713,
"author": "unxed",
"author_id": 493381,
"author_profile": "https://Stackoverflow.com/users/493381",
"pm_score": 2,
"selected": false,
"text": "<!-- the file named \"tt.jpg\" should exist in the same directory -->\n\n<script>\nfunction testConnection(callBack)\n{\n document.getElementsByTagName('body')[0].innerHTML +=\n '<img id=\"testImage\" style=\"display: none;\" ' +\n 'src=\"tt.jpg?' + Math.random() + '\" ' +\n 'onerror=\"testConnectionCallback(false);\" ' +\n 'onload=\"testConnectionCallback(true);\">';\n\n testConnectionCallback = function(result){\n callBack(result);\n\n var element = document.getElementById('testImage');\n element.parentNode.removeChild(element);\n } \n}\n</script>\n\n<!-- usage example -->\n\n<script>\nfunction myCallBack(result)\n{\n alert(result);\n}\n</script>\n\n<a href=# onclick=testConnection(myCallBack);>Am I online?</a>\n"
},
{
"answer_id": 5570815,
"author": "Edmhs",
"author_id": 403411,
"author_profile": "https://Stackoverflow.com/users/403411",
"pm_score": 5,
"selected": false,
"text": " if(navigator.onLine){\n alert('online');\n } else {\n alert('offline');\n }\n"
},
{
"answer_id": 5640276,
"author": "THEO",
"author_id": 704719,
"author_profile": "https://Stackoverflow.com/users/704719",
"pm_score": 3,
"selected": false,
"text": "function checkOnline() {\n setTimeout(\"doOnlineCheck()\", 20000);\n}\n\nfunction doOnlineCheck() {\n //if the server can be reached it returns 1, other wise it times out\n var submitURL = $(\"#base_path\").val() + \"index.php/menu/online\";\n\n $.ajax({\n url : submitURL,\n type : \"post\",\n dataType : \"msg\",\n timeout : 5000,\n success : function(msg) {\n if(msg==1) {\n $(\"#online\").addClass(\"online\");\n $(\"#online\").removeClass(\"offline\");\n } else {\n $(\"#online\").addClass(\"offline\");\n $(\"#online\").removeClass(\"online\");\n }\n checkOnline();\n },\n error : function() {\n $(\"#online\").addClass(\"offline\");\n $(\"#online\").removeClass(\"online\");\n checkOnline();\n }\n });\n}\n"
},
{
"answer_id": 29793305,
"author": "harishr",
"author_id": 1139099,
"author_profile": "https://Stackoverflow.com/users/1139099",
"pm_score": 3,
"selected": false,
"text": "$.ajax({\n type: \"HEAD\",\n url: document.location.pathname + \"?param=\" + new Date(),\n error: function() { return false; },\n success: function() { return true; }\n });\n"
},
{
"answer_id": 35952320,
"author": "wayofthefuture",
"author_id": 2152289,
"author_profile": "https://Stackoverflow.com/users/2152289",
"pm_score": 2,
"selected": false,
"text": "$.ajax({\n url: 'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',\n dataType: 'jsonp',\n timeout: 5000,\n\n error: function(xhr) {\n if (xhr.status == 404) {\n //internet connection working\n }\n else {\n //internet is down (xhr.status == 0)\n }\n }\n});\n"
},
{
"answer_id": 46542948,
"author": "Prakash Pazhanisamy",
"author_id": 8338128,
"author_profile": "https://Stackoverflow.com/users/8338128",
"pm_score": 3,
"selected": false,
"text": "var x = confirm(\"Are you sure you want to submit?\");\nif (x) {\n if (navigator.onLine == true) {\n return true;\n }\n alert('Internet connection is lost');\n return false;\n}\nreturn false;\n"
},
{
"answer_id": 49976613,
"author": "Rishabh Anand",
"author_id": 6540319,
"author_profile": "https://Stackoverflow.com/users/6540319",
"pm_score": -1,
"selected": false,
"text": "<h2>The Navigator Object</h2>\n\n<p>The onLine property returns true if the browser is online:</p>\n\n<p id=\"demo\"></p>\n\n<script>\n document.getElementById(\"demo\").innerHTML = \"navigator.onLine is \" + navigator.onLine;\n</script>\n"
},
{
"answer_id": 50574029,
"author": "Kareem",
"author_id": 2151420,
"author_profile": "https://Stackoverflow.com/users/2151420",
"pm_score": 0,
"selected": false,
"text": "$.ajax({\n url: /your_url,\n type: \"POST or GET\",\n data: your_data,\n success: function(result){\n //do stuff\n },\n error: function(xhr, status, error) {\n\n //detect if user is online and avoid the use of async\n $.ajax({\n type: \"HEAD\",\n url: document.location.pathname,\n error: function() { \n //user is offline, do stuff\n console.log(\"you are offline\"); \n }\n });\n } \n});\n"
},
{
"answer_id": 53820206,
"author": "Didier L",
"author_id": 525036,
"author_profile": "https://Stackoverflow.com/users/525036",
"pm_score": 8,
"selected": false,
"text": "window.navigator.onLine online offline console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');\n\nwindow.addEventListener('online', () => console.log('Became online'));\nwindow.addEventListener('offline', () => console.log('Became offline'));\n\ndocument.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine)); <button id=\"statusCheck\">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />\nCheck the console below for results: window.navigator.onLine true false true false true window.navigator.onLine false offline true online"
},
{
"answer_id": 57119692,
"author": "Vladimir Salguero",
"author_id": 4191716,
"author_profile": "https://Stackoverflow.com/users/4191716",
"pm_score": 2,
"selected": false,
"text": "navigator.onLine XMLHttpRequest XMLHttpRequest.status var xhr = new XMLHttpRequest();\n //index.php is in my web\n xhr.open('HEAD', 'index.php', true);\n xhr.send();\n\n xhr.addEventListener(\"readystatechange\", processRequest, false);\n\n function processRequest(e) {\n if (xhr.readyState == 4) {\n //If you use a cache storage manager (service worker), it is likely that the\n //index.php file will be available even without internet, so do the following validation\n if (xhr.status >= 200 && xhr.status < 304) {\n console.log('On line!');\n } else {\n console.log('Offline :(');\n }\n }\n}\n"
},
{
"answer_id": 58638556,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 4,
"selected": false,
"text": "window.navigator.onLine\n window.addEventListener(\"offline\", \n ()=> console.log(\"No Internet\")\n);\n window.addEventListener(\"online\", \n ()=> console.log(\"Connected Internet\")\n);\n"
},
{
"answer_id": 64094422,
"author": "Giddy Naya",
"author_id": 8043806,
"author_profile": "https://Stackoverflow.com/users/8043806",
"pm_score": 3,
"selected": false,
"text": "it is browser centric most browsers implement this property differently true false the value is only updated when the user follows links or when a script requests a remote page. true // This fetches your website's favicon, so replace path with favicon url\n// Notice the appended date param which helps prevent browser caching.\nfetch('/favicon.ico?d='+Date.now())\n .then(response => {\n if (!response.ok)\n throw new Error('Network response was not ok');\n\n // At this point we can safely assume the user has connection to the internet\n console.log(\"Internet connection available\"); \n })\n .catch(error => {\n // The resource could not be reached\n console.log(\"No Internet connection\", error);\n });\n // Firstly you trigger a resource available from a reputable site\n// For demo purpose you can use the favicon from MSN website\n// Also notice the appended date param which helps skip browser caching.\nfetch('https://static-global-s-msn-com.akamaized.net/hp-neu/sc/2b/a5ea21.ico?d='+Date.now())\n .then(response => {\n // Check if the response is successful\n if (!response.ok)\n throw new Error('Network response was not ok');\n\n// At this point we can safely say the user has connection to the internet\n console.log(\"Internet available\"); \n })\n .catch(error => {\n // The resource could not be reached\n console.log(\"No Internet connection\", error);\n });\n"
},
{
"answer_id": 64964557,
"author": "Karan Tewari",
"author_id": 3276999,
"author_profile": "https://Stackoverflow.com/users/3276999",
"pm_score": 0,
"selected": false,
"text": "navigator.onLine true"
},
{
"answer_id": 66299738,
"author": "Siddhartha",
"author_id": 8505763,
"author_profile": "https://Stackoverflow.com/users/8505763",
"pm_score": 0,
"selected": false,
"text": "function isInternetConnected(){return navigator.onLine;}\n"
},
{
"answer_id": 67297672,
"author": "CantThinkOfAnything",
"author_id": 3114383,
"author_profile": "https://Stackoverflow.com/users/3114383",
"pm_score": 2,
"selected": false,
"text": " fetch('https://google.com', {\n method: 'GET', // *GET, POST, PUT, DELETE, etc.\n mode: 'no-cors',\n }).then((result) => {\n console.log(result)\n }).catch(e => {\n console.error(e)\n })\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
189,436
|
<p>When I try to test the AutoLotWCFService using "wcftestclient", I get the following error. What am I doing wrong? Any insight will help. This is a simple Web Service that has wshttpbinding with interface contract and the implementation in the service. Here is the long error message: The Web.Config file has 2 endpoints - one for Web Service itself and other for metaDataExchange. Its all pretty much default stuff. I can include the code if needed - it seems I cannot attach files here.</p>
<hr>
<pre><code>Error: Cannot obtain Metadata from http://localhost/AutoLotWCFService/Service.svc
If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.
For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.
WS-Metadata Exchange Error
URI: http://localhost/AutoLotWCFService/Service.svc
Metadata contains a reference that cannot be resolved: 'http://localhost/AutoLotWCFService/Service.svc'.
The remote server returned an unexpected response: (405) Method not allowed.
The remote server returned an error: (405) Method Not Allowed.
HTTP GET Error URI: http://localhost/AutoLotWCFService/Service.svc
The document at the url http://localhost/AutoLotWCFService/Service.svc was not recognized as a known document type.The error message from each known type may help you fix the problem:
- Report from 'DISCO Document' is 'Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.'.
- Report from 'WSDL Document' is 'There is an error in XML document (1, 2).' -Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.
- Report from 'XML Schema' is 'Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.'.
</code></pre>
<hr>
|
[
{
"answer_id": 189459,
"author": "Craig Wilson",
"author_id": 25333,
"author_profile": "https://Stackoverflow.com/users/25333",
"pm_score": 0,
"selected": false,
"text": "<serviceBehaviors>\n <behavior name=\"serviceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\">\n </behavior>\n</serviceBehaviors>\n \n<service name=\"blah\" behaviorConfiguration=\"serviceBehavior\">\n"
},
{
"answer_id": 582283,
"author": "VikingProgrammer",
"author_id": 70418,
"author_profile": "https://Stackoverflow.com/users/70418",
"pm_score": 4,
"selected": false,
"text": "CD c:\\windows\\Microsoft.Net\\Framework\\v3.0\\Windows Communication Foundation\\\nServiceModelReg -i\n"
},
{
"answer_id": 5361637,
"author": "cja100",
"author_id": 208795,
"author_profile": "https://Stackoverflow.com/users/208795",
"pm_score": 1,
"selected": false,
"text": "\"%WINDIR%\\Microsoft.Net\\Framework\\v3.0\\Windows Communication Foundation\\ServiceModelReg.exe\" -r\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
189,451
|
<p>My team is trying to setup an Apache reverse proxy from a customer's site into one of our web applications. </p>
<p><a href="http://www.example.com/app1/some-path" rel="noreferrer">http://www.example.com/app1/some-path</a> maps to <a href="http://internal1.example.com/some-path" rel="noreferrer">http://internal1.example.com/some-path</a> </p>
<p>Inside our application we use struts and have redirect = true set on certain actions in order to provide certain functionality. The 302 status messages from these re-directs cause the user to break out of the proxy resulting in an error page for the end user.</p>
<p>HTTP/1.1 302 Found
Location: <a href="http://internal.example.com/some-path/redirect" rel="noreferrer">http://internal.example.com/some-path/redirect</a></p>
<p>Is there any way to setup the reverse proxy in apache so that the redirects work correctly?</p>
<p><a href="http://www.example.com/app1/some-path/redirect" rel="noreferrer">http://www.example.com/app1/some-path/redirect</a></p>
|
[
{
"answer_id": 1614672,
"author": "Marcel Levy",
"author_id": 676,
"author_profile": "https://Stackoverflow.com/users/676",
"pm_score": 2,
"selected": false,
"text": " <VirtualHost example>\n ServerName www.example.com\n\n ProxyPassReverse /app1/some-path/ http://internal1.example.com/some-path/\n RewriteEngine On\n RewriteRule /app1/(.*) http://internal1.example.com/some-path$1 [P]\n\n ...\n </VirtualHost>\n ProxyPassReverse / http://internal1.example.com/some-path\n ProxyPassReverse / http://internal2.example.com/some-path\n"
},
{
"answer_id": 55080298,
"author": "philippn",
"author_id": 4633326,
"author_profile": "https://Stackoverflow.com/users/4633326",
"pm_score": 2,
"selected": false,
"text": "ProxyPassReverse ProxyPassReverse / http://internal1.example.com/some-path/\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6021/"
] |
189,468
|
<p>I've had nothing but good luck from SO, so why not try again?</p>
<p>I have an application that needs to show a different image based on the season of the year (spring, summer, winter, fall). I have very specific start and end dates for these seasons.</p>
<p>What I would like from you geniuses is a method called GetSeason that takes a date as input and returns a String value of Spring, Summer, Winter or Fall. Here are the date ranges and their associated seasons:<br></p>
<p>Spring:3/1-4/30<br>
Summer:5/1-8/31<br>
Fall:9/1-10/31<br>
Winter: 11/1-2/28</p>
<p>Can someone provide a working method to return the proper season?
Thanks everyone!</p>
|
[
{
"answer_id": 189504,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 1,
"selected": false,
"text": "String getSeason(int month) {\n switch(month) {\n case 11:\n case 12:\n case 1:\n case 2:\n return \"winter\";\n case 3:\n case 4:\n return \"spring\";\n case 5:\n case 6:\n case 7:\n case 8:\n return \"summer\";\n default:\n return \"autumn\";\n }\n}\n public static Enum Season {\n WINTER(Arrays.asList(11,12,1,2)),\n SPRING(Arrays.asList(3,4)),\n SUMMER(Arrays.asList(5,6,7,8)),\n AUTUMN(Arrays.asList(9,10));\n\n Season(List<Integer> months) {\n this.monthlist = months;\n }\n private List<Integer> monthlist;\n public boolean inSeason(int month) {\n return this.monthlist.contains(month); // if months are 0 based, then insert +1 before the )\n }\n\n public static Season seasonForMonth(int month) {\n for(Season s: Season.values()) {\n if (s.inSeason(month))\n return s;\n }\n throw new IllegalArgumentException(\"Unknown month\");\n }\n}\n"
},
{
"answer_id": 189506,
"author": "Jorn",
"author_id": 8681,
"author_profile": "https://Stackoverflow.com/users/8681",
"pm_score": 0,
"selected": false,
"text": "switch (date.getMonth()) {\n case Calendar.JANUARY:\n case Calendar.FEBRUARY:\n return \"winter\";\n case Calendar.MARCH:\n return \"spring\";\n //etc\n}\n default:\n throw new IllegalArgumentException();\n"
},
{
"answer_id": 189521,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 4,
"selected": true,
"text": "private static final String seasons[] = {\n \"Winter\", \"Winter\", \"Spring\", \"Spring\", \"Summer\", \"Summer\", \n \"Summer\", \"Summer\", \"Fall\", \"Fall\", \"Winter\", \"Winter\"\n};\npublic String getSeason( Date date ) {\n return seasons[ date.getMonth() ];\n}\n\n// As stated above, getMonth() is deprecated, but if you start with a Date, \n// you'd have to convert to Calendar before continuing with new Java, \n// and that's not fast.\n"
},
{
"answer_id": 189553,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 1,
"selected": false,
"text": "import java.util.*\n\npublic String getSeason(Date today, int year){\n\n // the months are one less because GC is 0-based for the months, but not days.\n // i.e. 0 = January.\n String returnMe = \"\";\n\n GregorianCalender dateToday = new GregorianCalender(year, today.get(Calender.MONTH_OF_YEAR), today.get(Calender.DAY_OF_MONTH);\n GregorianCalender springstart = new GregorianCalender(year, 2, 1);\n GregorianCalender springend = new GregorianCalender(year, 3, 30);\n GregorianCalender summerstart = new GregorianCalender(year, 4, 1);\n GregorianCalender summerend = new GregorianCalender(year, 7, 31);\n GregorianCalender fallstart = new GregorianCalender(year, 8, 1);\n GregorianCalender fallend = new GregorianCalender(year, 9, 31);\n GregorianCalender winterstart = new GregorianCalender(year, 10, 1);\n GregorianCalender winterend = new GregorianCalender(year, 1, 28);\n\n if ((dateToday.after(springstart) && dateToday.before(springend)) || dateToday.equals(springstart) || dateToday.equals(springend)){\n returnMe = \"Spring\";\n\n else if ((dateToday.after(summerstart) && dateToday.before(summerend)) || dateToday.equals(summerstart) || dateToday.equals(summerend)){\n returnMe = \"Summer\";\n\n else if ((dateToday.after(fallstart) && dateToday.before(fallend)) || dateToday.equals(fallstart) || dateToday.equals(fallend)){\n returnMe = \"Fall\";\n\n else if ((dateToday.after(winterstart) && dateToday.before(winterend)) || dateToday.equals(winterstart) || dateToday.equals(winterend)){\n returnMe = \"Winter\";\n\n else {\n returnMe = \"Invalid\";\n }\n return returnMe;\n}\n"
},
{
"answer_id": 4293499,
"author": "Hjohnson",
"author_id": 522492,
"author_profile": "https://Stackoverflow.com/users/522492",
"pm_score": 1,
"selected": false,
"text": "public class lab6project1 {\n public static void main(String[] args) {\n Scanner keyboard = new Scanner(System.in);\n\n System.out.println(\"This program reports the season for a given day and month\");\n System.out.println(\"Please enter the month and day as integers with a space between the month and day\");\n\n int month = keyboard.nextInt();\n int day = keyboard.nextInt();\n\n\n if ((month == 1) || (month == 2)) {\n System.out.println(\"The season is Winter\");\n } else if ((month == 4) || (month == 5)) {\n System.out.println(\"The season is Spring\");\n } else if ((month == 7) || (month == 8)) {\n System.out.println(\"The season is Summer\");\n } else if ((month == 10) || (month == 11)) {\n System.out.println(\"The season is Fall\");\n } else if ((month == 3) && (day <= 19)) {\n System.out.println(\"The season is Winter\");\n } else if (month == 3) {\n System.out.println(\"The season is Spring\");\n } else if ((month == 6) && (day <= 20)) {\n System.out.println(\"The season is Spring\");\n } else if (month == 6) {\n System.out.println(\"The season is Summer\");\n } else if ((month == 9) && (day <= 20)) {\n System.out.println(\"The season is Summer\");\n } else if (month == 9) {\n System.out.println(\"The season is Autumn\");\n } else if ((month == 12) && (day <= 21)) {\n System.out.println(\"The season is Autumn\");\n } else if (month == 12) {\n System.out.println(\"The season is Winter\");\n }\n }\n}\n"
},
{
"answer_id": 38033293,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "Month Month EnumSet EnumSet EnumSet<Month> spring = EnumSet.of( Month.MARCH , Month.APRIL );\nEnumSet<Month> summer = EnumSet.of( Month.MAY , Month.JUNE , Month.JULY , Month.AUGUST );\nEnumSet<Month> fall = EnumSet.of( Month.SEPTEMBER , Month.OCTOBER );\nEnumSet<Month> winter = EnumSet.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY );\n ZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nZonedDateTime zdt = ZonedDateTime.now( zoneId );\n Month Month month = Month.from( zdt );\n EnumSet contains if ( spring.contains( month ) ) {\n …\n} else if ( summer.contains( month ) ) {\n …\n} else if ( fall.contains( month ) ) {\n …\n} else if ( winter.contains( month ) ) {\n …\n} else {\n // FIXME: Handle reaching impossible point as error condition.\n}\n public enum Season { SPRING, SUMMER, FALL, WINTER; } of package work.basil.example;\n\nimport java.time.Month;\n\npublic enum Season {\n SPRING, SUMMER, FALL, WINTER;\n\n static public Season of ( final Month month ) {\n switch ( month ) {\n\n // Spring.\n case MARCH: // Java quirk: An enum switch case label must be the unqualified name of an enum. So cannot use `Month.MARCH` here, only `MARCH`.\n return Season.SPRING;\n\n case APRIL:\n return Season.SPRING;\n\n // Summer.\n case MAY:\n return Season.SUMMER;\n\n case JUNE:\n return Season.SUMMER;\n\n case JULY:\n return Season.SUMMER;\n\n case AUGUST:\n return Season.SUMMER;\n\n // Fall.\n case SEPTEMBER:\n return Season.FALL;\n\n case OCTOBER:\n return Season.FALL;\n\n // Winter.\n case NOVEMBER:\n return Season.WINTER;\n\n case DECEMBER:\n return Season.WINTER;\n\n case JANUARY:\n return Season.WINTER;\n\n case FEBRUARY:\n return Season.WINTER;\n\n default:\n System.out.println ( \"ERROR.\" ); // FIXME: Handle reaching impossible point as error condition.\n return null;\n }\n }\n\n}\n package work.basil.example;\n\nimport java.time.Month;\nimport java.util.Objects;\n\npublic enum Season\n{\n SPRING, SUMMER, FALL, WINTER;\n\n static public Season of ( final Month month )\n {\n Objects.requireNonNull( month , \"ERROR - Received null where a `Month` is expected. Message # 0ac03df9-1c5a-4c2d-a22d-14c40e25c58b.\" );\n return\n switch ( Objects.requireNonNull( month ) )\n {\n // Spring.\n case MARCH , APRIL -> Season.SPRING;\n\n // Summer.\n case MAY , JUNE , JULY , AUGUST -> Season.SUMMER;\n\n // Fall.\n case SEPTEMBER , OCTOBER -> Season.FALL;\n\n // Winter.\n case NOVEMBER , DECEMBER , JANUARY , FEBRUARY -> Season.WINTER;\n }\n ;\n }\n}\n ZoneId zoneId = ZoneId.of ( \"America/Montreal\" );\nZonedDateTime zdt = ZonedDateTime.now ( zoneId );\nMonth month = Month.from ( zdt );\nSeason season = Season.of ( month );\n System.out.println ( \"zdt: \" + zdt + \" | month: \" + month + \" | season: \" + season );\n"
},
{
"answer_id": 39266771,
"author": "Volodymyr Machekhin",
"author_id": 4847691,
"author_profile": "https://Stackoverflow.com/users/4847691",
"pm_score": 0,
"selected": false,
"text": " Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(timeInMills);\n int month = calendar.get(Calendar.MONTH);\n CurrentSeason = month == 11 ? 0 : (month + 1) / 3;\n"
},
{
"answer_id": 53662468,
"author": "Meno Hochschild",
"author_id": 2491410,
"author_profile": "https://Stackoverflow.com/users/2491410",
"pm_score": 0,
"selected": false,
"text": "java.util.Date // your input\n java.util.Date d = new java.util.Date();\n ZoneId tz = ZoneId.systemDefault();\n\n // extract the relevant month-day\n ZonedDateTime zdt = d.toInstant().atZone(tz);\n MonthDay md = MonthDay.of(zdt.getMonth(), zdt.getDayOfMonth());\n\n // a definition with day-of-month other than first is possible here\n MonthDay beginOfSpring = MonthDay.of(3, 1);\n MonthDay beginOfSummer = MonthDay.of(5, 1);\n MonthDay beginOfAutumn = MonthDay.of(9, 1);\n MonthDay beginOfWinter = MonthDay.of(11, 1);\n\n // determine the season\n Season result;\n\n if (md.isBefore(beginOfSpring)) {\n result = Season.WINTER;\n } else if (md.isBefore(beginOfSummer)) {\n result = Season.SPRING;\n } else if (md.isBefore(beginOfAutumn)) {\n result = Season.SUMMER;\n } else if (md.isBefore(beginOfWinter)) {\n result = Season.FALL;\n } else {\n result = Season.WINTER;\n }\n\n System.out.println(result);\n public enum Season { SPRING, SUMMER, FALL, WINTER; } // your input\n java.util.Date d = new java.util.Date();\n boolean isSouthern = false;\n\n Moment m = TemporalType.JAVA_UTIL_DATE.translate(d);\n AstronomicalSeason result = AstronomicalSeason.of(m);\n\n if (isSouthern) { // switch to southern equivalent if necessary\n result = result.onSouthernHemisphere();\n }\n\n System.out.println(result);\n"
},
{
"answer_id": 62012826,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 0,
"selected": false,
"text": "/**\n * @return 1 - winter, 2 - spring, 3 - summer, 4 - autumn\n */\nprivate static int getDateSeason(LocalDate date) {\n return date.plus(1, MONTHS).get(IsoFields.QUARTER_OF_YEAR);\n}\n private static LocalDate atStartOfSeason(LocalDate date) {\n return date.plus(1, MONTHS).with(IsoFields.DAY_OF_QUARTER, 1).minus(1, MONTHS);\n}\n\nprivate static LocalDate afterEndOfSeason(LocalDate date) {\n return atStartOfSeason(date).plus(3, MONTHS);\n}\n"
},
{
"answer_id": 67847519,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "import java.util.Scanner;\n\npublic class Season {\n\npublic static void main (String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n System.out.println(\"Enter the month:\");\n\n int mon=sc.nextInt();\n\n if(mon>12||mon<1)\n {\n System.out.println(\"Invalid month\");\n }\n\n else if(mon>=3&&mon<=5)\n {\n System.out.println(\"Season:Spring\");\n }\n\n else if(mon>=6&&mon<=8)\n {\n System.out.println(\"Season:Summer\");\n }\n\n else if(mon>=9&&mon<=11)\n {\n System.out.println(\"Season:Autumn\");\n }\n\n else if(mon==12||mon==1||mon==2)\n {\n System.out.println(\"Season:Winter\");\n }\n}\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172/"
] |
189,475
|
<p>I want to know how to set the height property for the HTML <code><select></code> in code.</p>
<p>I tried setting <code>.Attribute.Add("Style","Height:120px")</code> just to see if I could get it to change but to no avail.</p>
|
[
{
"answer_id": 189514,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "DropDownList myDropDown;\nmyDropDown.Style[\"height\"] = \"120px\";\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25642/"
] |
189,490
|
<p>I tried looking for the .emacs file for my Windows installation for Emacs, but I could not find it. Does it have the same filename under Windows as in Unix?</p>
<p>Do I have to create it myself? If so, under what specific directory does it go?</p>
|
[
{
"answer_id": 189509,
"author": "Node",
"author_id": 7190,
"author_profile": "https://Stackoverflow.com/users/7190",
"pm_score": 8,
"selected": true,
"text": ".emacs _emacs .emacs.d/init.el .emacs.d C:\\.emacs C:/ C:/ ~ C-x C-f ~/.emacs"
},
{
"answer_id": 189519,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 5,
"selected": false,
"text": "C:\\Users\\<USER>\\AppData\\Roaming\\"
},
{
"answer_id": 189541,
"author": "polarbear",
"author_id": 3636,
"author_profile": "https://Stackoverflow.com/users/3636",
"pm_score": 1,
"selected": false,
"text": "C:\\Documents and Settings\\yourusernamehere\\Application Data\\\n"
},
{
"answer_id": 189605,
"author": "sverrejoh",
"author_id": 473,
"author_profile": "https://Stackoverflow.com/users/473",
"pm_score": 5,
"selected": false,
"text": "C-x C-f ~/.emacs\n"
},
{
"answer_id": 192097,
"author": "gone",
"author_id": 26880,
"author_profile": "https://Stackoverflow.com/users/26880",
"pm_score": 7,
"selected": false,
"text": "C-H v user-init-file RET M-x eval-expression RET (find-file user-init-file) RET"
},
{
"answer_id": 1991329,
"author": "Gauthier",
"author_id": 108802,
"author_profile": "https://Stackoverflow.com/users/108802",
"pm_score": 2,
"selected": false,
"text": "~/.emacs.d/init.el\n ~"
},
{
"answer_id": 3431275,
"author": "ex_",
"author_id": 99361,
"author_profile": "https://Stackoverflow.com/users/99361",
"pm_score": 2,
"selected": false,
"text": "HKCU\\SOFTWARE\\GNU\\Emacs\\HOME\n"
},
{
"answer_id": 11060532,
"author": "phils",
"author_id": 324105,
"author_profile": "https://Stackoverflow.com/users/324105",
"pm_score": 2,
"selected": false,
"text": "user-init-file (find-file user-init-file) (expand-file-name user-init-file)"
},
{
"answer_id": 20136853,
"author": "user3020269",
"author_id": 3020269,
"author_profile": "https://Stackoverflow.com/users/3020269",
"pm_score": 3,
"selected": false,
"text": "Ctrl-x Ctrl-f ~/.emacs"
},
{
"answer_id": 24796523,
"author": "caisah",
"author_id": 1088234,
"author_profile": "https://Stackoverflow.com/users/1088234",
"pm_score": 2,
"selected": false,
"text": "init.el C:\\Users\\user-name\\AppData\\Roaming\\.emacs.d\\ init.el init.el.txt"
},
{
"answer_id": 53126164,
"author": "PatS",
"author_id": 3281336,
"author_profile": "https://Stackoverflow.com/users/3281336",
"pm_score": 2,
"selected": false,
"text": "~/.emacs.el %USERPROFILE%\\AppData\\Roaming\\.emacs.d\\init.el user-emacs-directory\n\"~/.emacs.d/\"\n user-emacs-directory ~/.emacs.d %USERPROFILE%\\.emacs.d\\init.el expand-file-name (expand-file-name user-emacs-directory)\n\"c:/Users/pats/AppData/Roaming/.emacs.d/\"\n emacs.el %USERPROFILE%\\AppData\\Roaming\\.emacs.d\\init.el ~/myenv/emacs/*.el Warning (initialization): An error occurred while loading ‘c:/Users/pats/AppData/Roaming/.emacs.d/init.el’:\n ~/myenv/emacs/*.el HOME %USERPROFILE% HOME=%USERPROFILE% $HOME/.emacs.el %USERPROFILE%\\AppData\\Roaming\\.emacs.d\\init.el %USERPROFILE\\AppData\\Roaming %USERPROFILE% %USERPROFILE\\AppData\\Roaming %USERPROFILE\\AppData\\Local"
},
{
"answer_id": 60881230,
"author": "ZhaoGang",
"author_id": 2830167,
"author_profile": "https://Stackoverflow.com/users/2830167",
"pm_score": 0,
"selected": false,
"text": "HOME .emacs c:\\ .emacs _emacs .emacs"
},
{
"answer_id": 63978955,
"author": "ksinkar",
"author_id": 551046,
"author_profile": "https://Stackoverflow.com/users/551046",
"pm_score": 2,
"selected": false,
"text": "$XDG_CONFIG_HOME $XDG_CONFIG_HOME/emacs/init.el $XDG_CONFIG_HOME %LOCALAPPDATA% M-x eval-expression user-init-file\n user-emacs-directory\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
189,493
|
<p>Every so often when I'm debugging, I get this message in nice brown text on an ASP.NET error page:</p>
<blockquote>
<p><em>Access to the path
"c:\windows\microsoft.net\framework\(version)\Temporary ASP.NET Files\(blah)"
is denied.</em></p>
</blockquote>
<p>I've never been able to figure out what causes it, what really fixes it, and why it happens.</p>
<p>Often times the path after the "Temporary ASP.NET Files" portion (the "(blah)") does not exist, so I'm not sure why it's looking there.</p>
<p>Sometimes an IISRESET fixes it, and sometimes it doesn't.</p>
<p>Sometimes an aspnet_regiis fixes it, and sometimes it doesn't. </p>
<p>Sometimes a reboot fixes it, and sometimes it doesn't.</p>
<p>For what it's worth I ran into this today with some .NET 1.1 code (yes, still maintaining some - hoping to upgrade it soon) and I'm not sure if I've ever seen it with .NET 2.0 and above. </p>
<p>Does anyone know what causes this and what should fix it? I assume it has multiple possible causes but I'm just curious if someone could shed some light on it.</p>
|
[
{
"answer_id": 40347868,
"author": "Eddie Fletcher",
"author_id": 1413853,
"author_profile": "https://Stackoverflow.com/users/1413853",
"pm_score": 0,
"selected": false,
"text": "IIS_IUSRS C:\\Windows\\Temp Result is ACCESS DENIED csc.exe C:\\Windows\\Temp"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
] |
189,499
|
<p>According to the doucmentation for "Directory.Delete( "path", true )", it remove directories, subdirectories, and files in the path.</p>
<p>What does Directory.Delete( "path", false ) do? According to the doucmentation it does "otherwise".</p>
<p>I mean how can you delete a directory without removing the directory, subdirectories, and files?</p>
|
[
{
"answer_id": 189528,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "false"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
189,516
|
<p>For ActionScript 2, I've used <a href="http://www.naturaldocs.org/" rel="noreferrer">NaturalDocs</a>. However it has pretty poor support for PHP. I've looked so far at <a href="http://www.doxygen.nl/" rel="noreferrer">doxygen</a> and <a href="http://www.phpdoc.org/" rel="noreferrer">phpDocumentor</a>, but their output is pretty ugly in my opinion. Does anyone have any experience with automatic documentation generation for PHP? I'd prefer to be able to use javadoc-style tags, they are short to write and easy to remember.</p>
|
[
{
"answer_id": 1926510,
"author": "Pascal MARTIN",
"author_id": 138475,
"author_profile": "https://Stackoverflow.com/users/138475",
"pm_score": 4,
"selected": false,
"text": "@param type name description of the parameter @return type description of the return value @throws type description of the exception that can be thrown"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] |
189,522
|
<p>any thoughts on this would be appreciated:</p>
<pre><code>std::string s1 = "hello";
std::string s2 = std::string(s1);
</code></pre>
<p>I'd now expect these two strings to be independent, i.e. I could append ", world" to s2 and s1 would still read "hello". This is what I find on windows and linux but running the code on a HP_UX machine it seems that s2 and s1 are the same string, so modifying s2 changes s1.</p>
<p>Does this sound absolutely crazy, anyone seen anything similar?</p>
|
[
{
"answer_id": 189539,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <string>\n\nint main () \n{\n std::string s1 = \"hello\"; \n std::string s2 = std::string(s1); // note: std::string s2( s1); would reduce the number of copy ctor calls\n\n s2.append( \", world\");\n\n printf( \"%s\\n\", s1.c_str());\n printf( \"%s\\n\", s2.c_str());\n}\n"
},
{
"answer_id": 189587,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "string s1(\"abc\");\nstring::iterator i = s1.begin();\nstring s2 = s1;\n*i = ’a’; // Must modify only s1\n"
},
{
"answer_id": 191747,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n#include <string>\n\nclass S : public std::string // An extension of std::string\n{\npublic:\n explicit S(const char* s)\n : std::string(s)\n {\n }\n};\n\nclass N // Wraps an int\n{\npublic:\n explicit N(int n)\n : _n(n)\n {}\n operator S() const // Converts to a string extension\n {\n return _n == 0 ? S(\"zero\") : (_n == 1 ? S(\"one\") : S(\"other\"));\n }\nprivate:\n int _n;\n};\n\nint main(int, char**)\n{\n N n0 = N(0);\n N n1 = N(1);\n\n std::string zero = n0;\n std::cout << \"zero = \" << zero << std::endl;\n std::string one = n1;\n std::cout << \"zero = \" << zero\n << \", one = \" << one << std::endl;\n\n return 0;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26665/"
] |
189,523
|
<p>I have already extracted the tag from the source document using grep but, now I cant seem to figure out how to easily extract the properties from the string. Also I want to avoid having to use any programs that would not usually be present on a standard installation. </p>
<pre><code>$tag='<img src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg" title="Don't we all." alt="Barrel - Part 1" />'
</code></pre>
<p>I need to end up with the following variables</p>
<pre><code>$src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg"
$title="Don't we all."
$alt="Barrel - Part 1"
</code></pre>
|
[
{
"answer_id": 189735,
"author": "GameFreak",
"author_id": 26659,
"author_profile": "https://Stackoverflow.com/users/26659",
"pm_score": 1,
"selected": false,
"text": "src=`echo $tag | sed 's/.*src=[\"]\\(.*\\)[\"] title=[\"]\\(.*\\)[\"] alt=[\"]\\(.*\\)[\"].*/\\1/'` \ntitle=`echo $tag | sed 's/.*src=[\"]\\(.*\\)[\"] title=[\"]\\(.*\\)[\"] alt=[\"]\\(.*\\)[\"].*/\\2/'` \nalt=`echo $tag | sed 's/.*src=[\"]\\(.*\\)[\"] title=[\"]\\(.*\\)[\"] alt=[\"]\\(.*\\)[\"].*/\\3/'`\n"
},
{
"answer_id": 189890,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "$ echo $tag|xmlstarlet sel -t --value-of '//img/@src'\nhttp://imgs.xkcd.com/comics/barrel_cropped_(1).jpg\n $ get_attribute() {\n echo $1 | xmlstarlet sel -t -o \""\" -v $2 -o \""\"\n }\n$ src=get_attribute $tag '//img/@src'\n $ get_values() {\n eval file=\\${$#}\n eval $#= \n cmd=\"xmlstarlet sel \"\n for arg in $@\n do\n if [ -n $arg ]\n then\n var=${arg%%\\=*}\n expr=${arg#*=}\n cmd+=\" -t -o \\\"$var="\\\" -v $expr -o \\\""\\\" -n\"\n fi\n done\n eval $cmd $file\n }\n$ eval $(get_values src='//img/@src' title='//img/@title' your_file.xml)\n$ echo $src\nhttp://imgs.xkcd.com/comics/barrel_cropped_(1).jpg\n$ echo $title\nDon't we all.\n"
},
{
"answer_id": 3174307,
"author": "lmxy",
"author_id": 383018,
"author_profile": "https://Stackoverflow.com/users/383018",
"pm_score": 0,
"selected": false,
"text": "tag='<img src=\"http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg\" title=\"Don'\"'\"'t we all.\" alt=\"Barrel - Part 1\" />'\nxmlstarlet sel -T -t -m \"/img\" -m \"@*\" -v '.' -n <<< \"$tag\"\nIFS=$'\\n'\narray=( $(xmlstarlet sel -T -t -m \"/img\" -m \"@*\" -v '.' -n <<< \"$tag\") )\nsrc=\"${array[0]}\"\ntitle=\"${array[1]}\"\nalt=\"${array[2]}\"\n\nprintf \"%s\\n\" \"src: $src\" \"title: $title\" \"alt: $alt\"\n"
},
{
"answer_id": 16438923,
"author": "BeniBela",
"author_id": 1501222,
"author_profile": "https://Stackoverflow.com/users/1501222",
"pm_score": 0,
"selected": false,
"text": "eval $(xidel \"$tag\" -e '<img src=\"{$src}\" title=\"{$title}\" alt=\"{$alt}\"/>' --output-format bash)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26659/"
] |
189,534
|
<p>I am current writing an application that will require multiple inserts, updates and deletes for my business entity. I am using the TransactionScope class to guarantee all the stored procedures can commit or roll back as a single unit of work.</p>
<p>My question is, I am required to also use COMMIT TRAN and ROLLBACK TRAN is each of my stored procedures if I am using the TransactionScope class in my .NET class library?</p>
|
[
{
"answer_id": 190332,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "Transaction Binding=Explicit Unbind;"
},
{
"answer_id": 3527397,
"author": "Jared Moore",
"author_id": 425852,
"author_profile": "https://Stackoverflow.com/users/425852",
"pm_score": 1,
"selected": false,
"text": "TransactionScope CommittableTransaction begin transaction SqlConnection.BeginTransaction TransactionScope CommittableTransaction begin transaction SqlTransaction begin transaction"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
189,549
|
<p>Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it?</p>
<p>Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at work who have asked me this and I honestly don't know.</p>
|
[
{
"answer_id": 6362414,
"author": "Lars Holm Jensen",
"author_id": 348005,
"author_profile": "https://Stackoverflow.com/users/348005",
"pm_score": 7,
"selected": false,
"text": "public App()\n{\n AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n}\n\nSystem.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(\".dll\",\"\");\n\n dllName = dllName.Replace(\".\", \"_\");\n\n if (dllName.EndsWith(\"_resources\")) return null;\n\n System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + \".Properties.Resources\", System.Reflection.Assembly.GetExecutingAssembly());\n\n byte[] bytes = (byte[])rm.GetObject(dllName);\n\n return System.Reflection.Assembly.Load(bytes);\n}\n"
},
{
"answer_id": 10600034,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 4,
"selected": false,
"text": "ResolveHandler static void Main()\n{\n AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n {\n string assemblyName = new AssemblyName(args.Name).Name;\n if (assemblyName.EndsWith(\".resources\"))\n return null;\n\n string dllName = assemblyName + \".dll\";\n string dllFullPath = Path.Combine(GetMyApplicationSpecificPath(), dllName);\n\n using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + \".Resources.\" + dllName))\n {\n byte[] data = new byte[stream.Length];\n s.Read(data, 0, data.Length);\n\n //or just byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);\n\n File.WriteAllBytes(dllFullPath, data);\n }\n\n return Assembly.LoadFrom(dllFullPath);\n };\n}\n GetMyApplicationSpecificPath() using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + \".Resources.\" + dllName))\n {\n byte[] data = new byte[stream.Length];\n s.Read(data, 0, data.Length);\n return Assembly.Load(data);\n }\n\n //or just\n\n return Assembly.LoadFrom(dllFullPath); //if location is known.\n"
},
{
"answer_id": 19270093,
"author": "Anton Shepelev",
"author_id": 2862241,
"author_profile": "https://Stackoverflow.com/users/2862241",
"pm_score": 3,
"selected": false,
"text": "Dictionary<string, Assembly> loaded = new Dictionary<string,Assembly>();\nAppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n{ Assembly resAssembly;\n string dllName = args.Name.Contains(\",\") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(\".dll\",\"\");\n dllName = dllName.Replace(\".\", \"_\");\n if ( !loaded.ContainsKey( dllName ) )\n { if (dllName.EndsWith(\"_resources\")) return null;\n System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + \".Properties.Resources\", System.Reflection.Assembly.GetExecutingAssembly());\n byte[] bytes = (byte[])rm.GetObject(dllName);\n resAssembly = System.Reflection.Assembly.Load(bytes);\n loaded.Add(dllName, resAssembly);\n }\n else\n { resAssembly = loaded[dllName]; }\n return resAssembly;\n}; \n static HashSet<string> IncludedAssemblies = new HashSet<string>();\nstring[] resources = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();\nfor(int i = 0; i < resources.Length; i++)\n{ IncludedAssemblies.Add(resources[i]); }\n IncludedAssemblies"
},
{
"answer_id": 19806004,
"author": "Steve",
"author_id": 1330601,
"author_profile": "https://Stackoverflow.com/users/1330601",
"pm_score": 4,
"selected": false,
"text": "AppDomain.CurrentDomain.AssemblyResolve += (sender, bargs) =>\n {\n String dllName = new AssemblyName(bargs.Name).Name + \".dll\";\n var assem = Assembly.GetExecutingAssembly();\n String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));\n if (resourceName == null) return null; // Not found, maybe another handler will find it\n using (var stream = assem.GetManifestResourceStream(resourceName))\n {\n Byte[] assemblyData = new Byte[stream.Length];\n stream.Read(assemblyData, 0, assemblyData.Length);\n return Assembly.Load(assemblyData);\n }\n };\n"
},
{
"answer_id": 20306095,
"author": "Matthias",
"author_id": 568266,
"author_profile": "https://Stackoverflow.com/users/568266",
"pm_score": 11,
"selected": true,
"text": "Install-Package Costura.Fody\n Install-CleanReferencesTarget\n"
},
{
"answer_id": 28919741,
"author": "Josh",
"author_id": 1480854,
"author_profile": "https://Stackoverflow.com/users/1480854",
"pm_score": 4,
"selected": false,
"text": "Install-Package ILRepack.MSBuild.Task <!-- ILRepack -->\n<Target Name=\"AfterBuild\" Condition=\"'$(Configuration)' == 'Release'\">\n\n <ItemGroup>\n <InputAssemblies Include=\"$(OutputPath)\\$(AssemblyName).exe\" />\n <InputAssemblies Include=\"$(OutputPath)\\ExampleAssemblyToMerge.dll\" />\n </ItemGroup>\n\n <ILRepack \n Parallel=\"true\"\n Internalize=\"true\"\n InputAssemblies=\"@(InputAssemblies)\"\n TargetKind=\"Exe\"\n OutputFile=\"$(OutputPath)\\$(AssemblyName).exe\"\n />\n</Target>\n"
},
{
"answer_id": 36916920,
"author": "Mark Llewellyn",
"author_id": 6267034,
"author_profile": "https://Stackoverflow.com/users/6267034",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing Renci;//FOR THE SSH\nusing System.Net;//FOR THE ADDRESS TRANSLATION\nusing System.Reflection;//FOR THE Assembly\n\n//+ref>\"C:\\Program Files (x86)\\Microsoft\\ILMerge\\Renci.SshNet.dll\"\n//+res>\"C:\\Program Files (x86)\\Microsoft\\ILMerge\\Renci.SshNet.dll\"\n//+ico>\"C:\\Program Files (x86)\\Microsoft CAPICOM 2.1.0.2 SDK\\Samples\\c_sharp\\xmldsig\\resources\\Traffic.ico\"\n public static void Main(string[] args)\n{\n AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n .\n"
},
{
"answer_id": 57749050,
"author": "Marcell Toth",
"author_id": 10614791,
"author_profile": "https://Stackoverflow.com/users/10614791",
"pm_score": 4,
"selected": false,
"text": " <PropertyGroup>\n <PublishSingleFile>true</PublishSingleFile>\n </PropertyGroup>\n"
},
{
"answer_id": 62929101,
"author": "Ludovic Feltz",
"author_id": 2576706,
"author_profile": "https://Stackoverflow.com/users/2576706",
"pm_score": 3,
"selected": false,
"text": ".csproj <Target Name=\"AfterResolveReferences\">\n <ItemGroup>\n <EmbeddedResource Include=\"@(ReferenceCopyLocalPaths)\" Condition=\"'%(ReferenceCopyLocalPaths.Extension)' == '.dll'\">\n <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>\n </EmbeddedResource>\n </ItemGroup>\n</Target>\n Program.cs [STAThreadAttribute]\npublic static void Main()\n{\n AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;\n App.Main();\n}\n OnResolveAssembly private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)\n{\n Assembly executingAssembly = Assembly.GetExecutingAssembly();\n AssemblyName assemblyName = new AssemblyName(args.Name);\n\n var path = assemblyName.Name + \".dll\";\n if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) path = String.Format(@\"{0}\\{1}\", assemblyName.CultureInfo, path);\n\n using (Stream stream = executingAssembly.GetManifestResourceStream(path))\n {\n if (stream == null) return null;\n\n var assemblyRawBytes = new byte[stream.Length];\n stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);\n return Assembly.Load(assemblyRawBytes);\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133/"
] |
189,552
|
<p>I'm trying to host a subdomain for my site with a different hosting company and I'm running into issues on how to set it up.</p>
<p>Here are the specifics:</p>
<ul>
<li>Domain is registered with GoDaddy.</li>
<li>Nameservers are pointing to DiscountASP.net where ASP.NET app has been happily running for couple of years.</li>
<li>Would like <code>blog.mydomain.example</code> to point to my account with DreamHost.com to take advantage of their LAMP stack.</li>
</ul>
<p>I have added <code>blog.mydomain.example</code> to DreamHost (after adding <code>mydomain.example</code>) via their control panel. I thought I would be able to add a subdomain entry on GoDaddy to point to DreamHost, but all they allow is <code>blog.mydomain.example</code> = new URL.</p>
<p>In theory I could just take our .biz or .net domain and host it on DreamHost but was hoping I could do it all with a subdomain.</p>
<p>So, to summarize I'd like to know if what I want to do is feasible and if so, how do I go about it (given the constraints of GoDaddy, DiscountASP, & DreamHost).</p>
|
[
{
"answer_id": 189563,
"author": "Saif Khan",
"author_id": 23667,
"author_profile": "https://Stackoverflow.com/users/23667",
"pm_score": 8,
"selected": true,
"text": "mydomain.example anothersite.mydomain.example anothersite.mydomain.example"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3262/"
] |
189,555
|
<p>I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.</p>
<p>How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.</p>
|
[
{
"answer_id": 189580,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 8,
"selected": true,
"text": "import urllib, urllib2, cookielib\n\nusername = 'myuser'\npassword = 'mypassword'\n\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nlogin_data = urllib.urlencode({'username' : username, 'j_password' : password})\nopener.open('http://www.example.com/login.php', login_data)\nresp = opener.open('http://www.example.com/hiddenpage.php')\nprint resp.read()\n resp.read() opener"
},
{
"answer_id": 12103969,
"author": "Boden Garman",
"author_id": 584423,
"author_profile": "https://Stackoverflow.com/users/584423",
"pm_score": 7,
"selected": false,
"text": "from requests import session\n\npayload = {\n 'action': 'login',\n 'username': USERNAME,\n 'password': PASSWORD\n}\n\nwith session() as c:\n c.post('http://example.com/login.php', data=payload)\n response = c.get('http://example.com/protected_page.php')\n print(response.headers)\n print(response.text)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26668/"
] |
189,557
|
<p>We're running a java/hibernate app going against ORACLE 10g in TESTING. Once in a while, we're seeing this error:</p>
<blockquote>
<p>ORA-00942: table or view does not exist</p>
</blockquote>
<p>Is there a way to find out which table/view(s) ORACLE is talking about ?</p>
<p>I know that I can add extra levels of logging in hibernate which will show all the SQL that it executes on ORACLE and then run that SQL to figure out which TABLE/VIEW is missing or missing permission. But given that it is in TESTING/STAGING, that will slow down performance.</p>
<p>Is there a simple way to narrow down on the Table/View Name ?</p>
<h2>UPDATE :</h2>
<p>Just so you know, I don't have control over the Oracle DB Server Environment. <br>
I enabled Hibernate tracing/logging and found a VALID SQL. I even put Wireshark(which is a TCP packet filter) to see what hibernate actually sends and that was a valid SQL. So, why would Oracle complain about it once in a while and NOT always.</p>
|
[
{
"answer_id": 190614,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 3,
"selected": false,
"text": "create table caught_errors (\n dt date, \n username varchar2( 30), -- value from ora_login_user\n msg varchar2(2000),\n stmt varchar2(2000)\n);\n\n\ncreate or replace trigger catch_errors\n after servererror on database\ndeclare\n sql_text ora_name_list_t;\n msg_ varchar2(2000) := null;\n stmt_ varchar2(2000) := null;\nbegin\n\n for depth in 1 .. ora_server_error_depth loop\n msg_ := msg_ || ora_server_error_msg(depth);\n end loop;\n\n for i in 1 .. ora_sql_txt(sql_text) loop\n stmt_ := stmt_ || sql_text(i);\n end loop;\n\n insert into \n caught_errors (dt , username ,msg ,stmt )\n values (sysdate, ora_login_user,msg_,stmt_);\nend;\n/\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11142/"
] |
189,559
|
<p>Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.</p>
<p>Is there a simpler way than:</p>
<pre class="lang-java prettyprint-override"><code>List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
</code></pre>
|
[
{
"answer_id": 189568,
"author": "Tim",
"author_id": 5284,
"author_profile": "https://Stackoverflow.com/users/5284",
"pm_score": 5,
"selected": false,
"text": "List<String> newList = new ArrayList<String>(listOne);\nnewList.addAll(listTwo);\n"
},
{
"answer_id": 189569,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 9,
"selected": false,
"text": "List<String> newList = new ArrayList<String>(listOne);\nnewList.addAll(listTwo);\n"
},
{
"answer_id": 189572,
"author": "Jorn",
"author_id": 8681,
"author_profile": "https://Stackoverflow.com/users/8681",
"pm_score": 5,
"selected": false,
"text": "List<String> newList = new ArrayList<String>(listOne);\nnewList.addAll(listTwo);\n"
},
{
"answer_id": 189699,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 7,
"selected": false,
"text": "List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };\n"
},
{
"answer_id": 189742,
"author": "deterb",
"author_id": 15585,
"author_profile": "https://Stackoverflow.com/users/15585",
"pm_score": 4,
"selected": false,
"text": "(newList = new ArrayList<String>(list1)).addAll(list2);\n"
},
{
"answer_id": 189752,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 3,
"selected": false,
"text": "public class Lists {\n\n private Lists() { } // can't be instantiated\n\n public static List<T> join(List<T>... lists) {\n List<T> result = new ArrayList<T>();\n for(List<T> list : lists) {\n result.addAll(list);\n }\n return results;\n }\n\n}\n import static Lists.join;\nList<T> result = join(list1, list2, list3, list4);\n"
},
{
"answer_id": 190165,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": -1,
"selected": false,
"text": "List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + \", \" + listTwo.toString().subString(1, listTwo.length() - 1)).split(\", \")));\n"
},
{
"answer_id": 190713,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 0,
"selected": false,
"text": "Collection mergedList = Collections.list(new sun.misc.CompoundEnumeration(new Enumeration[] {\n new Vector(list1).elements(),\n new Vector(list2).elements(),\n ...\n}))\n"
},
{
"answer_id": 190918,
"author": "alex",
"author_id": 26787,
"author_profile": "https://Stackoverflow.com/users/26787",
"pm_score": 2,
"selected": false,
"text": "public static <E> Collection<E> addAll(Collection<E> dest, Collection<? extends E>... src) {\n for(Collection<? extends E> c : src) {\n dest.addAll(c);\n }\n\n return dest;\n}\n\npublic static void main(String[] args) {\n System.out.println(addAll(new ArrayList<Object>(), Arrays.asList(1,2,3), Arrays.asList(\"a\", \"b\", \"c\")));\n\n // does not compile\n // System.out.println(addAll(new ArrayList<Integer>(), Arrays.asList(1,2,3), Arrays.asList(\"a\", \"b\", \"c\")));\n\n System.out.println(addAll(new ArrayList<Integer>(), Arrays.asList(1,2,3), Arrays.asList(4, 5, 6)));\n}\n"
},
{
"answer_id": 3581132,
"author": "Guillermo",
"author_id": 432521,
"author_profile": "https://Stackoverflow.com/users/432521",
"pm_score": 9,
"selected": false,
"text": "List<String> newList = ListUtils.union(list1, list2);\n"
},
{
"answer_id": 6874135,
"author": "Yuri Geinish",
"author_id": 318558,
"author_profile": "https://Stackoverflow.com/users/318558",
"pm_score": 6,
"selected": false,
"text": "com.google.common.collect.Iterables#concat()\n"
},
{
"answer_id": 7317532,
"author": "nirmal",
"author_id": 930312,
"author_profile": "https://Stackoverflow.com/users/930312",
"pm_score": 0,
"selected": false,
"text": "List<String> newList = new ArrayList<String>(l1);\nnewList.addAll(l2);\n\nfor(String w:newList)\n System.out.printf(\"%s \", w);\n"
},
{
"answer_id": 11666257,
"author": "Olivier Faucheux",
"author_id": 1166992,
"author_profile": "https://Stackoverflow.com/users/1166992",
"pm_score": 3,
"selected": false,
"text": "/**\n * @param smallLists\n * @return one big list containing all elements of the small ones, in the same order.\n */\npublic static <E> List<E> concatenate (final List<E> ... smallLists)\n{\n final ArrayList<E> bigList = new ArrayList<E>();\n for (final List<E> list: smallLists)\n {\n bigList.addAll(list);\n }\n return bigList;\n}\n"
},
{
"answer_id": 13868047,
"author": "Martin",
"author_id": 1358179,
"author_profile": "https://Stackoverflow.com/users/1358179",
"pm_score": 6,
"selected": false,
"text": "List<String> newList = new ArrayList<>(listOne.size() + listTwo.size());\nnewList.addAll(listOne);\nnewList.addAll(listTwo);\n"
},
{
"answer_id": 13868352,
"author": "Kevin K",
"author_id": 292728,
"author_profile": "https://Stackoverflow.com/users/292728",
"pm_score": 7,
"selected": false,
"text": "addAll() public class CompositeUnmodifiableList<E> extends AbstractList<E> {\n\n private final List<? extends E> list1;\n private final List<? extends E> list2;\n\n public CompositeUnmodifiableList(List<? extends E> list1, List<? extends E> list2) {\n this.list1 = list1;\n this.list2 = list2;\n }\n \n @Override\n public E get(int index) {\n if (index < list1.size()) {\n return list1.get(index);\n }\n return list2.get(index-list1.size());\n }\n\n @Override\n public int size() {\n return list1.size() + list2.size();\n }\n}\n List<String> newList = new CompositeUnmodifiableList<String>(listOne,listTwo);\n"
},
{
"answer_id": 13990351,
"author": "Ram Pasupula",
"author_id": 1921533,
"author_profile": "https://Stackoverflow.com/users/1921533",
"pm_score": -1,
"selected": false,
"text": "public class TestApp {\n\n/**\n * @param args\n */\npublic static void main(String[] args) {\n System.out.println(\"Hi\");\n Set<List<String>> bcOwnersList = new HashSet<List<String>>();\n List<String> bclist = new ArrayList<String>();\n List<String> bclist1 = new ArrayList<String>();\n List<String> object = new ArrayList<String>();\n object.add(\"BC11\");\n object.add(\"C2\");\n bclist.add(\"BC1\");\n bclist.add(\"BC2\");\n bclist.add(\"BC3\");\n bclist.add(\"BC4\");\n bclist.add(\"BC5\");\n bcOwnersList.add(bclist);\n bcOwnersList.add(object);\n\n bclist1.add(\"BC11\");\n bclist1.add(\"BC21\");\n bclist1.add(\"BC31\");\n bclist1.add(\"BC4\");\n bclist1.add(\"BC5\");\n\n List<String> listList= new ArrayList<String>();\n for(List<String> ll : bcOwnersList){\n listList = (List<String>) CollectionUtils.union(listList,CollectionUtils.intersection(ll, bclist1));\n }\n /*for(List<String> lists : listList){\n test = (List<String>) CollectionUtils.union(test, listList);\n }*/\n for(Object l : listList){\n System.out.println(l.toString());\n }\n System.out.println(bclist.contains(\"BC\"));\n\n}\n\n}\n"
},
{
"answer_id": 18687790,
"author": "Dale Emery",
"author_id": 780017,
"author_profile": "https://Stackoverflow.com/users/780017",
"pm_score": 10,
"selected": false,
"text": "List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())\n .collect(Collectors.toList());\n List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();\n"
},
{
"answer_id": 18689435,
"author": "ceklock",
"author_id": 1366353,
"author_profile": "https://Stackoverflow.com/users/1366353",
"pm_score": 5,
"selected": false,
"text": "Collections.addAll(listOne, listTwo.toArray());\n"
},
{
"answer_id": 22850433,
"author": "Mark",
"author_id": 3486249,
"author_profile": "https://Stackoverflow.com/users/3486249",
"pm_score": 8,
"selected": false,
"text": "List<String> newList = Stream.of(listOne, listTwo)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n Stream.of() List<String> newList = Stream.of(listOne, listTwo, listThree)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n"
},
{
"answer_id": 24715402,
"author": "martyglaubitz",
"author_id": 657341,
"author_profile": "https://Stackoverflow.com/users/657341",
"pm_score": 2,
"selected": false,
"text": "public static <T> List<T> merge(List<T>... args) {\n final List<T> result = new ArrayList<>();\n\n for (List<T> list : args) {\n result.addAll(list);\n }\n\n return result;\n}\n"
},
{
"answer_id": 34090554,
"author": "SpaceTrucker",
"author_id": 1466267,
"author_profile": "https://Stackoverflow.com/users/1466267",
"pm_score": 6,
"selected": false,
"text": "List<Object> newList = new ArrayList<>();\nStream.of(list1, list2).forEach(newList::addAll);\n newList newList newList"
},
{
"answer_id": 37386846,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 6,
"selected": false,
"text": "Stream.of Stream.concat List<String> result1 = Stream.concat(Stream.concat(list1.stream(),list2.stream()),list3.stream()).collect(Collectors.toList());\nList<String> result2 = Stream.of(list1,list2,list3).flatMap(Collection::stream).collect(Collectors.toList());\n Stream.concat Stream.concat public static <T> List<T> concatenateLists(List<T>... collections) {\n return Arrays.stream(collections).flatMap(Collection::stream).collect(Collectors.toList()); \n}\n List<String> result3 = Utils.concatenateLists(list1,list2,list3);\n"
},
{
"answer_id": 40119122,
"author": "shinzou",
"author_id": 4279201,
"author_profile": "https://Stackoverflow.com/users/4279201",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n List<String> list2 = new ArrayList<>();\n List<Pair<Integer, String>> list1 = new ArrayList<>();\n\n list2.add(\"asd\");\n list2.add(\"asdaf\");\n list1.add(new Pair<>(1, \"werwe\"));\n list1.add(new Pair<>(2, \"tyutyu\"));\n\n Stream stream = Stream.concat(list1.stream(), list2.stream());\n\n List<Pair<Integer, String>> res = (List<Pair<Integer, String>>) stream\n .map(item -> {\n if (item instanceof String) {\n return new Pair<>(0, item);\n }\n else {\n return new Pair<>(((Pair<Integer, String>)item).getKey(), ((Pair<Integer, String>)item).getValue());\n }\n })\n .collect(Collectors.toList());\n}\n"
},
{
"answer_id": 40559634,
"author": "Saravana",
"author_id": 3344829,
"author_profile": "https://Stackoverflow.com/users/3344829",
"pm_score": 3,
"selected": false,
"text": "Java8 flatMap flatMap List<E> li = lol.stream().collect(ArrayList::new, List::addAll, List::addAll);\n List<E> ints = Stream.of(list1, list2).collect(ArrayList::new, List::addAll, List::addAll);\n List<List<Integer>> lol = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));\n List<Integer> li = lol.stream().collect(ArrayList::new, List::addAll, List::addAll);\n System.out.println(lol);\n System.out.println(li);\n [[1, 2, 3], [4, 5, 6]]\n[1, 2, 3, 4, 5, 6]\n"
},
{
"answer_id": 40870053,
"author": "cslysy",
"author_id": 1749126,
"author_profile": "https://Stackoverflow.com/users/1749126",
"pm_score": 3,
"selected": false,
"text": "public List<SomeClass> mergeLists(final List<SomeClass> left, final List<SomeClass> right, String primaryKey) {\n final Map<Object, SomeClass> mergedList = new LinkedHashMap<>();\n\n Stream.concat(left.stream(), right.stream())\n .map(someObject -> new Pair<Object, SomeClass>(someObject.getSomeKey(), someObject))\n .forEach(pair-> mergedList.put(pair.getKey(), pair.getValue()));\n\n return new ArrayList<>(mergedList.values());\n}\n"
},
{
"answer_id": 42990654,
"author": "Nitin Jain",
"author_id": 4139773,
"author_profile": "https://Stackoverflow.com/users/4139773",
"pm_score": 4,
"selected": false,
"text": "List<?> newList = \nStream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());\n"
},
{
"answer_id": 47457484,
"author": "Jan Weitz",
"author_id": 1378313,
"author_profile": "https://Stackoverflow.com/users/1378313",
"pm_score": 0,
"selected": false,
"text": "A, B ALL public static final EnumSet<MyType> CATEGORY_A = EnumSet.of(A_1, A_2);\npublic static final EnumSet<MyType> CATEGORY_B = EnumSet.of(B_1, B_2, B_3);\n\npublic static final List<MyType> ALL = \n Collections.unmodifiableList(\n new ArrayList<MyType>(CATEGORY_A.size() + CATEGORY_B.size())\n {{\n addAll(CATEGORY_A);\n addAll(CATEGORY_B);\n }}\n );\n"
},
{
"answer_id": 48904406,
"author": "Langusten Gustel",
"author_id": 1431044,
"author_profile": "https://Stackoverflow.com/users/1431044",
"pm_score": 2,
"selected": false,
"text": "public static <T> List<T> merge(@Nonnull final List<T>... list) {\n // calculate length first\n int mergedLength = 0;\n for (List<T> ts : list) {\n mergedLength += ts.size();\n }\n\n final List<T> mergedList = new ArrayList<>(mergedLength);\n\n for (List<T> ts : list) {\n mergedList.addAll(ts);\n }\n\n return mergedList;\n }\n"
},
{
"answer_id": 50418885,
"author": "Daniel Hári",
"author_id": 1386911,
"author_profile": "https://Stackoverflow.com/users/1386911",
"pm_score": 4,
"selected": false,
"text": "@SafeVarargs\npublic static <T> List<T> concat(List<T>... lists) {\n return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());\n}\n"
},
{
"answer_id": 55517693,
"author": "benez",
"author_id": 3583589,
"author_profile": "https://Stackoverflow.com/users/3583589",
"pm_score": -1,
"selected": false,
"text": "import java.util.AbstractList;\nimport java.util.List;\n\n\n/**\n * The {@code ConcatList} is a lightweight view of two {@code List}s.\n * <p>\n * This implementation is <em>not</em> thread-safe even though the underlying lists can be.\n * \n * @param <E>\n * the type of elements in this list\n */\npublic class ConcatList<E> extends AbstractList<E> {\n\n /** The first underlying list. */\n private final List<E> list1;\n /** The second underlying list. */\n private final List<E> list2;\n\n /**\n * Constructs a new {@code ConcatList} from the given two lists.\n * \n * @param list1\n * the first list\n * @param list2\n * the second list\n */\n public ConcatList(final List<E> list1, final List<E> list2) {\n this.list1 = list1;\n this.list2 = list2;\n }\n\n @Override\n public E get(final int index) {\n return getList(index).get(getListIndex(index));\n }\n\n @Override\n public E set(final int index, final E element) {\n return getList(index).set(getListIndex(index), element);\n }\n\n @Override\n public void add(final int index, final E element) {\n getList(index).add(getListIndex(index), element);\n }\n\n @Override\n public E remove(final int index) {\n return getList(index).remove(getListIndex(index));\n }\n\n @Override\n public int size() {\n return list1.size() + list2.size();\n }\n\n @Override\n public boolean contains(final Object o) {\n return list1.contains(o) || list2.contains(o);\n }\n\n @Override\n public void clear() {\n list1.clear();\n list2.clear();\n }\n\n /**\n * Returns the index within the corresponding list related to the given index.\n * \n * @param index\n * the index in this list\n * \n * @return the index of the underlying list\n */\n private int getListIndex(final int index) {\n final int size1 = list1.size();\n return index >= size1 ? index - size1 : index;\n }\n\n /**\n * Returns the list that corresponds to the given index.\n * \n * @param index\n * the index in this list\n * \n * @return the underlying list that corresponds to that index\n */\n private List<E> getList(final int index) {\n return index >= list1.size() ? list2 : list1;\n }\n\n}\n"
},
{
"answer_id": 60854305,
"author": "Himank Batra",
"author_id": 12543660,
"author_profile": "https://Stackoverflow.com/users/12543660",
"pm_score": 3,
"selected": false,
"text": " List<String> list1 = Arrays.asList(\"S\", \"T\");\n List<String> list2 = Arrays.asList(\"U\", \"V\");\n List<String> collect2 = Stream.concat(list1.stream(), list2.stream()).collect(toList());\n System.out.println(\"collect2 = \" + collect2); // collect2 = [S, T, U, V]\n List<String> collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());\n System.out.println(\"collect3 = \" + collect3); // collect3 = [S, T, U, V]\n"
},
{
"answer_id": 61083016,
"author": "Raymond Chenon",
"author_id": 311420,
"author_profile": "https://Stackoverflow.com/users/311420",
"pm_score": 3,
"selected": false,
"text": "List<String> newList = new LinkedList<>(listOne);\nnewList.addAll(listTwo);\n"
},
{
"answer_id": 70102879,
"author": "lqbweb",
"author_id": 1043677,
"author_profile": "https://Stackoverflow.com/users/1043677",
"pm_score": 2,
"selected": false,
"text": "List<String> combined = ImmutableList.<String>builder().addAll(list1).addAll(list2).build()\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17294/"
] |
189,562
|
<p>There are many ways of doing debugging, using a debugger is one, but the simple one for the humble, lazy, programmer is to just add a bunch of print statements to your code.</p>
<p>i.e.</p>
<pre><code> def foo(x):
print 'Hey wow, we got to foo!', x
...
print 'foo is returning:', bar
return bar
</code></pre>
<p>Is there a proper name for this style of debugging?</p>
|
[
{
"answer_id": 189570,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 7,
"selected": true,
"text": "printf() PRINT printf() fprintf() stderr"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14648/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.