qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
136,104
<p>Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?</p>
[ { "answer_id": 136109, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 4, "selected": true, "text": " <Target Name=\"AfterBuild\" DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\" Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\" Outputs=\"$(OutputPath)$(_SGenDllName)\"> \n <SGen BuildAssemblyName=\"$(TargetFileName)\" BuildAssemblyPath=\"$(OutputPath)\" References=\"@(ReferencePath)\" ShouldGenerateSerializer=\"true\" UseProxyTypes=\"false\" KeyContainer=\"$(KeyContainerName)\" KeyFile=\"$(KeyOriginatorFile)\" DelaySign=\"$(DelaySign)\" ToolPath=\"$(SGenToolPath)\">\n <Output TaskParameter=\"SerializationAssembly\" ItemName=\"SerializationAssembly\" />\n </SGen>\n </Target>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
136,129
<p>I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors:</p> <ul> <li>If background color is transparent then ForeColor is same as TextBox disabled Color.</li> <li>If background color is set to anything else, ForeColor is a Dark Gray color.</li> </ul> <p>The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes.</p> <p><img src="https://i.stack.imgur.com/60viN.png" alt="alt text"></p> <p>Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent.</p>
[ { "answer_id": 136265, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 2, "selected": true, "text": "ControlPaint.DrawStringDisabled(g, this.Text, this.Font, Color.Transparent,\n new Rectangle(CustomStringWidth, 5, StringSize2.Width, StringSize2.Height), StringFormat.GenericTypographic);\n" }, { "answer_id": 17196593, "author": "MDMoore313", "author_id": 1298503, "author_profile": "https://Stackoverflow.com/users/1298503", "pm_score": 0, "selected": false, "text": "public partial class NewLabel : Label\n{\n public NewLabel()\n {\n InitializeComponent();\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n TextRenderer.DrawText(e.Graphics, this.Text.ToString(), this.Font, ClientRectangle, ForeColor);\n }\n\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19242/" ]
136,132
<p>I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:</p> <pre><code>RichTextBox rtb = new RichTextBox(); Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold); rtb.Text = "sometext"; rtb.SelectAll() rtb.SelectionFont = boldfont; rtb.SelectionIndent = 12; </code></pre> <p>There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?</p> <p>Edit: The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.</p>
[ { "answer_id": 136221, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "public static RichTextBox Set(this RichTextBox rtb, Font font, string text)\n{ \n rtb.Text = text;\n rtb.SelectAll();\n rtb.SelectionFont = font;\n rtb.SelectionIndent = 12;\n return rtb;\n}\n someRtb.Set(yourFont, \"The Text\").AndThenYouCanAddMoreAndCHainThem();\n" }, { "answer_id": 26768915, "author": "ePandit", "author_id": 676779, "author_profile": "https://Stackoverflow.com/users/676779", "pm_score": 1, "selected": false, "text": "RichTextBox rtb = new RichTextBox();\nrtb.SuspendLayout();\n//richtext processing goes here...\nrtb.Dispose();\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13776/" ]
136,146
<p>Examples:</p> <pre><code>"1" yes "-1" yes "- 3" no "1.2" yes "1.2.3" no "7e4" no (though in some cases you may want to allow scientific notation) ".123" yes "123." yes "." no "-.5" yes "007" yes "00" yes </code></pre>
[ { "answer_id": 136157, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 2, "selected": false, "text": "/^\\s*[+-]?(?:\\d+\\.?\\d*|\\d*\\.\\d+)\\s*$/\n" }, { "answer_id": 136321, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 2, "selected": false, "text": "^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$\n ^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)$\n" }, { "answer_id": 160871, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 2, "selected": false, "text": "/^[-+]?(?=\\.?\\d)\\d*(?:\\.\\d*)?$/\n /^[-+]?(?:\\.\\d+|\\d+(?:\\.\\d*)?)$/\n/^[-+]?(\\.\\d+|\\d+(\\.\\d*)?)$/ # if you don't mind capturing parens\n /^[-+]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)$/\n/^[-+]?(\\.\\d+|(0|[1-9]\\d*)(\\.\\d*)?)$/\n \\d [0-9] \\d \\d /^[-+]?(?:\\.[0-9]+|(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?)$/\n/^[-+]?(\\.[0-9]+|(0|[1-9][0-9]*)(\\.[0-9]*)?)$/\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
136,168
<p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.</p> <p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and support an offset. This is hat I came up with:</p> <pre><code>def tail(f, n, offset=0): &quot;&quot;&quot;Reads a n lines from f with an offset of offset lines.&quot;&quot;&quot; avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) &gt;= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 </code></pre> <p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
[ { "answer_id": 136280, "author": "Mark", "author_id": 16363, "author_profile": "https://Stackoverflow.com/users/16363", "pm_score": 7, "selected": false, "text": "import os\ndef tail(f, n, offset=0):\n stdin,stdout = os.popen2(\"tail -n \"+n+offset+\" \"+f)\n stdin.close()\n lines = stdout.readlines(); stdout.close()\n return lines[:,-offset]\n import subprocess\ndef tail(f, n, offset=0):\n proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)\n lines = proc.stdout.readlines()\n return lines[:, -offset]\n" }, { "answer_id": 136354, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 1, "selected": false, "text": "import os, itertools\n\ndef rblocks(f, blocksize=4096):\n \"\"\"Read file as series of blocks from end of file to start.\n\n The data itself is in normal order, only the order of the blocks is reversed.\n ie. \"hello world\" -> [\"ld\",\"wor\", \"lo \", \"hel\"]\n Note that the file must be opened in binary mode.\n \"\"\"\n if 'b' not in f.mode.lower():\n raise Exception(\"File must be opened using binary mode.\")\n size = os.stat(f.name).st_size\n fullblocks, lastblock = divmod(size, blocksize)\n\n # The first(end of file) block will be short, since this leaves \n # the rest aligned on a blocksize boundary. This may be more \n # efficient than having the last (first in file) block be short\n f.seek(-lastblock,2)\n yield f.read(lastblock)\n\n for i in range(fullblocks-1,-1, -1):\n f.seek(i * blocksize)\n yield f.read(blocksize)\n\ndef tail(f, nlines):\n buf = ''\n result = []\n for block in rblocks(f):\n buf = block + buf\n lines = buf.splitlines()\n\n # Return all lines except the first (since may be partial)\n if lines:\n result.extend(lines[1:]) # First line may not be complete\n if(len(result) >= nlines):\n return result[-nlines:]\n\n buf = lines[0]\n\n return ([buf]+result)[-nlines:]\n\n\nf=open('file_to_tail.txt','rb')\nfor line in tail(f, 20):\n print line\n" }, { "answer_id": 136368, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": false, "text": "def tail( f, lines=20 ):\n total_lines_wanted = lines\n\n BLOCK_SIZE = 1024\n f.seek(0, 2)\n block_end_byte = f.tell()\n lines_to_go = total_lines_wanted\n block_number = -1\n blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting\n # from the end of the file\n while lines_to_go > 0 and block_end_byte > 0:\n if (block_end_byte - BLOCK_SIZE > 0):\n # read the last block we haven't yet read\n f.seek(block_number*BLOCK_SIZE, 2)\n blocks.append(f.read(BLOCK_SIZE))\n else:\n # file too small, start from begining\n f.seek(0,0)\n # only read what was not read\n blocks.append(f.read(block_end_byte))\n lines_found = blocks[-1].count('\\n')\n lines_to_go -= lines_found\n block_end_byte -= BLOCK_SIZE\n block_number -= 1\n all_read_text = ''.join(reversed(blocks))\n return '\\n'.join(all_read_text.splitlines()[-total_lines_wanted:])\n f = open('C:/.../../apache_logs.txt', 'rb') def tail(f, lines=20):\n total_lines_wanted = lines\n\n BLOCK_SIZE = 1024\n f.seek(0, 2)\n block_end_byte = f.tell()\n lines_to_go = total_lines_wanted\n block_number = -1\n blocks = []\n while lines_to_go > 0 and block_end_byte > 0:\n if (block_end_byte - BLOCK_SIZE > 0):\n f.seek(block_number*BLOCK_SIZE, 2)\n blocks.append(f.read(BLOCK_SIZE))\n else:\n f.seek(0,0)\n blocks.append(f.read(block_end_byte))\n lines_found = blocks[-1].count(b'\\n')\n lines_to_go -= lines_found\n block_end_byte -= BLOCK_SIZE\n block_number -= 1\n all_read_text = b''.join(reversed(blocks))\n return b'\\n'.join(all_read_text.splitlines()[-total_lines_wanted:])\n" }, { "answer_id": 136475, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": -1, "selected": false, "text": "def tail( f, window=20 ):\n lines= ['']*window\n count= 0\n for l in f:\n lines[count%window]= l\n count += 1\n print lines[count%window:], lines[:count%window]\n" }, { "answer_id": 280083, "author": "A. Coady", "author_id": 36433, "author_profile": "https://Stackoverflow.com/users/36433", "pm_score": 5, "selected": false, "text": "from collections import deque\ndeque(f, maxlen=n)\n import itertools\ndef maxque(items, size):\n items = iter(items)\n q = deque(itertools.islice(items, size))\n for item in items:\n del q[0]\n q.append(item)\n return q\n def tail(f, n):\n assert n >= 0\n pos, lines = n+1, []\n while len(lines) <= n:\n try:\n f.seek(-pos, 2)\n except IOError:\n f.seek(0)\n break\n finally:\n lines = list(f)\n pos *= 2\n return lines[-n:]\n" }, { "answer_id": 692616, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 6, "selected": true, "text": "def tail(f, n, offset=None):\n \"\"\"Reads a n lines from f with an offset of offset lines. The return\n value is a tuple in the form ``(lines, has_more)`` where `has_more` is\n an indicator that is `True` if there are more lines in the file.\n \"\"\"\n avg_line_length = 74\n to_read = n + (offset or 0)\n\n while 1:\n try:\n f.seek(-(avg_line_length * to_read), 2)\n except IOError:\n # woops. apparently file is smaller than what we want\n # to step back, go to the beginning instead\n f.seek(0)\n pos = f.tell()\n lines = f.read().splitlines()\n if len(lines) >= to_read or pos == 0:\n return lines[-to_read:offset and -offset or None], \\\n len(lines) > to_read or pos > 0\n avg_line_length *= 1.3\n" }, { "answer_id": 3018671, "author": "Eyecue", "author_id": 359868, "author_profile": "https://Stackoverflow.com/users/359868", "pm_score": 2, "selected": false, "text": "def tail(the_file, lines_2find=20): \n the_file.seek(0, 2) #go to end of file\n bytes_in_file = the_file.tell() \n lines_found, total_bytes_scanned = 0, 0\n while lines_2find+1 > lines_found and bytes_in_file > total_bytes_scanned: \n byte_block = min(1024, bytes_in_file-total_bytes_scanned)\n the_file.seek(-(byte_block+total_bytes_scanned), 2)\n total_bytes_scanned += byte_block\n lines_found += the_file.read(1024).count('\\n')\n the_file.seek(-total_bytes_scanned, 2)\n line_list = list(the_file.readlines())\n return line_list[-lines_2find:]\n\n #we read at least 21 line breaks from the bottom, block by block for speed\n #21 to ensure we don't get a half line\n" }, { "answer_id": 4131157, "author": "rabbit", "author_id": 501548, "author_profile": "https://Stackoverflow.com/users/501548", "pm_score": 1, "selected": false, "text": "def readline_backwards(self, f):\n backline = ''\n last = ''\n while not last == '\\n':\n backline = last + backline\n if f.tell() <= 0:\n return backline\n f.seek(-1, 1)\n last = f.read(1)\n f.seek(-1, 1)\n backline = last\n last = ''\n while not last == '\\n':\n backline = last + backline\n if f.tell() <= 0:\n return backline\n f.seek(-1, 1)\n last = f.read(1)\n f.seek(-1, 1)\n f.seek(1, 1)\n return backline\n" }, { "answer_id": 4751601, "author": "fdb", "author_id": 260908, "author_profile": "https://Stackoverflow.com/users/260908", "pm_score": 1, "selected": false, "text": "class File(file):\n def head(self, lines_2find=1):\n self.seek(0) #Rewind file\n return [self.next() for x in xrange(lines_2find)]\n\n def tail(self, lines_2find=1): \n self.seek(0, 2) #go to end of file\n bytes_in_file = self.tell() \n lines_found, total_bytes_scanned = 0, 0\n while (lines_2find+1 > lines_found and\n bytes_in_file > total_bytes_scanned): \n byte_block = min(1024, bytes_in_file-total_bytes_scanned)\n self.seek(-(byte_block+total_bytes_scanned), 2)\n total_bytes_scanned += byte_block\n lines_found += self.read(1024).count('\\n')\n self.seek(-total_bytes_scanned, 2)\n line_list = list(self.readlines())\n return line_list[-lines_2find:]\n f = File('path/to/file', 'r')\nf.head(3)\nf.tail(3)\n" }, { "answer_id": 5638389, "author": "David Rogers", "author_id": 704467, "author_profile": "https://Stackoverflow.com/users/704467", "pm_score": 1, "selected": false, "text": "def tail(file, n=1, bs=1024):\n f = open(file)\n f.seek(-1,2)\n l = 1-f.read(1).count('\\n') # If file doesn't end in \\n, count it anyway.\n B = f.tell()\n while n >= l and B > 0:\n block = min(bs, B)\n B -= block\n f.seek(B, 0)\n l += f.read(block).count('\\n')\n f.seek(B, 0)\n l = min(l,n) # discard first (incomplete) line if l > n\n lines = f.readlines()[-l:]\n f.close()\n return lines\n" }, { "answer_id": 6813975, "author": "dimitri", "author_id": 861232, "author_profile": "https://Stackoverflow.com/users/861232", "pm_score": 4, "selected": false, "text": "import mmap\nimport os\n\ndef tail(filename, n):\n \"\"\"Returns last n lines from the filename. No exception handling\"\"\"\n size = os.path.getsize(filename)\n with open(filename, \"rb\") as f:\n # for Windows the mmap parameters are different\n fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)\n try:\n for i in xrange(size - 1, -1, -1):\n if fm[i] == '\\n':\n n -= 1\n if n == -1:\n break\n return fm[i + 1 if i else 0:].splitlines()\n finally:\n fm.close()\n" }, { "answer_id": 7047765, "author": "papercrane", "author_id": 892621, "author_profile": "https://Stackoverflow.com/users/892621", "pm_score": 5, "selected": false, "text": "def tail(f, window=20):\n \"\"\"\n Returns the last `window` lines of file `f` as a list.\n f - a byte file-like object\n \"\"\"\n if window == 0:\n return []\n BUFSIZ = 1024\n f.seek(0, 2)\n bytes = f.tell()\n size = window + 1\n block = -1\n data = []\n while size > 0 and bytes > 0:\n if bytes - BUFSIZ > 0:\n # Seek back one whole BUFSIZ\n f.seek(block * BUFSIZ, 2)\n # read BUFFER\n data.insert(0, f.read(BUFSIZ))\n else:\n # file too small, start from begining\n f.seek(0,0)\n # only read what was not read\n data.insert(0, f.read(bytes))\n linesFound = data[0].count('\\n')\n size -= linesFound\n bytes -= BUFSIZ\n block -= 1\n return ''.join(data).splitlines()[-window:]\n" }, { "answer_id": 10175048, "author": "Marko", "author_id": 1336404, "author_profile": "https://Stackoverflow.com/users/1336404", "pm_score": 2, "selected": false, "text": "def GetLastNLines(self, n, fileName):\n \"\"\"\n Name: Get LastNLines\n Description: Gets last n lines using Unix tail\n Output: returns last n lines of a file\n Keyword argument:\n n -- number of last lines to return\n filename -- Name of the file you need to tail into\n \"\"\"\n p = subprocess.Popen(['tail','-n',str(n),self.__fileName], stdout=subprocess.PIPE)\n soutput, sinput = p.communicate()\n return soutput\n for line in GetLastNLines(50,'myfile.log').split('\\n'):\n print line\n" }, { "answer_id": 13790289, "author": "glenbot", "author_id": 1889809, "author_profile": "https://Stackoverflow.com/users/1889809", "pm_score": 5, "selected": false, "text": ">>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=10)\n0.0014600753784179688\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=100)\n0.00899195671081543\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=1000)\n0.05842900276184082\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=10000)\n0.5394978523254395\n>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open(\"log.txt\", \"r\");', number=100000)\n5.377126932144165\n import os\n\n\ndef tail(f, lines=1, _buffer=4098):\n \"\"\"Tail a file and get X lines from the end\"\"\"\n # place holder for the lines found\n lines_found = []\n\n # block counter will be multiplied by buffer\n # to get the block size from the end\n block_counter = -1\n\n # loop until we find X lines\n while len(lines_found) < lines:\n try:\n f.seek(block_counter * _buffer, os.SEEK_END)\n except IOError: # either file is too small, or too many lines requested\n f.seek(0)\n lines_found = f.readlines()\n break\n\n lines_found = f.readlines()\n\n # we found enough lines, get out\n # Removed this line because it was redundant the while will catch\n # it, I left it for history\n # if len(lines_found) > lines:\n # break\n\n # decrement the block counter to get the\n # next X bytes\n block_counter -= 1\n\n return lines_found[-lines:]\n" }, { "answer_id": 16507215, "author": "Leifbk", "author_id": 2374816, "author_profile": "https://Stackoverflow.com/users/2374816", "pm_score": 0, "selected": false, "text": "#! /bin/bash\ntail -n1 /home/leif/projects/transfer/export.log | awk {'print $14'}\n from subprocess import check_output\n\nlast_netp = int(check_output(\"/usr/local/bin/get_last_netp\"))\n" }, { "answer_id": 16507435, "author": "Hal Canary", "author_id": 2204941, "author_profile": "https://Stackoverflow.com/users/2204941", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\nimport sys\nimport collections\ndef tail(iterable, N):\n deq = collections.deque()\n for thing in iterable:\n if len(deq) >= N:\n deq.popleft()\n deq.append(thing)\n for thing in deq:\n yield thing\nif __name__ == '__main__':\n for line in tail(sys.stdin,10):\n sys.stdout.write(line)\n" }, { "answer_id": 23290416, "author": "Raj", "author_id": 1283605, "author_profile": "https://Stackoverflow.com/users/1283605", "pm_score": 0, "selected": false, "text": "This is my version of tailf\n\nimport sys, time, os\n\nfilename = 'path to file'\n\ntry:\n with open(filename) as f:\n size = os.path.getsize(filename)\n if size < 1024:\n s = size\n else:\n s = 999\n f.seek(-s, 2)\n l = f.read()\n print l\n while True:\n line = f.readline()\n if not line:\n time.sleep(1)\n continue\n print line\nexcept IOError:\n pass\n" }, { "answer_id": 25450971, "author": "moylop260", "author_id": 3753497, "author_profile": "https://Stackoverflow.com/users/3753497", "pm_score": 0, "selected": false, "text": "import time\n\nattemps = 600\nwait_sec = 5\nfname = \"YOUR_PATH\"\n\nwith open(fname, \"r\") as f:\n where = f.tell()\n for i in range(attemps):\n line = f.readline()\n if not line:\n time.sleep(wait_sec)\n f.seek(where)\n else:\n print line, # already has newline\n" }, { "answer_id": 34029605, "author": "ShadowRanger", "author_id": 364696, "author_profile": "https://Stackoverflow.com/users/364696", "pm_score": 3, "selected": false, "text": "mmap mmap import io # Gets consistent version of open for both Py2.7 and Py3.x\nimport itertools\nimport mmap\n\ndef skip_back_lines(mm, numlines, startidx):\n '''Factored out to simplify handling of n and offset'''\n for _ in itertools.repeat(None, numlines):\n startidx = mm.rfind(b'\\n', 0, startidx)\n if startidx < 0:\n break\n return startidx\n\ndef tail(f, n, offset=0):\n # Reopen file in binary mode\n with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:\n # len(mm) - 1 handles files ending w/newline by getting the prior line\n startofline = skip_back_lines(mm, offset, len(mm) - 1)\n if startofline < 0:\n return [] # Offset lines consumed whole file, nothing to return\n # If using a generator function (yield-ing, see below),\n # this should be a plain return, no empty list\n\n endoflines = startofline + 1 # Slice end to omit offset lines\n\n # Find start of lines to capture (add 1 to move from newline to beginning of following line)\n startofline = skip_back_lines(mm, n, startofline) + 1\n\n # Passing True to splitlines makes it return the list of lines without\n # removing the trailing newline (if any), so list mimics f.readlines()\n return mm[startofline:endoflines].splitlines(True)\n # If Windows style \\r\\n newlines need to be normalized to \\n, and input\n # is ASCII compatible, can normalize newlines with:\n # return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\\n').splitlines(True)\n mm.seek(startofline)\n # Call mm.readline n times, or until EOF, whichever comes first\n # Python 3.2 and earlier:\n for line in itertools.islice(iter(mm.readline, b''), n):\n yield line\n\n # 3.3+:\n yield from itertools.islice(iter(mm.readline, b''), n)\n mmap str bytes unicode str lines = itertools.islice(iter(mm.readline, b''), n)\n if f.encoding: # Decode if the passed file was opened with a specific encoding\n lines = (line.decode(f.encoding) for line in lines)\n if 'b' not in f.mode: # Fix line breaks if passed file opened in text mode\n lines = (line.replace(os.linesep, '\\n') for line in lines)\n # Python 3.2 and earlier:\n for line in lines:\n yield line\n # 3.3+:\n yield from lines\n offset" }, { "answer_id": 37176501, "author": "WorkingRobot", "author_id": 5662232, "author_profile": "https://Stackoverflow.com/users/5662232", "pm_score": -1, "selected": false, "text": "f \\n : def tail(f,n):\n return \"\\n\".join(f.read().split(\"\\n\")[-n:])\n" }, { "answer_id": 37903261, "author": "GL2014", "author_id": 2117603, "author_profile": "https://Stackoverflow.com/users/2117603", "pm_score": 1, "selected": false, "text": "with open('/etc/passwd', 'r') as f:\n try:\n f.seek(0,2)\n s = ''\n while s.count('\\n') < 11:\n cur = f.tell()\n f.seek((cur - 10))\n s = f.read(10) + s\n f.seek((cur - 10))\n print s\n except Exception as e:\n f.readlines()\n" }, { "answer_id": 45960693, "author": "Emilio", "author_id": 6183931, "author_profile": "https://Stackoverflow.com/users/6183931", "pm_score": 3, "selected": false, "text": "open(filename, 'rb') def tail(f, window=20):\n \"\"\"Returns the last `window` lines of file `f` as a list.\n \"\"\"\n if window == 0:\n return []\n\n BUFSIZ = 1024\n f.seek(0, 2)\n remaining_bytes = f.tell()\n size = window + 1\n block = -1\n data = []\n\n while size > 0 and remaining_bytes > 0:\n if remaining_bytes - BUFSIZ > 0:\n # Seek back one whole BUFSIZ\n f.seek(block * BUFSIZ, 2)\n # read BUFFER\n bunch = f.read(BUFSIZ)\n else:\n # file too small, start from beginning\n f.seek(0, 0)\n # only read what was not read\n bunch = f.read(remaining_bytes)\n\n bunch = bunch.decode('utf-8')\n data.insert(0, bunch)\n size -= bunch.count('\\n')\n remaining_bytes -= BUFSIZ\n block -= 1\n\n return ''.join(data).splitlines()[-window:]\n" }, { "answer_id": 48087596, "author": "hrehfeld", "author_id": 876786, "author_profile": "https://Stackoverflow.com/users/876786", "pm_score": 2, "selected": false, "text": "def tail(f, window=1):\n \"\"\"\n Returns the last `window` lines of file `f` as a list of bytes.\n \"\"\"\n if window == 0:\n return b''\n BUFSIZE = 1024\n f.seek(0, 2)\n end = f.tell()\n nlines = window + 1\n data = []\n while nlines > 0 and end > 0:\n i = max(0, end - BUFSIZE)\n nread = min(end, BUFSIZE)\n\n f.seek(i)\n chunk = f.read(nread)\n data.append(chunk)\n nlines -= chunk.count(b'\\n')\n end -= nread\n return b'\\n'.join(b''.join(reversed(data)).splitlines()[-window:])\n with open(path, 'rb') as f:\n last_lines = tail(f, 3).decode('utf-8')\n" }, { "answer_id": 49089617, "author": "Yannis", "author_id": 1543017, "author_profile": "https://Stackoverflow.com/users/1543017", "pm_score": 0, "selected": false, "text": "import itertools\nfname = 'log.txt'\noffset = 5\nn = 10\nwith open(fname) as f:\n n_last_lines = list(reversed([x for x in itertools.islice(f, None)][-(offset+1):-(offset+n+1):-1]))\n" }, { "answer_id": 50894317, "author": "Kant Manapure", "author_id": 914457, "author_profile": "https://Stackoverflow.com/users/914457", "pm_score": 0, "selected": false, "text": "abc = \"2018-06-16 04:45:18.68\"\nfilename = \"abc.txt\"\nwith open(filename) as myFile:\n for num, line in enumerate(myFile, 1):\n if abc in line:\n lastline = num\nprint \"last occurance of work at file is in \"+str(lastline) \n" }, { "answer_id": 50909127, "author": "user9956608", "author_id": 9956608, "author_profile": "https://Stackoverflow.com/users/9956608", "pm_score": -1, "selected": false, "text": "file=open(\"xyz.txt\",'r\")\nliner=file.readlines()\nfor ran in range((len(liner)-N),len(liner)):\n print liner[ran]\n file=open(\"xyz.txt\",'r\")\nliner=file.readlines()\nfor ran in range(0,N+1):\n print liner[ran]\n" }, { "answer_id": 50947562, "author": "Med sadek", "author_id": 7450085, "author_profile": "https://Stackoverflow.com/users/7450085", "pm_score": -1, "selected": false, "text": "def tail(fname,nl):\nwith open(fname) as f:\n data=f.readlines() #readlines return a list\n print(''.join(data[-nl:]))\n" }, { "answer_id": 53842743, "author": "Quinten Cabo", "author_id": 6767994, "author_profile": "https://Stackoverflow.com/users/6767994", "pm_score": 1, "selected": false, "text": "from file_read_backwards import FileReadBackwards\n\nwith FileReadBackwards(\"/tmp/file\", encoding=\"utf-8\") as frb:\n\n# getting lines by lines starting from the last line up\nfor l in frb:\n print(l)\n" }, { "answer_id": 56141523, "author": "Samba Siva Reddy", "author_id": 4513845, "author_profile": "https://Stackoverflow.com/users/4513845", "pm_score": 2, "selected": false, "text": "with open(\"test.txt\") as f:\ndata = f.readlines()\ntail = data[-2:]\nprint(''.join(tail)\n" }, { "answer_id": 57277212, "author": "itsjwala", "author_id": 9485283, "author_profile": "https://Stackoverflow.com/users/9485283", "pm_score": 1, "selected": false, "text": "N import time\nimport os\nimport sys\n\ndef tail(f, n):\n assert n >= 0\n pos, lines = n+1, []\n\n # set file pointer to end\n\n f.seek(0, os.SEEK_END)\n\n isFileSmall = False\n\n while len(lines) <= n:\n try:\n f.seek(f.tell() - pos, os.SEEK_SET)\n except ValueError as e:\n # lines greater than file seeking size\n # seek to start\n f.seek(0,os.SEEK_SET)\n isFileSmall = True\n except IOError:\n print(\"Some problem reading/seeking the file\")\n sys.exit(-1)\n finally:\n lines = f.readlines()\n if isFileSmall:\n break\n\n pos *= 2\n\n print(lines)\n\n return lines[-n:]\n\n\n\n\nwith open(\"stream_logs.txt\") as f:\n while(True):\n time.sleep(0.5)\n print(tail(f,2))\n\n" }, { "answer_id": 58206900, "author": "Blaine McMahon", "author_id": 12155298, "author_profile": "https://Stackoverflow.com/users/12155298", "pm_score": 0, "selected": false, "text": "contents=[]\ndef tail(contents,n):\n with open('file.txt') as file:\n for i in file.readlines():\n contents.append(i)\n\n for i in contents[:n:-1]:\n print(i)\n\ntail(contents,-5)\n" }, { "answer_id": 59475149, "author": "Zhen Wang", "author_id": 6792401, "author_profile": "https://Stackoverflow.com/users/6792401", "pm_score": 3, "selected": false, "text": "deque from collections import deque\n\ndef tail(filename, n=10):\n with open(filename) as f:\n return deque(f, n)\n" }, { "answer_id": 67232314, "author": "rish_hyun", "author_id": 11814875, "author_profile": "https://Stackoverflow.com/users/11814875", "pm_score": 0, "selected": false, "text": "def get_last_line(filepath):\n try:\n with open(filepath,'rb') as f:\n f.seek(-1,os.SEEK_END)\n text = [f.read(1)]\n while text[-1] != '\\n'.encode('utf-8') or len(text)==1:\n f.seek(-2, os.SEEK_CUR)\n text.append(f.read(1))\n except Exception as e:\n pass\n return ''.join([t.decode('utf-8') for t in text[::-1]]).strip()\n" }, { "answer_id": 73357932, "author": "Jacek Błocki", "author_id": 8365731, "author_profile": "https://Stackoverflow.com/users/8365731", "pm_score": 0, "selected": false, "text": "import mmap\ndef tail1(fn, n=5, encoding='utf8'):\n with open(fn) as f:\n mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n nn = len(mm)\n for i in range(n+1):\n nn = mm.rfind(b'\\n',0,nn)\n if nn < 0: break\n return mm[nn:].decode(encoding=encoding).strip()\n\n\ndef tail2(fn, n=5, encoding='utf8'):\n with open(fn,'rb') as f:\n for i in range(f.seek(0, 2), 0, -1):\n _ = f.seek(i)\n if f.read(1) == b'\\n': n -= 1\n if n < 0: break\n return f.read().decode(encoding=encoding).strip()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19990/" ]
136,172
<p>I have a single-threaded application that loads several assemblies at runtime using the following:</p> <pre><code>objDLL = Assembly.LoadFrom(strDLLs[i]); </code></pre> <p>I would like the assemblies loaded in this manner to use the same log4net.ILog reference as the rest of the assemblies do. But it appears the runtime loaded assemblies have a different reference altogether and need their own configuration. Does anyone know if a single log4net.ILog can be used across assemblies loaded at runtime using a .NET interface?</p> <p>Here is the log4net.ILog creation and supporting code in the Program class:</p> <pre><code> // Configure log4net using the .config file [assembly: log4net.Config.XmlConfigurator(Watch = true)] public static class Program { private static log4net.ILog m_Log = null; [STAThread] public static void Main(string[] args) { try { m_Log = log4net.LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } } </code></pre>
[ { "answer_id": 185626, "author": "Jérôme Laban", "author_id": 26346, "author_profile": "https://Stackoverflow.com/users/26346", "pm_score": 2, "selected": false, "text": "log4net.LogManager.GetLogger(\"SomeLogger\");\n" }, { "answer_id": 226240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "[assembly: log4net.Config.XmlConfigurator(ConfigFile=\"<configpath>\",Watch = true)]\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
136,175
<p>My app keeps track of the state of about 1000 objects. Those objects are read from and written to a persistent store (serialized) in no particular order. </p> <p>Right now the app uses the registry to store each object's state. This is nice because:</p> <ul> <li><p>It is simple</p></li> <li><p>It is very fast</p></li> <li><p>Individual object's state can be read/written without needing to read some larger entity (like pulling out a snippet from a large XML file)</p></li> <li><p>There is a decent editor (RegEdit) which allow easily manipulating individual items</p></li> </ul> <p>Having said that, I'm wondering if there is a better way. SQLite seems like a possibility, but you don't have the same level of multiple-reader/multiple-writer that you get with the registry, and no simple way to edit existing entries.</p> <p>Any better suggestions? A bunch of flat files?</p>
[ { "answer_id": 136714, "author": "pestophagous", "author_id": 10278, "author_profile": "https://Stackoverflow.com/users/10278", "pm_score": 3, "selected": true, "text": "sqlite3_open" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
136,178
<p>I'm running <a href="http://www.git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> on a file, but the change is at the end of a long line.</p> <p>If I use cursor keys to move right, it loses colour-coding&mdash;and worse the lines don't line up&mdash;making it harder to track the change.</p> <p>Is there a way to prevent that problem or to simply make the lines wrap instead?</p> <p>I'm running Git 1.5.5 via mingw32.</p>
[ { "answer_id": 136396, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 2, "selected": false, "text": "gitk git-gui" }, { "answer_id": 152546, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 8, "selected": true, "text": "git diff less GIT_PAGER GIT_PAGER $ GIT_PAGER='' git diff\n --no-color $ GIT_PAGER='' git diff --no-color\n" }, { "answer_id": 891173, "author": "singingfish", "author_id": 36499, "author_profile": "https://Stackoverflow.com/users/36499", "pm_score": 4, "selected": false, "text": "GIT_PAGER='less -r'" }, { "answer_id": 3107807, "author": "someone45", "author_id": 374967, "author_profile": "https://Stackoverflow.com/users/374967", "pm_score": 8, "selected": false, "text": "-S" }, { "answer_id": 3673836, "author": "Shoan", "author_id": 17404, "author_profile": "https://Stackoverflow.com/users/17404", "pm_score": 7, "selected": false, "text": "git config $ git config core.pager 'less -r' \n $ git config --global core.pager 'less -r' \n" }, { "answer_id": 6103533, "author": "John Lemberger", "author_id": 2882, "author_profile": "https://Stackoverflow.com/users/2882", "pm_score": 4, "selected": false, "text": "git config --global core.pager 'less -+$LESS -FRX'\n" }, { "answer_id": 12499930, "author": "Daniel Montezano", "author_id": 1683826, "author_profile": "https://Stackoverflow.com/users/1683826", "pm_score": 5, "selected": false, "text": "git config --global core.pager 'less -+S'\n" }, { "answer_id": 17597024, "author": "AnonTidbits", "author_id": 2573232, "author_profile": "https://Stackoverflow.com/users/2573232", "pm_score": 2, "selected": false, "text": "git diff | more\n" }, { "answer_id": 19253759, "author": "lindes", "author_id": 313756, "author_profile": "https://Stackoverflow.com/users/313756", "pm_score": 6, "selected": false, "text": "git diff --word-diff\n diff --git a/test-file.txt b/test-file.txt\nindex 19e6adf..eb6bb81 100644\n--- a/test-file.txt\n+++ b/test-file.txt\n@@ -1 +1 @@\n-this is a short line\n+this is a slightly longer line\n diff --git a/test-file.txt b/test-file.txt\nindex 19e6adf..eb6bb81 100644\n--- a/test-file.txt\n+++ b/test-file.txt\n@@ -1 +1 @@\nthis is a [-short-]{+slightly longer+} line\n" }, { "answer_id": 23643093, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 4, "selected": false, "text": "--no-pager git --no-pager diff\n" }, { "answer_id": 35142708, "author": "user5870226", "author_id": 5870226, "author_profile": "https://Stackoverflow.com/users/5870226", "pm_score": 1, "selected": false, "text": " $ git config --global core.pager \n less -FXRS -x2\n $ git config --global core.pager 'less -FXR -x2'\n" }, { "answer_id": 35352049, "author": "Thomson Comer", "author_id": 498629, "author_profile": "https://Stackoverflow.com/users/498629", "pm_score": 3, "selected": false, "text": "git config core.pager `fold -w 80 | less`\n" }, { "answer_id": 38125882, "author": "infoclogged", "author_id": 1534898, "author_profile": "https://Stackoverflow.com/users/1534898", "pm_score": 3, "selected": false, "text": "git diff --color | less -R\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ]
136,191
<p>Let's say I want to write a regular expression to change all <code>&lt;abc&gt;</code>, <code>&lt;def&gt;</code>, and <code>&lt;ghi&gt;</code> tags into <code>&lt;xyz&gt;</code> tags.. and I also want to change their closing tags to <code>&lt;/xyz&gt;</code>. This seems like a reasonable regex (ignore the backticks; StackOverflow has trouble with the less-than signs if I don't include them):</p> <pre><code>`s!&lt;(/)?(abc|def|ghi)&gt;!&lt;${1}xyz&gt;!g;` </code></pre> <p>And it works, too. The only problem is that for opening tags, the optional $1 variable gets assigned undef, and so I get a "Use of uninitialized value..." warning.</p> <p>What's an elegant way to fix this? I'd rather not make this into two separate regexs, one for opening tags and another for closing tags, because then there are two copies of the taglist that need to be maintained, instead of just one.</p> <p><strong>Edit:</strong> I know I could just turn off warnings in this region of the code, but I don't consider that "elegant".</p>
[ { "answer_id": 136267, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 1, "selected": false, "text": "(</?) < < </" }, { "answer_id": 136268, "author": "jmcnamara", "author_id": 10238, "author_profile": "https://Stackoverflow.com/users/10238", "pm_score": 1, "selected": false, "text": " s!<(/?)(abc|def|ghi)>!<$1xyz>!g;\n (?:pattern)" }, { "answer_id": 136274, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": -1, "selected": false, "text": "no warnings 'uninitialized';\n s!<(/)?(abc|def|ghi)>! join '', '<', ${1}||'', 'xyz>' !ge;\n" }, { "answer_id": 136275, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 2, "selected": false, "text": "`s!(</?)(abc|def|ghi)>!${1}xyz>!g;`\n" }, { "answer_id": 136281, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 0, "selected": false, "text": " s!<(/|)?(abc|def|ghi)>!<${1}xyz>!g;\n ^\n note the pipe symbol, meaning '/' or ''\n" }, { "answer_id": 136343, "author": "Robᵩ", "author_id": 8747, "author_profile": "https://Stackoverflow.com/users/8747", "pm_score": 1, "selected": false, "text": "s!<(/?)(abc|def|ghi)>!<${1}xyz>!g;" }, { "answer_id": 143459, "author": "theorbtwo", "author_id": 4839, "author_profile": "https://Stackoverflow.com/users/4839", "pm_score": 0, "selected": false, "text": "use HTML::TreeBuilder;\nmy $tree=HTML::TreeBuilder->new_from_content(\"<abc>asdf</abc>\");\nfor my $tag (qw<abc def ghi>) {\n for my $elem ($tree->look_down(_tag => $tag)) {\n $elem->tag('xyz');\n }\n}\nprint $tree->as_HTML;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
136,195
<p>We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser. </p> <p>We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object. </p> <p>However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Test&lt;/TITLE&gt; &lt;SCRIPT type="text/javascript"&gt; var field = 'hello world'; &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;input type="button" value="See field" onclick="javascript:alert(field);"/&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>We want to access the <em>field</em> variable and assign a value to it. In VB6 the code for this was pretty straightforward:</p> <pre><code>doc.Script.field = 'newValue' </code></pre> <p>However, in C# we've had to resort to other tricks, like this: </p> <pre><code>Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null); </code></pre> <p>The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".</p> <p>That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable <code>field</code>. </p> <p>Has anyone had any experience doing this type of operation before?</p>
[ { "answer_id": 1763769, "author": "EndangeringSpecies", "author_id": 208334, "author_profile": "https://Stackoverflow.com/users/208334", "pm_score": 3, "selected": false, "text": "eval() webBrowser1.Document.InvokeScript(\"eval\", new String[] {\"1 + 2\"});\n \"1 + 2\" \"3\" InvokeScript(\"eval\", new String[] {\"varName = 3\"})\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14177/" ]
136,204
<p>Not really getting the point of the map function. Can anyone explain with examples its use?</p> <p>Are there any performance benefits to using this instead of a loop or is it just sugar?</p>
[ { "answer_id": 136228, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 7, "selected": true, "text": "# Double all elements of a list\nmy @double = map { $_ * 2 } (1,2,3,4,5);\n# @double = (2,4,6,8,10);\n # @user_objects is a list of objects having a unique_id() method\nmy %users = map { $_->unique_id() => $_ } @user_objects;\n# %users = ( $id => $obj, $id => $obj, ...);\n map" }, { "answer_id": 136242, "author": "Craig H", "author_id": 2328, "author_profile": "https://Stackoverflow.com/users/2328", "pm_score": 3, "selected": false, "text": "@names = (\"andrew\", \"bob\", \"carol\" );\n @names = map (ucfirst, @names);\n" }, { "answer_id": 136295, "author": "AndrewJFord", "author_id": 6154, "author_profile": "https://Stackoverflow.com/users/6154", "pm_score": 2, "selected": false, "text": "@numbers = (3,2,1);\n@squares = map { $_ ** 2 } @numbers;\n" }, { "answer_id": 136331, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": false, "text": "my %is_boolean = map { $_ => 1 } qw(true false);\n my %is_boolean = ( true => 1, false => 1 );\n %is_US_state" }, { "answer_id": 136342, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "$ perl -E'say map {chr(32 + 95 * rand)} 1..16'\n# -> j'k=$^o7\\l'yi28G\n" }, { "answer_id": 136363, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 5, "selected": false, "text": "map for[each] my @uppercase = map { uc } @lowercase;\nmy @hex = map { sprintf \"0x%x\", $_ } @decimal;\nmy %hash = map { $_ => 1 } @array;\nsub join_csv { join ',', map {'\"' . $_ . '\"' } @_ }\n" }, { "answer_id": 136383, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 5, "selected": false, "text": "my @raw_values = (...);\nmy @derived_values;\nfor my $value (@raw_values) {\n push (@derived_values, _derived_value($value));\n}\n my @raw_values = (...);\nmy @derived_values = map { _derived_value($_) } @raw_values;\n my $sentence = \"...\";\nmy @stopwords = (...);\nmy @foundstopwords;\nfor my $word (split(/\\s+/, $sentence)) {\n for my $stopword (@stopwords) {\n if ($word eq $stopword) {\n push (@foundstopwords, $word);\n }\n }\n}\n my $sentence = \"...\";\nmy @stopwords = (...);\nmy %is_stopword = map { $_ => 1 } @stopwords;\nmy @foundstopwords = grep { $is_stopword{$_} } split(/\\s+/, $sentence);\n my %params = ( username => '...', password => '...', action => $action );\nmy @parampairs;\nfor my $param (keys %params) {\n push (@parampairs, $param . '=' . CGI::escape($params{$param}));\n}\nmy $url = $ENV{SCRIPT_NAME} . '?' . join('&amp;', @parampairs);\n my %params = ( username => '...', password => '...', action => $action );\nmy $url = $ENV{SCRIPT_NAME} . '?'\n . join('&amp;', map { $_ . '=' . CGI::escape($params{$_}) } keys %params);\n" }, { "answer_id": 136609, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 2, "selected": false, "text": "my @array = ( 1..5 );\n@array = map { $_+5 } @array;\nprint \"@array\\n\";\n@array = grep { $_ < 7 } @array;\nprint \"@array\\n\";\n" }, { "answer_id": 136693, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 2, "selected": false, "text": "{ name => 'John Smith'\n, rank => 'Lieutenant'\n, serial_number => '382-293937-20'\n};\n map { $_->{name} } values %soldiers\n ${[ sort map { $_->{name} } values %soldiers ]}[-1]\n my %soldiers_by_sn = map { $->{serial_number} => $_ } values %soldiers;\n my %soldiers_by_sn \n = map { $->{serial_number}, $_ } \n grep { $_->{name} !~ m/Hatfield$/ } \n values %soldiers\n ;\n" }, { "answer_id": 137617, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 3, "selected": false, "text": "f l f f l f map f map map map" }, { "answer_id": 138362, "author": "kixx", "author_id": 11260, "author_profile": "https://Stackoverflow.com/users/11260", "pm_score": 4, "selected": false, "text": "@file_list = glob('*');\n@file_modify_times = map { [ $_, (stat($_))[8] ] } @file_list;\n@files_sorted_by_mtime = sort { $a->[1] <=> $b->[1] } @file_modify_times;\n@sorted_files = map { $_->[0] } @files_sorted_by_mtime;\n @sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, (stat($_))[8] ] } glob('*');\n @sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } grep { $_->[1] > (time - 24 * 3600 } map { [ $_, (stat($_))[8] ] } glob('*');\n" }, { "answer_id": 140475, "author": "jimtut", "author_id": 13563, "author_profile": "https://Stackoverflow.com/users/13563", "pm_score": 1, "selected": false, "text": "my @patents = ('7,120,721', '6,809,505', '7,194,673');\nprint join(\", \", map { \"<a href=\\\"http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=/netahtml/srchnum.htm&r=0&f=S&l=50&TERM1=$_\\\">$_</a>\" } @patents);\n" }, { "answer_id": 153853, "author": "Kyle", "author_id": 2237619, "author_profile": "https://Stackoverflow.com/users/2237619", "pm_score": 1, "selected": false, "text": "perl -e '@x=(\"x\"); map { push @x, $_ } @x'\nperl -e '@x=(\"x\"); push @x, $_ for @x'\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
136,233
<p>in tcsh I'm trying to redirect STDERR from a command from my .aliases file.</p> <p>I found that I can redirect STDERR from the command line like this. . .</p> <pre><code>$ (xemacs &gt; /dev/tty) &gt;&amp; /dev/null </code></pre> <p>. . . but when I put this in my .aliases file I get an alias loop. . .</p> <pre><code>$ cat .aliases alias xemacs '(xemacs &gt; /dev/tty ) &gt;&amp; /dev/null' $ xemacs &amp; Alias loop. $ </code></pre> <p>. . . so I put a backslash before the command in .aliases, which allows the command to run. . .</p> <pre><code>$ cat .aliases alias xemacs '(\xemacs &gt; /dev/tty ) &gt;&amp; /dev/null' $ xemacs &amp; [1] 17295 $ </code></pre> <p>. . . but now I can't give the command any arguments:</p> <pre><code>$ xemacs foo.txt &amp; Badly placed ()'s. [1] Done ( \xemacs &gt; /dev/tty ) &gt;&amp; /dev/null $ </code></pre> <p>Can anyone offer any solutions? Thank you in advance!</p> <hr> <p>UPDATE: I'm still curious if it's possible to redirect STDERR in tcsh from .aliases, but as has been suggested here, I ended up with a shell script:</p> <pre><code>#!/bin/sh # wrapper script to suppress messages sent to STDERR on launch # from the command line. /usr/bin/xemacs "$@" 2&gt;/dev/null </code></pre>
[ { "answer_id": 136313, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 4, "selected": true, "text": "#!/bin/tcsh\n\n(xemacs $* > /dev/tty ) >& /dev/null\n" }, { "answer_id": 307638, "author": "J. A. Faucett", "author_id": 18503, "author_profile": "https://Stackoverflow.com/users/18503", "pm_score": 2, "selected": false, "text": "alias emacs '(\\emacs \\!* > /dev/tty) >& /dev/null'\n \\!* emacs abc (/usr/bin/emacs > /dev/tty) >& /dev/null abc\n \\!* emacs abc (/usr/bin/emacs abc > /dev/tty) >& /dev/null\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
136,235
<p>The reason I want to do this is to make it easy to parse out instructions that are emailed to a bot, the kind of thing majordomo might do to parse commands like subscribing and unsubscribing. It turns out there are a lot of crazy formats and things to deal with, like quoted text, distinguishing between header and body, etc.</p> <p>A perl module to do this would be ideal but solutions in any language are welcome.</p>
[ { "answer_id": 136324, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": -1, "selected": false, "text": "# Take an email as a big string and turn it into a plain ascii equivalent.\n# TODO: leave any html tags inside of quotes alone.\nsub plainify {\n my($email) = @_;\n\n # translate quoted-printable or whatever this crap is to plain text.\n $email =~ s/\\=0D\\=0A/\\n/gs;\n $email =~ s/\\=0A/\\n/gs;\n $email =~ s/\\=A0/ /gs;\n $email =~ s/\\=2E/\\./gs;\n $email =~ s/\\=20/\\ /gs;\n $email =~ s/\\=([\\n\\r]|\\n\\r|\\r\\n)//gs;\n\n # translate html to plain text (or enough of it to parse commands).\n $email =~ s/\\&nbsp\\;/ /gs;\n $email =~ s/\\<br\\>/\\n/gis;\n $email =~ s/(\\<[^\\>]+\\>)/\\n$1\\n/gs;\n\n return $email\n}\n" }, { "answer_id": 137277, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": ">>> import email\n>>> p = email.Parser.Parser()\n>>> msg = p.parsestr(\"From: me@example.com\\nSubject: Hello\\nDear Sir or Madam...\")\n>>> msg.get(\"Subject\")\nHello\n>>> msg.get_payload()\n'Dear Sir or Madam...'\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
136,238
<p>I have a Windows Form app written in C#. Its job is to send messages to a list of users. While those messages are being sent, I'd like to display status of the operation for each user. What I am doing (for each user) is creating a Label control and adding it to Panel. This works without a problem for a small set of users. When I increase the size to 1000 or more, the Visual Studio Debugger displays the following message:</p> <blockquote> <p><em>A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in System.Windows.Forms.dll A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll</em></p> </blockquote> <p>And then the application hangs. Any thoughts on what I'm doing wrong and how I can fix this?</p>
[ { "answer_id": 136459, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 1, "selected": false, "text": "ListView EnsureVisible()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324/" ]
136,278
<p>For example, I rarely need:</p> <pre><code>using System.Text; </code></pre> <p>but it's always there by default. I assume the application will use more memory if your code contains unnecessary <a href="http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx" rel="noreferrer">using directives</a>. But is there anything else I should be aware of?</p> <p>Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?</p> <hr> <p><em>Edit: Note that this question is not about the unrelated concept called a <a href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx" rel="noreferrer">using statement</a>, designed to help one manage resources by ensuring that when an object goes out of scope, its <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx" rel="noreferrer">IDisposable.Dispose</a> method is called. See <a href="https://stackoverflow.com/questions/75401/uses-of-using-in-c">Uses of "using" in C#</a>.</em></p>
[ { "answer_id": 136320, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 5, "selected": false, "text": "using using Using using using" }, { "answer_id": 136494, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "using using #region #region" }, { "answer_id": 50764491, "author": "Masd", "author_id": 3381362, "author_profile": "https://Stackoverflow.com/users/3381362", "pm_score": 2, "selected": false, "text": "using" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ]
136,288
<p>I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database.</p> <p>Could someone look at my code and see where a problem could occur?</p> <pre><code>&lt;?php $title = "Edit News"; include("../includes/header.php"); include("../includes/database.php"); $done = false; $expected = array('newstitle', 'newscontent', 'id'); if ($_GET &amp;&amp; !$_POST) { if (isset($_GET['id']) &amp;&amp; is_numeric($_GET['id'])) { $id = $_GET['id']; } else { $id = NULL; } if ($id) { $sql = "SELECT * FROM news WHERE id = $id"; $result = mysql_query($sql) or die ("Error connecting to database..."); $row = mysql_fetch_assoc($result); } // if form has been submitted, update record if (array_key_exists('update', $_POST)) { // prepare expected items for insertion into database foreach ($_POST as $key =&gt; $value) { if (in_array($key, $expected)) { ${$key} = mysql_real_escape_string($value); } } // abandon the process if primary key invalid if (!is_numeric($id)) { die('Invalid request'); } // prepare the SQL query $query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id"; // submit the query $done = mysql_query($query) or die("Error connecting to database..."); } } // redirect page if $id is invalid if ($done) { header("Location: $ROOT/admin/listnews.php"); exit; } ?&gt; </code></pre>
[ { "answer_id": 136345, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 3, "selected": false, "text": "if ($_GET && !$_POST) { \n if (array_key_exists('update', $_POST)) { \n" }, { "answer_id": 136348, "author": "stukelly", "author_id": 5891, "author_profile": "https://Stackoverflow.com/users/5891", "pm_score": 0, "selected": false, "text": "// prepare the SQL query \n$query = \"UPDATE news SET title = '$newstitle', content = '$newscontent' WHERE id = $id\";\n" }, { "answer_id": 136359, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "if (array_key_exists('update', $_POST)) if($_GET && !$_POST) $_POST $_GET $query foreach ($_POST as $key => $value) $expected $newstitle, $newscontent, $id $content $title" }, { "answer_id": 136375, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "if (array_key_exists('update', $_POST)) {\n print()" }, { "answer_id": 136379, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "\n if (array_key_exists('update', $_POST)) { \n...\n}\n \n if (count($_POST) && array_key_exists('update', $_POST)) { \n...\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
136,308
<p>We recently started using maven for dependency management. Our team uses eclipse as it's IDE. Is there an easy way to get eclipse to refresh the maven dependencies without running mvn eclipse:eclipse?</p> <p>The dependencies are up to date in the local maven repository, but eclipse doesn't pick up the changes until we use the eclipse:eclipse command. This regenerates a lot of eclipse configuration files.</p>
[ { "answer_id": 136349, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 2, "selected": false, "text": "mvn eclipse:eclipse" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
136,362
<p>Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness.</p> <p>Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try:</p> <pre><code>mvn compile </code></pre> <p>inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path.</p> <p>If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land.</p> <p>I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.</p>
[ { "answer_id": 136395, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 1, "selected": false, "text": "mvn install" }, { "answer_id": 136397, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 5, "selected": true, "text": "mvn install" }, { "answer_id": 136403, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 1, "selected": false, "text": "mvn eclipse:eclipse" }, { "answer_id": 136706, "author": "Micke", "author_id": 19392, "author_profile": "https://Stackoverflow.com/users/19392", "pm_score": 3, "selected": false, "text": "mvn eclipse:eclipse mvn install" }, { "answer_id": 44821136, "author": "Andreas Covidiot", "author_id": 1915920, "author_profile": "https://Stackoverflow.com/users/1915920", "pm_score": 0, "selected": false, "text": "LATEST" }, { "answer_id": 46817944, "author": "Tezra", "author_id": 6893866, "author_profile": "https://Stackoverflow.com/users/6893866", "pm_score": 2, "selected": false, "text": "Dependencies Add... Enter groupId, artifactId or sha1 prefix or pattern (*):" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8178/" ]
136,401
<p>This could be weird, Have you ever come across a blog which you wanted to read in the chronological order? And that blog could be old, with several hundred posts. When i add this feed to my feed reader, say googlereader, the latest feed comes on top and as i scroll down further, the older posts appear. This could be frustrating if you want to read it from the beginning. Is there any reader that does this? Or, i would love to do this as a pet project, (preferably in c#), how exactly should i go about it? Also, are there any .NET libraries which i can use to work on RSS feeds? I have not done any RSS feed programming before.</p> <p><strong>EDIT</strong> I would like to know if there are any technical limitations to this. This was jsut one interesting problem that I encountered that i thought could be tackled programmatically.</p>
[ { "answer_id": 160792, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 3, "selected": true, "text": "List<SyndicationItem> private SyndicationFeed m_feed;\nprivate List<SyndicationItem> m_items;\n\n...snip...\n\nm_items.Reverse();\nm_feed.Items = m_items;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
136,413
<p>I have a Flex application where I'm using a Canvas to contain several other components. On that Canvas there is a Button which is used to invoke a particular flow through the system. Clicking anywhere else on the Canvas should cause cause a details pane to appear showing more information about the record represented by this control.</p> <p>The problem I'm having is that because the button sits inside the Canvas any time the user clicks the Button the click event is fired on both the Button and the Canvas. Is there any way to avoid having the click event fired on the Canvas object if the user clicks on an area covered up by another component?</p> <p>I've created a simple little test application to demonstrate the problem:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:Script&gt; &lt;![CDATA[ private function onCanvasClick(event:Event):void { text.text = text.text + "\n" + "Canvas Clicked"; } private function onButtonClick(event:Event):void { text.text = text.text + "\n" + "Button Clicked"; } ]]&gt; &lt;/mx:Script&gt; &lt;mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)"&gt; &lt;mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/&gt; &lt;/mx:Canvas&gt; &lt;mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/&gt; &lt;/mx:Application&gt; </code></pre> <p>As it stands when you click the button you will see two entries made in the text box, "Button Clicked" followed by "Canvas Clicked" even though the mouse was clicked only once.</p> <p>I'd like to find a way that I could avoid having the second entry made such that when I click the Button only the "Button Clicked" entry is made, but if I were to click anywhere else in the Canvas the "Canvas Clicked" entry would still appear.</p>
[ { "answer_id": 136569, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 4, "selected": true, "text": "event.stopImmediatePropagation()\n" }, { "answer_id": 136571, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "\nbtn.addEventListener(MouseEvent.Click,function(event:MouseEvent):void{\n event.stopImmediatePropagation();\n ...\n});\n \nbtn.addEventListener(MouseEvent.Click,function(event:MouseEvent):void{\n if(event.target == btn){\n ...\n }\n else{\n ...\n }\n});\n" }, { "answer_id": 139444, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 1, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\">\n <mx:Script>\n <![CDATA[\n private function onCanvasClick(event:Event):void {\n text.text = text.text + \"\\n\" + \"Canvas Clicked\";\n }\n\n private function onButtonClick(event:Event):void {\n text.text = text.text + \"\\n\" + \"Button Clicked\";\n event.stopImmediatePropagation();\n }\n ]]>\n </mx:Script>\n\n <mx:Canvas x=\"97\" y=\"91\" width=\"200\" height=\"200\" backgroundColor=\"red\" click=\"onCanvasClick(event)\">\n <mx:Button x=\"67\" y=\"88\" label=\"Button\" click=\"onButtonClick(event)\"/>\n </mx:Canvas>\n <mx:Text id=\"text\" x=\"97\" y=\"330\" text=\"Text\" width=\"200\" height=\"129\"/>\n</mx:Application>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
136,419
<p>I need to determine the current year in Java as an integer. I could just use <code>java.util.Date()</code>, but it is deprecated.</p>
[ { "answer_id": 136434, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 11, "selected": true, "text": "int year = Year.now().getValue();\n int year = Calendar.getInstance().get(Calendar.YEAR);\n" }, { "answer_id": 136445, "author": "conmulligan", "author_id": 1467, "author_profile": "https://Stackoverflow.com/users/1467", "pm_score": 4, "selected": false, "text": "// year is stored as a static member\nint year = Calendar.getInstance().get(Calendar.YEAR);\n" }, { "answer_id": 136455, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 5, "selected": false, "text": " int year = Calendar.getInstance().get(Calendar.YEAR);\n" }, { "answer_id": 136543, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 2, "selected": false, "text": "java.util.Date java.util.Calendar" }, { "answer_id": 137770, "author": "maxp", "author_id": 21152, "author_profile": "https://Stackoverflow.com/users/21152", "pm_score": -1, "selected": false, "text": "int[] int_dmy( long timestamp ) // remember month is [0..11] !!!\n{\n Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );\n return new int[] { \n cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )\n };\n};\n\n\nint[] int_dmy( Date d ) { \n ...\n}\n" }, { "answer_id": 138019, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": -1, "selected": false, "text": "return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);\n" }, { "answer_id": 6761567, "author": "basZero", "author_id": 356815, "author_profile": "https://Stackoverflow.com/users/356815", "pm_score": 3, "selected": false, "text": "public static int getYearFromDate(Date date) {\n int result = -1;\n if (date != null) {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n result = cal.get(Calendar.YEAR);\n }\n return result;\n}\n" }, { "answer_id": 27107237, "author": "maral04", "author_id": 4112413, "author_profile": "https://Stackoverflow.com/users/4112413", "pm_score": 2, "selected": false, "text": "int year;\n\nyear = Calendar.getInstance().get(Calendar.YEAR);\n Calendar.getInstance().get(Calendar.YEAR)\n import java.util.Calendar;\nimport java.util.Scanner;\n\npublic static void main (String[] args){\n\n Scanner scannernumber = new Scanner(System.in);\n int year;\n\n /*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/\n\n do{\n System.out.print(\"Year (Between \"+((Calendar.getInstance().get(Calendar.YEAR))-200)+\" and \"+Calendar.getInstance().get(Calendar.YEAR)+\") : \");\n year = scannernumber.nextInt();\n }while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));\n}\n" }, { "answer_id": 28891864, "author": "Raffi Khatchadourian", "author_id": 405326, "author_profile": "https://Stackoverflow.com/users/405326", "pm_score": 3, "selected": false, "text": "LocalDate import java.time.LocalDate;\n//...\nint year = LocalDate.now().getYear();\n" }, { "answer_id": 30019752, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 4, "selected": false, "text": "ZonedDateTime.now( ZoneId.of( \"Africa/Casablanca\" ) )\n .getYear()\n int year = ZonedDateTime.now( ZoneId.of( \"Africa/Casablanca\" ) ).getYear() ;\n int year = DateTime.now( DateTimeZone.forID( \"Africa/Casablanca\" ) ).getYear() ;\n ZonedDateTime zdt = \n ZonedDateTime\n .now( ZoneId.of( \"Africa/Casablanca\" ) )\n .minusYears( 1 ) \n;\n DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( \"Africa/Casablanca\" ) ).minusYears( 1 ) ;\n" }, { "answer_id": 33700141, "author": "assylias", "author_id": 829571, "author_profile": "https://Stackoverflow.com/users/829571", "pm_score": 8, "selected": false, "text": "Year::now int year = Year.now().getValue();\n" }, { "answer_id": 44138205, "author": "Zhurov Konstantin", "author_id": 6643968, "author_profile": "https://Stackoverflow.com/users/6643968", "pm_score": 4, "selected": false, "text": "java.time.YearMonth import java.time.YearMonth;\n...\nint year = YearMonth.now().getYear();\nint month = YearMonth.now().getMonthValue();\n" }, { "answer_id": 57391538, "author": "KayV", "author_id": 3956731, "author_profile": "https://Stackoverflow.com/users/3956731", "pm_score": 3, "selected": false, "text": "LocalDate localDate = LocalDate.now();\nint year = localDate.getYear();\nint month = localDate.getMonthValue();\nint date = localDate.getDayOfMonth();\n" }, { "answer_id": 58837485, "author": "Alex Martian", "author_id": 5499118, "author_profile": "https://Stackoverflow.com/users/5499118", "pm_score": -1, "selected": false, "text": "YYYY-MM-DD java.time.Instant UTC import java.time.Instant;\nint myYear = Integer.parseInt(Instant.now().toString().substring(0,4));\n String int Calendar" }, { "answer_id": 62329383, "author": "Mayur Satav", "author_id": 8379852, "author_profile": "https://Stackoverflow.com/users/8379852", "pm_score": 0, "selected": false, "text": "import java.util.Scanner;\nimport java.util.Date;\n\npublic class Practice\n{ \n public static void main(String[] args)\n {\n Date d=new Date(); \n int year=d.getYear();\n int currentYear=year+1900; \n\n System.out.println(currentYear);\n\n }\n\n}\n" }, { "answer_id": 73637810, "author": "Maximiliano Salibe", "author_id": 14881639, "author_profile": "https://Stackoverflow.com/users/14881639", "pm_score": 0, "selected": false, "text": "import java.time.LocalDate;\nint yourVariable = LocalDate.now().getYear()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ]
136,429
<p>I have a PHP script that is called from a cron job every minute. This script takes some info from the database and then calls another PHP script using the System function (passing it some parameters).</p> <p>That means that I can start up to 10 scripts from this "main" one. And what I would like to do is that I would call the script and continue the execution of the main script, that is, not wait for the System call to complete and then call the next one. </p> <p>How can this be done?</p>
[ { "answer_id": 136487, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": -1, "selected": false, "text": "system('php yourscript.php &');\n <?php\nwhile(true) {\n // do whatever needs to be done.\n}\n?>\n" }, { "answer_id": 139397, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 3, "selected": true, "text": "proc_open() stream_select() stream_set_blocking() pcntl_fork()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185527/" ]
136,432
<p>I have a client/server system that performs communication using XML transferred using HTTP requests and responses with the client using Perl's LWP and the server running Perl's CGI.pm through Apache. In addition the stream is encrypted using SSL with certificates for both the server and all clients.</p> <p>This system works well, except that periodically the client needs to send really large amounts of data. An obvious solution would be to compress the data on the client side, send it over, and decompress it on the server. Rather than implement this myself, I was hoping to use Apache's mod_deflate's "Input Decompression" as described <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html" rel="nofollow noreferrer">here</a>.</p> <p>The description warns:</p> <blockquote> <p>If you evaluate the request body yourself, don't trust the Content-Length header! The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream.</p> </blockquote> <p>So if I provide a Content-Length value which matches the compressed data size, the data is truncated. This is because mod_deflate decompresses the stream, but CGI.pm only reads to the Content-Length limit.</p> <p>Alternatively, if I try to outsmart it and override the Content-Length header with the decompressed data size, LWP complains and resets the value to the compressed length, leaving me with the same problem.</p> <p>Finally, I attempted to hack the part of LWP which does the correction. The original code is:</p> <pre><code> # Set (or override) Content-Length header my $clen = $request_headers-&gt;header('Content-Length'); if (defined($$content_ref) &amp;&amp; length($$content_ref)) { $has_content = length($$content_ref); if (!defined($clen) || $clen ne $has_content) { if (defined $clen) { warn "Content-Length header value was wrong, fixed"; hlist_remove(\@h, 'Content-Length'); } push(@h, 'Content-Length' =&gt; $has_content); } } elsif ($clen) { warn "Content-Length set when there is no content, fixed"; hlist_remove(\@h, 'Content-Length'); } </code></pre> <p>And I changed the push line to:</p> <pre><code> push(@h, 'Content-Length' =&gt; $clen); </code></pre> <p>Unfortunately this causes some problem where content (truncated or not) doesn't even get to my CGI script.</p> <p>Has anyone made this work? I found <a href="http://hype-free.blogspot.com/2007/07/compressed-http.html" rel="nofollow noreferrer">this</a> which does compression on a file before uploading, but not compressing a generic request.</p>
[ { "answer_id": 137279, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": "read(STDIN, $query_string, $ENV{'CONTENT_LENGTH'});\n" }, { "answer_id": 138095, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 1, "selected": false, "text": "$ENV{'CONTENT_LENGTH'}" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22410/" ]
136,435
<p>How to allow <code>TextBlock</code>'s text to be selectable?</p> <p>I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?</p>
[ { "answer_id": 2506504, "author": "MSB", "author_id": 300663, "author_profile": "https://Stackoverflow.com/users/300663", "pm_score": 9, "selected": true, "text": "TextBox TextBlock <TextBox Background=\"Transparent\"\n BorderThickness=\"0\"\n Text=\"{Binding Text, Mode=OneWay}\"\n IsReadOnly=\"True\"\n TextWrapping=\"Wrap\" />\n" }, { "answer_id": 4145443, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 1, "selected": false, "text": "\nnew TextBox\n{\n Text = text,\n TextAlignment = TextAlignment.Center,\n TextWrapping = TextWrapping.Wrap,\n IsReadOnly = true,\n Background = Brushes.Transparent,\n BorderThickness = new Thickness()\n {\n Top = 0,\n Bottom = 0,\n Left = 0,\n Right = 0\n }\n};\n" }, { "answer_id": 7399948, "author": "Saraf Talukder", "author_id": 690310, "author_profile": "https://Stackoverflow.com/users/690310", "pm_score": 2, "selected": false, "text": "<Style x:Key=\"TextBlockUsingTextBoxStyle\" BasedOn=\"{x:Null}\" TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"BorderBrush\" Value=\"{StaticResource TextBoxBorder}\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Padding\" Value=\"1\"/>\n <Setter Property=\"AllowDrop\" Value=\"true\"/>\n <Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\"/>\n <Setter Property=\"ScrollViewer.PanningMode\" Value=\"VerticalFirst\"/>\n <Setter Property=\"Stylus.IsFlicksEnabled\" Value=\"False\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBox BorderThickness=\"{TemplateBinding BorderThickness}\" IsReadOnly=\"True\" Text=\"{TemplateBinding Text}\" Background=\"{x:Null}\" BorderBrush=\"{x:Null}\" />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n" }, { "answer_id": 9231349, "author": "jdearana", "author_id": 207949, "author_profile": "https://Stackoverflow.com/users/207949", "pm_score": 4, "selected": false, "text": "<Style x:Key=\"SelectableTextBlockLikeStyle\" TargetType=\"TextBox\" BasedOn=\"{StaticResource {x:Type TextBox}}\">\n <Setter Property=\"IsReadOnly\" Value=\"True\"/>\n <Setter Property=\"IsTabStop\" Value=\"False\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"Padding\" Value=\"-2,0,0,0\"/>\n <!-- The Padding -2,0,0,0 is required because the TextBox\n seems to have an inherent \"Padding\" of about 2 pixels.\n Without the Padding property,\n the text seems to be 2 pixels to the left\n compared to a TextBlock\n -->\n <Style.Triggers>\n <MultiTrigger>\n <MultiTrigger.Conditions>\n <Condition Property=\"IsMouseOver\" Value=\"False\" />\n <Condition Property=\"IsFocused\" Value=\"False\" />\n </MultiTrigger.Conditions>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBlock Text=\"{TemplateBinding Text}\" \n FontSize=\"{TemplateBinding FontSize}\"\n FontStyle=\"{TemplateBinding FontStyle}\"\n FontFamily=\"{TemplateBinding FontFamily}\"\n FontWeight=\"{TemplateBinding FontWeight}\"\n TextWrapping=\"{TemplateBinding TextWrapping}\"\n Foreground=\"{DynamicResource NormalText}\"\n Padding=\"0,0,0,0\"\n />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </MultiTrigger>\n </Style.Triggers>\n</Style>\n" }, { "answer_id": 24609144, "author": "Robert Važan", "author_id": 1981276, "author_profile": "https://Stackoverflow.com/users/1981276", "pm_score": -1, "selected": false, "text": "<jc:SelectableTextBlock Text=\"Some text\" />\n" }, { "answer_id": 32870521, "author": "Billy Willoughby", "author_id": 4810862, "author_profile": "https://Stackoverflow.com/users/4810862", "pm_score": 5, "selected": false, "text": "xmlns:sdo=\"clr-namespace:iFaceCaseMain\"\n\n<sdo:TextBlockMoo x:Name=\"txtResults\" Background=\"Black\" Margin=\"5,5,5,5\" \n Foreground=\"GreenYellow\" FontSize=\"14\" FontFamily=\"Courier New\"></TextBlockMoo>\n public partial class TextBlockMoo : TextBlock \n{\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler TextSelected;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n TextRange otr = new TextRange(this.ContentStart, this.ContentEnd);\n otr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));\n\n TextRange ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.White));\n\n SelectedText = ntr.Text;\n if (!(TextSelected == null))\n {\n TextSelected(SelectedText);\n }\n }\n}\n public ucExample(IInstanceHost host, ref String WindowTitle, String ApplicationID, String Parameters)\n {\n InitializeComponent();\n /*Used to add selected text to clipboard*/\n this.txtResults.TextSelected += txtResults_TextSelected;\n }\n\n void txtResults_TextSelected(string SelectedText)\n {\n Clipboard.SetText(SelectedText);\n }\n" }, { "answer_id": 36224662, "author": "Titwan", "author_id": 509932, "author_profile": "https://Stackoverflow.com/users/509932", "pm_score": 0, "selected": false, "text": "Really nice and easy solution, exactly what I wanted !\n public class TextBlockMoo : TextBlock \n{\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler OnTextSelected;\n protected void RaiseEvent()\n {\n if (OnTextSelected != null){OnTextSelected(SelectedText);}\n }\n\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n Brush _saveForeGroundBrush;\n Brush _saveBackGroundBrush;\n\n TextRange _ntr = null;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n\n if (_ntr!=null) {\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);\n }\n\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n _ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n\n // keep saved\n _saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);\n _saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);\n // change style\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));\n\n SelectedText = _ntr.Text;\n }\n}\n" }, { "answer_id": 45627524, "author": "torvin", "author_id": 332528, "author_profile": "https://Stackoverflow.com/users/332528", "pm_score": 7, "selected": false, "text": "TextBox TextBox TextBlock System.Windows.Documents.TextEditor TextEditor.RegisterCommandHandlers() TextEditor System.Windows.Documents.ITextContainer Focusable True TextEditor class TextEditorWrapper\n{\n private static readonly Type TextEditorType = Type.GetType(\"System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty(\"IsReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty(\"TextView\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod(\"RegisterCommandHandlers\", \n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n private static readonly Type TextContainerType = Type.GetType(\"System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty(\"TextView\");\n\n private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty(\"TextContainer\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n public static TextEditorWrapper CreateFor(TextBlock tb)\n {\n var textContainer = TextContainerProp.GetValue(tb);\n\n var editor = new TextEditorWrapper(textContainer, tb, false);\n IsReadOnlyProp.SetValue(editor._editor, true);\n TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));\n\n return editor;\n }\n\n private readonly object _editor;\n\n public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)\n {\n _editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, \n null, new[] { textContainer, uiScope, isUndoEnabled }, null);\n }\n}\n SelectableTextBlock TextBlock public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n }\n}\n TextBlock TextEditor _editor.TextContainer.TextView = null;\n_editor.OnDetach();\n_editor = null;\n" }, { "answer_id": 53296378, "author": "Angel T", "author_id": 2814337, "author_profile": "https://Stackoverflow.com/users/2814337", "pm_score": 0, "selected": false, "text": "public MainPage()\n{\n this.InitializeComponent();\n ...\n ...\n ...\n //Make Start result text copiable\n TextBlockStatusStart.IsTextSelectionEnabled = true;\n}\n" }, { "answer_id": 55397367, "author": "Rauland", "author_id": 602152, "author_profile": "https://Stackoverflow.com/users/602152", "pm_score": 0, "selected": false, "text": "TextTrimming=\"CharacterEllipsis\" public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n\n this.Loaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;\n };\n this.Unloaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n };\n }\n\n private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n if (!string.IsNullOrEmpty(e?.Exception?.StackTrace))\n {\n if (e.Exception.StackTrace.Contains(\"System.Windows.Controls.TextBlock.GetTextPositionFromDistance\"))\n {\n e.Handled = true;\n }\n }\n }\n}\n" }, { "answer_id": 67036133, "author": "Nicke Manarin", "author_id": 1735672, "author_profile": "https://Stackoverflow.com/users/1735672", "pm_score": 0, "selected": false, "text": "FlowDocument FlowDocumentScrollViewer <FlowDocumentScrollViewer Grid.Row=\"2\" Margin=\"5,3\" BorderThickness=\"1\" \n BorderBrush=\"{DynamicResource Element.Border}\" \n VerticalScrollBarVisibility=\"Auto\">\n <FlowDocument>\n <Paragraph>\n <Bold>Some bold text in the paragraph.</Bold>\n Some text that is not bold.\n </Paragraph>\n\n <List>\n <ListItem>\n <Paragraph>ListItem 1</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 2</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 3</Paragraph>\n </ListItem>\n </List>\n </FlowDocument>\n</FlowDocumentScrollViewer>\n" }, { "answer_id": 68139947, "author": "Shakti", "author_id": 741147, "author_profile": "https://Stackoverflow.com/users/741147", "pm_score": 1, "selected": false, "text": "public class TextBlockEx : TextBox\n{\n public TextBlockEx()\n {\n base.BorderThickness = new Thickness(0);\n IsReadOnly = true;\n TextWrapping = TextWrapping.Wrap;\n //Background = Brushes.Transparent; // Uncomment to get parent's background color\n }\n}\n" }, { "answer_id": 69110678, "author": "Michael Wagner", "author_id": 12470516, "author_profile": "https://Stackoverflow.com/users/12470516", "pm_score": 0, "selected": false, "text": "Background Run.Background" }, { "answer_id": 74535160, "author": "altair", "author_id": 1516045, "author_profile": "https://Stackoverflow.com/users/1516045", "pm_score": 0, "selected": false, "text": "public class SelectableTextBlock : TextBlock\n{\n\n static readonly Type TextEditorType\n = Type.GetType(\"System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n static readonly PropertyInfo IsReadOnlyProp\n = TextEditorType.GetProperty(\"IsReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly PropertyInfo TextViewProp\n = TextEditorType.GetProperty(\"TextView\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly MethodInfo RegisterMethod\n = TextEditorType.GetMethod(\"RegisterCommandHandlers\",\n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n static readonly Type TextContainerType\n = Type.GetType(\"System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n static readonly PropertyInfo TextContainerTextViewProp\n = TextContainerType.GetProperty(\"TextView\");\n\n static readonly PropertyInfo TextContainerTextSelectionProp\n = TextContainerType.GetProperty(\"TextSelection\");\n\n static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty(\"TextContainer\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n //private readonly TextEditorWrapper _editor;\n object? textContainer;\n object? editor;\n public TextSelection TextSelection { get; private set; }\n\n public SelectableTextBlock()\n {\n textContainer = TextContainerProp.GetValue(this);\n\n editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,\n null, new[] { textContainer, this, false }, null);\n\n\n IsReadOnlyProp.SetValue(editor, true);\n TextViewProp.SetValue(editor, TextContainerTextViewProp.GetValue(textContainer));\n\n TextSelection = (TextSelection)TextContainerTextSelectionProp.GetValue(textContainer);\n TextSelection.Changed += (s, e) => OnSelectionChanged?.Invoke(this, e);\n }\n\n public event EventHandler OnSelectionChanged;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1133/" ]
136,436
<p>I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'. </p> <p>I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up?</p> <p>Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for. </p> <p>Thanks.</p>
[ { "answer_id": 2506504, "author": "MSB", "author_id": 300663, "author_profile": "https://Stackoverflow.com/users/300663", "pm_score": 9, "selected": true, "text": "TextBox TextBlock <TextBox Background=\"Transparent\"\n BorderThickness=\"0\"\n Text=\"{Binding Text, Mode=OneWay}\"\n IsReadOnly=\"True\"\n TextWrapping=\"Wrap\" />\n" }, { "answer_id": 4145443, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 1, "selected": false, "text": "\nnew TextBox\n{\n Text = text,\n TextAlignment = TextAlignment.Center,\n TextWrapping = TextWrapping.Wrap,\n IsReadOnly = true,\n Background = Brushes.Transparent,\n BorderThickness = new Thickness()\n {\n Top = 0,\n Bottom = 0,\n Left = 0,\n Right = 0\n }\n};\n" }, { "answer_id": 7399948, "author": "Saraf Talukder", "author_id": 690310, "author_profile": "https://Stackoverflow.com/users/690310", "pm_score": 2, "selected": false, "text": "<Style x:Key=\"TextBlockUsingTextBoxStyle\" BasedOn=\"{x:Null}\" TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"BorderBrush\" Value=\"{StaticResource TextBoxBorder}\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Padding\" Value=\"1\"/>\n <Setter Property=\"AllowDrop\" Value=\"true\"/>\n <Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\"/>\n <Setter Property=\"ScrollViewer.PanningMode\" Value=\"VerticalFirst\"/>\n <Setter Property=\"Stylus.IsFlicksEnabled\" Value=\"False\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBox BorderThickness=\"{TemplateBinding BorderThickness}\" IsReadOnly=\"True\" Text=\"{TemplateBinding Text}\" Background=\"{x:Null}\" BorderBrush=\"{x:Null}\" />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n" }, { "answer_id": 9231349, "author": "jdearana", "author_id": 207949, "author_profile": "https://Stackoverflow.com/users/207949", "pm_score": 4, "selected": false, "text": "<Style x:Key=\"SelectableTextBlockLikeStyle\" TargetType=\"TextBox\" BasedOn=\"{StaticResource {x:Type TextBox}}\">\n <Setter Property=\"IsReadOnly\" Value=\"True\"/>\n <Setter Property=\"IsTabStop\" Value=\"False\"/>\n <Setter Property=\"BorderThickness\" Value=\"0\"/>\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n <Setter Property=\"Padding\" Value=\"-2,0,0,0\"/>\n <!-- The Padding -2,0,0,0 is required because the TextBox\n seems to have an inherent \"Padding\" of about 2 pixels.\n Without the Padding property,\n the text seems to be 2 pixels to the left\n compared to a TextBlock\n -->\n <Style.Triggers>\n <MultiTrigger>\n <MultiTrigger.Conditions>\n <Condition Property=\"IsMouseOver\" Value=\"False\" />\n <Condition Property=\"IsFocused\" Value=\"False\" />\n </MultiTrigger.Conditions>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TextBox}\">\n <TextBlock Text=\"{TemplateBinding Text}\" \n FontSize=\"{TemplateBinding FontSize}\"\n FontStyle=\"{TemplateBinding FontStyle}\"\n FontFamily=\"{TemplateBinding FontFamily}\"\n FontWeight=\"{TemplateBinding FontWeight}\"\n TextWrapping=\"{TemplateBinding TextWrapping}\"\n Foreground=\"{DynamicResource NormalText}\"\n Padding=\"0,0,0,0\"\n />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </MultiTrigger>\n </Style.Triggers>\n</Style>\n" }, { "answer_id": 24609144, "author": "Robert Važan", "author_id": 1981276, "author_profile": "https://Stackoverflow.com/users/1981276", "pm_score": -1, "selected": false, "text": "<jc:SelectableTextBlock Text=\"Some text\" />\n" }, { "answer_id": 32870521, "author": "Billy Willoughby", "author_id": 4810862, "author_profile": "https://Stackoverflow.com/users/4810862", "pm_score": 5, "selected": false, "text": "xmlns:sdo=\"clr-namespace:iFaceCaseMain\"\n\n<sdo:TextBlockMoo x:Name=\"txtResults\" Background=\"Black\" Margin=\"5,5,5,5\" \n Foreground=\"GreenYellow\" FontSize=\"14\" FontFamily=\"Courier New\"></TextBlockMoo>\n public partial class TextBlockMoo : TextBlock \n{\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler TextSelected;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n TextRange otr = new TextRange(this.ContentStart, this.ContentEnd);\n otr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));\n\n TextRange ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.White));\n\n SelectedText = ntr.Text;\n if (!(TextSelected == null))\n {\n TextSelected(SelectedText);\n }\n }\n}\n public ucExample(IInstanceHost host, ref String WindowTitle, String ApplicationID, String Parameters)\n {\n InitializeComponent();\n /*Used to add selected text to clipboard*/\n this.txtResults.TextSelected += txtResults_TextSelected;\n }\n\n void txtResults_TextSelected(string SelectedText)\n {\n Clipboard.SetText(SelectedText);\n }\n" }, { "answer_id": 36224662, "author": "Titwan", "author_id": 509932, "author_profile": "https://Stackoverflow.com/users/509932", "pm_score": 0, "selected": false, "text": "Really nice and easy solution, exactly what I wanted !\n public class TextBlockMoo : TextBlock \n{\n public String SelectedText = \"\";\n\n public delegate void TextSelectedHandler(string SelectedText);\n public event TextSelectedHandler OnTextSelected;\n protected void RaiseEvent()\n {\n if (OnTextSelected != null){OnTextSelected(SelectedText);}\n }\n\n TextPointer StartSelectPosition;\n TextPointer EndSelectPosition;\n Brush _saveForeGroundBrush;\n Brush _saveBackGroundBrush;\n\n TextRange _ntr = null;\n\n protected override void OnMouseDown(MouseButtonEventArgs e)\n {\n base.OnMouseDown(e);\n\n if (_ntr!=null) {\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);\n }\n\n Point mouseDownPoint = e.GetPosition(this);\n StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true); \n }\n\n protected override void OnMouseUp(MouseButtonEventArgs e)\n {\n base.OnMouseUp(e);\n Point mouseUpPoint = e.GetPosition(this);\n EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);\n\n _ntr = new TextRange(StartSelectPosition, EndSelectPosition);\n\n // keep saved\n _saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);\n _saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);\n // change style\n _ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));\n _ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));\n\n SelectedText = _ntr.Text;\n }\n}\n" }, { "answer_id": 45627524, "author": "torvin", "author_id": 332528, "author_profile": "https://Stackoverflow.com/users/332528", "pm_score": 7, "selected": false, "text": "TextBox TextBox TextBlock System.Windows.Documents.TextEditor TextEditor.RegisterCommandHandlers() TextEditor System.Windows.Documents.ITextContainer Focusable True TextEditor class TextEditorWrapper\n{\n private static readonly Type TextEditorType = Type.GetType(\"System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty(\"IsReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty(\"TextView\", BindingFlags.Instance | BindingFlags.NonPublic);\n private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod(\"RegisterCommandHandlers\", \n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n private static readonly Type TextContainerType = Type.GetType(\"System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty(\"TextView\");\n\n private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty(\"TextContainer\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n public static TextEditorWrapper CreateFor(TextBlock tb)\n {\n var textContainer = TextContainerProp.GetValue(tb);\n\n var editor = new TextEditorWrapper(textContainer, tb, false);\n IsReadOnlyProp.SetValue(editor._editor, true);\n TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));\n\n return editor;\n }\n\n private readonly object _editor;\n\n public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)\n {\n _editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, \n null, new[] { textContainer, uiScope, isUndoEnabled }, null);\n }\n}\n SelectableTextBlock TextBlock public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n }\n}\n TextBlock TextEditor _editor.TextContainer.TextView = null;\n_editor.OnDetach();\n_editor = null;\n" }, { "answer_id": 53296378, "author": "Angel T", "author_id": 2814337, "author_profile": "https://Stackoverflow.com/users/2814337", "pm_score": 0, "selected": false, "text": "public MainPage()\n{\n this.InitializeComponent();\n ...\n ...\n ...\n //Make Start result text copiable\n TextBlockStatusStart.IsTextSelectionEnabled = true;\n}\n" }, { "answer_id": 55397367, "author": "Rauland", "author_id": 602152, "author_profile": "https://Stackoverflow.com/users/602152", "pm_score": 0, "selected": false, "text": "TextTrimming=\"CharacterEllipsis\" public class SelectableTextBlock : TextBlock\n{\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n private readonly TextEditorWrapper _editor;\n\n public SelectableTextBlock()\n {\n _editor = TextEditorWrapper.CreateFor(this);\n\n this.Loaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;\n };\n this.Unloaded += (sender, args) => {\n this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;\n };\n }\n\n private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n {\n if (!string.IsNullOrEmpty(e?.Exception?.StackTrace))\n {\n if (e.Exception.StackTrace.Contains(\"System.Windows.Controls.TextBlock.GetTextPositionFromDistance\"))\n {\n e.Handled = true;\n }\n }\n }\n}\n" }, { "answer_id": 67036133, "author": "Nicke Manarin", "author_id": 1735672, "author_profile": "https://Stackoverflow.com/users/1735672", "pm_score": 0, "selected": false, "text": "FlowDocument FlowDocumentScrollViewer <FlowDocumentScrollViewer Grid.Row=\"2\" Margin=\"5,3\" BorderThickness=\"1\" \n BorderBrush=\"{DynamicResource Element.Border}\" \n VerticalScrollBarVisibility=\"Auto\">\n <FlowDocument>\n <Paragraph>\n <Bold>Some bold text in the paragraph.</Bold>\n Some text that is not bold.\n </Paragraph>\n\n <List>\n <ListItem>\n <Paragraph>ListItem 1</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 2</Paragraph>\n </ListItem>\n <ListItem>\n <Paragraph>ListItem 3</Paragraph>\n </ListItem>\n </List>\n </FlowDocument>\n</FlowDocumentScrollViewer>\n" }, { "answer_id": 68139947, "author": "Shakti", "author_id": 741147, "author_profile": "https://Stackoverflow.com/users/741147", "pm_score": 1, "selected": false, "text": "public class TextBlockEx : TextBox\n{\n public TextBlockEx()\n {\n base.BorderThickness = new Thickness(0);\n IsReadOnly = true;\n TextWrapping = TextWrapping.Wrap;\n //Background = Brushes.Transparent; // Uncomment to get parent's background color\n }\n}\n" }, { "answer_id": 69110678, "author": "Michael Wagner", "author_id": 12470516, "author_profile": "https://Stackoverflow.com/users/12470516", "pm_score": 0, "selected": false, "text": "Background Run.Background" }, { "answer_id": 74535160, "author": "altair", "author_id": 1516045, "author_profile": "https://Stackoverflow.com/users/1516045", "pm_score": 0, "selected": false, "text": "public class SelectableTextBlock : TextBlock\n{\n\n static readonly Type TextEditorType\n = Type.GetType(\"System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n static readonly PropertyInfo IsReadOnlyProp\n = TextEditorType.GetProperty(\"IsReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly PropertyInfo TextViewProp\n = TextEditorType.GetProperty(\"TextView\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static readonly MethodInfo RegisterMethod\n = TextEditorType.GetMethod(\"RegisterCommandHandlers\",\n BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);\n\n static readonly Type TextContainerType\n = Type.GetType(\"System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n static readonly PropertyInfo TextContainerTextViewProp\n = TextContainerType.GetProperty(\"TextView\");\n\n static readonly PropertyInfo TextContainerTextSelectionProp\n = TextContainerType.GetProperty(\"TextSelection\");\n\n static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty(\"TextContainer\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)\n {\n RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });\n }\n\n static SelectableTextBlock()\n {\n FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));\n RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);\n\n // remove the focus rectangle around the control\n FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));\n }\n\n //private readonly TextEditorWrapper _editor;\n object? textContainer;\n object? editor;\n public TextSelection TextSelection { get; private set; }\n\n public SelectableTextBlock()\n {\n textContainer = TextContainerProp.GetValue(this);\n\n editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,\n null, new[] { textContainer, this, false }, null);\n\n\n IsReadOnlyProp.SetValue(editor, true);\n TextViewProp.SetValue(editor, TextContainerTextViewProp.GetValue(textContainer));\n\n TextSelection = (TextSelection)TextContainerTextSelectionProp.GetValue(textContainer);\n TextSelection.Changed += (s, e) => OnSelectionChanged?.Invoke(this, e);\n }\n\n public event EventHandler OnSelectionChanged;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424554/" ]
136,443
<p>We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block:</p> <pre><code>public PageSizer(string href, int index) { HRef = href; PageIndex = index; } </code></pre> <p>Copy and pasted from IE7, ends up like this:</p> <pre> public PageSizer(string href, int index){ HRef = href; PageIndex = index; } </pre> <p>Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this:</p> <pre><code>&lt;pre&gt;&lt;code&gt;public PageSizer(string href, int index) { HRef = href; PageIndex = index; } &lt;/code&gt;&lt;/pre&gt; </code></pre> <p>So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way?</p> <blockquote> <p>Update: <strong>this specifically has to do with <code>&lt;pre&gt;</code> <code>&lt;code&gt;</code> blocks that are being modified at runtime via JavaScript.</strong> The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.</p> </blockquote>
[ { "answer_id": 136510, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": -1, "selected": false, "text": "<code>" }, { "answer_id": 136586, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 4, "selected": false, "text": "public PageSizer(string href, int index)<br />{<br /> HRef = href;<br /> PageIndex = index;<br /> } \npublic PageSizer(string href, int index)<br />\n{<br />\n HRef = href;<br />\n PageIndex = index;<br />\n}<br />\n \nhtml.push(htmlChunk.replace(newlineRe, '<br />'));\n \nhtml.push(htmlChunk.replace(newlineRe, '\\n'));\n" }, { "answer_id": 155826, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 0, "selected": false, "text": "html.push(htmlChunk.replace(newlineRe, '\\n'));\n <pre>" }, { "answer_id": 156069, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 0, "selected": false, "text": "\n// Replace <br>s with line-feeds so that copying and pasting works\n// on IE 6.\n// Doing this on other browsers breaks lots of stuff since \\r\\n is\n// treated as two newlines on Firefox, and doing this also slows\n// down rendering.\n" }, { "answer_id": 159582, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 6, "selected": true, "text": "function _pr_isIE7() {\n var isIE7 = navigator && navigator.userAgent &&\n /\\bMSIE 7\\./.test(navigator.userAgent);\n _pr_isIE7 = function () { return isIE7; };\n return isIE7;\n}\n function prettyPrint(opt_whenDone) {\n var isIE6 = _pr_isIE6();\n+ var isIE7 = _pr_isIE7();\n - if (isIE6 && cs.tagName === 'PRE') {\n+ if ((isIE6 || isIE7) && cs.tagName === 'PRE') {\n var lineBreaks = cs.getElementsByTagName('br');\n+ var newline;\n+ if (isIE6) {\n+ newline = '\\r\\n';\n+ } else {\n+ newline = '\\r';\n+ }\n for (var j = lineBreaks.length; --j >= 0;) {\n var lineBreak = lineBreaks[j];\n lineBreak.parentNode.replaceChild(\n- document.createTextNode('\\r\\n'), lineBreak);\n+ document.createTextNode(newline), lineBreak);\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
136,444
<p>I'm working on an embedded linux system in C, I'm looking for the source code to the equivalet of SendARP in Windows. Any pointers?</p>
[ { "answer_id": 137384, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": true, "text": "\nfoo = system(\"/somepath/arping somehost\");\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15797/" ]
136,458
<p>How would I have a <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used? </p> <p>It would also be nice if the back button would reload the original URL.</p> <p>I am trying to record JavaScript state in the URL.</p>
[ { "answer_id": 136506, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 8, "selected": false, "text": "history.pushState history.popState window.location.hash onhashchange setInterval" }, { "answer_id": 702930, "author": "user58670", "author_id": 58670, "author_profile": "https://Stackoverflow.com/users/58670", "pm_score": 1, "selected": false, "text": "http://domain.com/site/page.html location.append = new.html http://domain.com/site/page.htmlnew.html location.get = me=1&page=1 http://domain.com/site/page.html?me=1&page=1 div" }, { "answer_id": 4222584, "author": "clu3", "author_id": 513116, "author_profile": "https://Stackoverflow.com/users/513116", "pm_score": 8, "selected": true, "text": "history.pushState <script type=\"text/javascript\">\nvar stateObj = { foo: \"bar\" };\nfunction change_my_url()\n{\n history.pushState(stateObj, \"page 2\", \"bar.html\");\n}\nvar link = document.getElementById('click');\nlink.addEventListener('click', change_my_url, false);\n</script>\n <a href=\"#\" id='click'>Click to change url to bar.html</a>\n history.replaceState" }, { "answer_id": 4659443, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 2, "selected": false, "text": "/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507\n /photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507\n" }, { "answer_id": 19258379, "author": "Ilia", "author_id": 1455661, "author_profile": "https://Stackoverflow.com/users/1455661", "pm_score": 3, "selected": false, "text": "pushState history.pushState(null, null, $(this).attr('href')); $('a').click(function (event) {\n\n // Prevent default click action\n event.preventDefault(); \n\n // Detect if pushState is available\n if(history.pushState) {\n history.pushState(null, null, $(this).attr('href'));\n }\n return false;\n});\n history.pushState() window.history.pushState(\"object\", \"Your New Title\", \"/new-url\"); pushState() pushState() pushState() pushState() pushState()" }, { "answer_id": 19665941, "author": "Tusko Trush", "author_id": 1627681, "author_profile": "https://Stackoverflow.com/users/1627681", "pm_score": 1, "selected": false, "text": "//change address bar\nfunction setLocation(curLoc){\n try {\n history.pushState(null, null, curLoc);\n return false;\n } catch(e) {}\n location.hash = '#' + curLoc;\n}\n setLocation('http://example.com/your-url-here');\n $(document).ready(function(){\n $('nav li a').on('click', function(){\n if($(this).hasClass('active')) {\n\n } else {\n setLocation($(this).attr('href'));\n }\n return false;\n });\n});\n" }, { "answer_id": 24365301, "author": "Adam Hey", "author_id": 2261245, "author_profile": "https://Stackoverflow.com/users/2261245", "pm_score": 0, "selected": false, "text": "location.hash=\"myValue\";\n #myValue location.hash # location.hash var articleId = window.location.hash.replace(\"#\",\"\");\n" }, { "answer_id": 50036569, "author": "Veshraj Joshi", "author_id": 2347438, "author_profile": "https://Stackoverflow.com/users/2347438", "pm_score": 2, "selected": false, "text": "history.replaceState() history.replaceState(data,\"Title of page\"[,'url-of-the-page']);\n" }, { "answer_id": 54715005, "author": "sam", "author_id": 7538821, "author_profile": "https://Stackoverflow.com/users/7538821", "pm_score": 2, "selected": false, "text": "window.history.pushState(null, null, \"/abc\")\n /abc" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
136,467
<p>short:</p> <p>Is there a way in Ruby to DRY-ify this:</p> <pre><code>def entry_point_one begin do_something rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc =&gt; syn_err raise syn_err.exception(syn_err.message) end end def entry_point_two begin do_something_else rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc =&gt; syn_err raise syn_err.exception(syn_err.message) end end </code></pre> <p>longer:</p> <p>I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do_something, especially since the interpreter makes use of recursion.</p> <p>As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this:</p> <pre><code>def entry_point_one re_raise_known_exceptions {do_something} end def entry_point_two re_raise_known_exceptions {do_something_else} end def re_raise_known_exceptions yield rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc =&gt; syn_err raise syn_err.exception(syn_err.message) end </code></pre> <p>But that makes the method re-raise-known-exceptions show up in the back trace.</p> <p>edit: I guess what I want would be something like a C pre-processing macro</p>
[ { "answer_id": 136541, "author": "Patrick Huizinga", "author_id": 15200, "author_profile": "https://Stackoverflow.com/users/15200", "pm_score": 2, "selected": false, "text": "interpreter_block {do_something}\n\ndef interpreter_block\n yield\nrescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc\n raise exc.exception(exc.message)\nend\n" }, { "answer_id": 136791, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 0, "selected": false, "text": "class MyError < StandardError; end\n\ndef interpreter_block\n yield\nrescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc\n raise MyError\nend\n" }, { "answer_id": 137389, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "COMMON_ERRORS = [ArgumentError, RuntimeError] # add your own \n\ndef f\n yield\nrescue *COMMON_ERRORS => err\n puts \"Got an error of type #{err.class}\"\nend\n\n\nf{ raise ArgumentError.new }\nGot an error of type ArgumentError\n\nf{ raise 'abc' }\nGot an error of type RuntimeError\n" }, { "answer_id": 138975, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 1, "selected": false, "text": "COMMON_ERRORS = [ArgumentError, RuntimeError]\n\ndef interpreter_block\n yield\nrescue *COMMON_ERRORS => err\n err.backtrace.delete_if{ |line| line=~/interpreter_block/ }\n raise err\nend\n" }, { "answer_id": 1517699, "author": "Peter Wagenet", "author_id": 181916, "author_profile": "https://Stackoverflow.com/users/181916", "pm_score": 1, "selected": false, "text": "class Interpreter\n\n def method1\n error_catcher{ puts 1 / 0 }\n end\n\n def error_catcher\n yield\n rescue => err\n err.set_backtrace(err.backtrace - err.backtrace[1..2])\n raise err\n end\n\nend\n err.set_backtrace(err.backtrace - err.backtrace[1..2]) ZeroDivisionError: divided by 0\n from (irb):43:in `/'\n from (irb):43:in `block in method1'\n from (irb):47:in `error_catcher'\n from (irb):43:in `method1'\n from (irb):54\n from /Users/peterwagenet/.ruby_versions/ruby-1.9.1-p129/bin/irb:12:in `<main>'\n ZeroDivisionError: divided by 0\n from (irb):73:in `/'\n from (irb):73:in `method1'\n from (irb):84\n from /Users/peterwagenet/.ruby_versions/ruby-1.9.1-p129/bin/irb:12:in `<main>'\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15200/" ]
136,474
<p>I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:</p> <pre><code>Vector itemsVector = getItems(); Collections.shuffle(itemsVector); itemsVector.setSize(5); </code></pre> <p>While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is</p> <pre><code>Vector itemsVector = getItems(); Random rand = new Random(System.currentTimeMillis()); // would make this static to the class List subsetList = new ArrayList(5); for (int i = 0; i &lt; 5; i++) { // be sure to use Vector.remove() or you may get the same item twice subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size()))); } </code></pre> <p>Any suggestions on better ways to draw out a random subset from a Collection?</p>
[ { "answer_id": 136544, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < 5; i++){\n int r = rand.nextInt(itemsVector.size());\n while (boolArray[r]){\n r = rand.nextInt(itemsVector.size());\n }\n subsetList.add(itemsVector[r]);\n boolArray[r] = true;\n}\n" }, { "answer_id": 136730, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 3, "selected": false, "text": "void genknuth(int m, int n)\n{ for (int i = 0; i < n; i++)\n /* select m of remaining n-i */\n if ((bigrand() % (n-i)) < m) {\n cout << i << \"\\n\";\n m--;\n }\n}\n void genshuf(int m, int n)\n{ int i,j;\n int *x = new int[n];\n for (i = 0; i < n; i++)\n x[i] = i;\n for (i = 0; i < m; i++) {\n j = randint(i, n-1);\n int t = x[i]; x[i] = x[j]; x[j] = t;\n }\n sort(x, x+m);\n for (i = 0; i< m; i++)\n cout << x[i] << \"\\n\";\n}\n" }, { "answer_id": 136765, "author": "Wesley Tarle", "author_id": 17057, "author_profile": "https://Stackoverflow.com/users/17057", "pm_score": 0, "selected": false, "text": "Set<Integer> s = new HashSet<Integer>()\n// add random indexes to s\nwhile(s.size() < 5)\n{\n s.add(rand.nextInt(itemsVector.size()))\n}\n// iterate over s and put the items in the list\nfor(Integer i : s)\n{\n out.add(itemsVector.get(i));\n}\n" }, { "answer_id": 136858, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 3, "selected": false, "text": "public static <T> List<T> getRandomSubList(List<T> input, int subsetSize)\n{\n Random r = new Random();\n int inputSize = input.size();\n for (int i = 0; i < subsetSize; i++)\n {\n int indexToSwap = i + r.nextInt(inputSize - i);\n T temp = input.get(i);\n input.set(i, input.get(indexToSwap));\n input.set(indexToSwap, temp);\n }\n return input.subList(0, subsetSize);\n}\n java.util.Random java.security.SecureRandom" }, { "answer_id": 137250, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 1, "selected": false, "text": "# Returns a container s with k distinct random numbers from {0, 1, ..., n-1}\ndef ChooseRandomSubset(n, k):\n for i in range(k):\n r = UniformRandom(0, n-i) # May be 0, must be < n-i\n q = s.FirstIndexSuchThat( s[q] - q > r ) # This is the search.\n s.InsertInOrder(q ? r + q : r + len(s)) # Inserts right before q.\n return s \n" }, { "answer_id": 9550317, "author": "user967710", "author_id": 967710, "author_profile": "https://Stackoverflow.com/users/967710", "pm_score": 0, "selected": false, "text": "//Assume the set is given as an array:\nObject[] set ....;\nfor(int i=0;i<K; i++){\nrandomNumber = random() % N;\n print set[randomNumber];\n //swap the chosen element with the last place\n temp = set[randomName];\n set[randomName] = set[N-1];\n set[N-1] = temp;\n //decrease N\n N--;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459/" ]
136,500
<p>I have a string in a node and I'd like to split the string on '?' and return the last item in the array.</p> <p>For example, in the block below:</p> <pre><code>&lt;a&gt; &lt;xsl:attribute name="href"&gt; /newpage.aspx?&lt;xsl:value-of select="someNode"/&gt; &lt;/xsl:attribute&gt; Link text &lt;/a&gt; </code></pre> <p>I'd like to split the <code>someNode</code> value.</p> <p>Edit: Here's the VB.Net that I use to load the Xsl for my Asp.Net page:</p> <pre><code>Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl") Dim myXsltSettings As New XsltSettings() Dim myXMLResolver As New XmlUrlResolver() myXsltSettings.EnableScript = True myXsltSettings.EnableDocumentFunction = True myXslDoc = New XslCompiledTransform(False) myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver) Dim myStringBuilder As New StringBuilder() Dim myXmlWriter As XmlWriter = Nothing Dim myXmlWriterSettings As New XmlWriterSettings() myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto myXmlWriterSettings.Indent = True myXmlWriterSettings.OmitXmlDeclaration = True myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings) myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter) Return myStringBuilder.ToString() </code></pre> <p><strong>Update:</strong> here's <a href="http://gist.github.com/360186" rel="noreferrer">an example of splitting XML on a particular node</a></p>
[ { "answer_id": 136531, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 4, "selected": false, "text": "tokenize(string, separator) tokenize(\"XPath is fun\", \"\\s+\")\nResult: (\"XPath\", \"is\", \"fun\")\n" }, { "answer_id": 136848, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": false, "text": "substring-after() <a>\n <xsl:attribute name=\"href\">\n /newpage.aspx?<xsl:value-of select=\"substring-after(someNode, '?')\"/>\n </xsl:attribute>\n Link text\n</a>\n 'tokenize()' is an unknown XSLT function. tokenize()" }, { "answer_id": 141022, "author": "mortenbpost", "author_id": 17577, "author_profile": "https://Stackoverflow.com/users/17577", "pm_score": 7, "selected": true, "text": "<xsl:template name=\"output-tokens\">\n <xsl:param name=\"list\" /> \n <xsl:variable name=\"newlist\" select=\"concat(normalize-space($list), ' ')\" /> \n <xsl:variable name=\"first\" select=\"substring-before($newlist, ' ')\" /> \n <xsl:variable name=\"remaining\" select=\"substring-after($newlist, ' ')\" /> \n <id>\n <xsl:value-of select=\"$first\" /> \n </id>\n <xsl:if test=\"$remaining\">\n <xsl:call-template name=\"output-tokens\">\n <xsl:with-param name=\"list\" select=\"$remaining\" /> \n </xsl:call-template>\n </xsl:if>\n</xsl:template>\n" }, { "answer_id": 2867303, "author": "Paul Wagland", "author_id": 97627, "author_profile": "https://Stackoverflow.com/users/97627", "pm_score": 3, "selected": false, "text": "<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:str=\"http://exslt.org/strings\"\n extension-element-prefixes=\"str\">\n\n...\n <a>\n <xsl:attribute name=\"href\">\n <xsl:text>/newpage.aspx?</xsl:text>\n <xsl:value-of select=\"str:tokenize(someNode)[2]\"/>\n </xsl:attribute> \n </a>\n...\n</xsl:stylesheet>\n" }, { "answer_id": 6160502, "author": "Lav G", "author_id": 184347, "author_profile": "https://Stackoverflow.com/users/184347", "pm_score": 2, "selected": false, "text": "string-before string-after <?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:template match=\"/\">\n<xsl:for-each select=\"Paths/Item\">\n<xsl:call-template name=\"SplitText\">\n<xsl:with-param name=\"inputString\" select=\"Path\"/>\n<xsl:with-param name=\"delimiter\" select=\"Delimiter\"/>\n</xsl:call-template>\n<br/>\n</xsl:for-each>\n</xsl:template>\n<xsl:template name=\"SplitText\">\n<xsl:param name=\"inputString\"/>\n<xsl:param name=\"delimiter\"/>\n<xsl:choose>\n<xsl:when test=\"contains($inputString, $delimiter)\">\n<xsl:value-of select=\"substring-before($inputString,$delimiter)\"/>\n<xsl:text disable-output-escaping = \"no\"> </xsl:text>\n<xsl:call-template name=\"SplitText\">\n<xsl:with-param name=\"inputString\" select=\"substring-after($inputString,$delimiter)\"/>\n<xsl:with-param name=\"delimiter\" select=\"$delimiter\"/>\n</xsl:call-template>\n</xsl:when>\n<xsl:otherwise>\n<xsl:choose>\n<xsl:when test=\"$inputString = ''\">\n<xsl:text></xsl:text>\n</xsl:when>\n<xsl:otherwise>\n<xsl:value-of select=\"$inputString\"/>\n<xsl:text> </xsl:text>\n</xsl:otherwise>\n</xsl:choose>\n</xsl:otherwise>\n</xsl:choose>\n</xsl:template>\n</xsl:stylesheet>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"textSpliter.xslt\"?>\n<Paths>\n <Item>\n <Path>C:\\ProgramFiles\\SomeWierdSoftware</Path>\n <Delimiter>\\</Delimiter>\n </Item>\n</Paths> \n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
136,505
<p>I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits.</p> <p>Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs?</p>
[ { "answer_id": 136591, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 6, "selected": true, "text": "\"ca761232ed4211cebacd00aa0057b223\" \n\n\"CA761232-ED42-11CE-BACD-00AA0057B223\" \n\n\"{CA761232-ED42-11CE-BACD-00AA0057B223}\" \n\n\"(CA761232-ED42-11CE-BACD-00AA0057B223)\" \n\n\"{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}\" \n" }, { "answer_id": 3999043, "author": "JimP", "author_id": 178688, "author_profile": "https://Stackoverflow.com/users/178688", "pm_score": 5, "selected": false, "text": "[\\w]{8}(-[\\w]{4}){3}-[\\w]{12} [\\w]{8}-[\\w]{4}-[\\w]{4}-[\\w]{4}-[\\w]{12}" }, { "answer_id": 6640851, "author": "Ivelin", "author_id": 805030, "author_profile": "https://Stackoverflow.com/users/805030", "pm_score": 9, "selected": false, "text": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n ^...$ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\n" }, { "answer_id": 12843265, "author": "Matthew F. Robben", "author_id": 1532867, "author_profile": "https://Stackoverflow.com/users/1532867", "pm_score": 7, "selected": false, "text": "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}" }, { "answer_id": 14166194, "author": "Gajus", "author_id": 368691, "author_profile": "https://Stackoverflow.com/users/368691", "pm_score": 7, "selected": false, "text": "/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/\n" }, { "answer_id": 14712056, "author": "Bruno Bronosky", "author_id": 117471, "author_profile": "https://Stackoverflow.com/users/117471", "pm_score": 3, "selected": false, "text": "import re\ntest = \"01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK\"\nre.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars\n## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']\nre.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars\n## ['01234ABCDEF', '01234', 'ABCDEF']\nre.compile(r'[0-F]+', re.I).findall(test) # Good\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\nre.compile(r'[0-f]+', re.I).findall(test) # Good\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\nre.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\nre.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)\n## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']\n re_uuid = re.compile(\"[0-F]{8}-([0-F]{4}-){3}[0-F]{12}\", re.I)\n :;<=>?@'" }, { "answer_id": 16026126, "author": "Christopher Smith", "author_id": 60871, "author_profile": "https://Stackoverflow.com/users/60871", "pm_score": 3, "selected": false, "text": "re_uuid = re.compile(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', re.I)\n" }, { "answer_id": 23117267, "author": "Anton K", "author_id": 209406, "author_profile": "https://Stackoverflow.com/users/209406", "pm_score": 3, "selected": false, "text": "#include <regex> // Required include\n\n...\n\n// Source string \nstd::wstring srcStr = L\"String with GIUD: {4d36e96e-e325-11ce-bfc1-08002be10318} any text\";\n\n// Regex and match\nstd::wsmatch match;\nstd::wregex rx(L\"(\\\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\\\})\", std::regex_constants::icase);\n\n// Search\nstd::regex_search(srcStr, match, rx);\n\n// Result\nstd::wstring strGUID = match[1];\n" }, { "answer_id": 24387746, "author": "iGEL", "author_id": 362378, "author_profile": "https://Stackoverflow.com/users/362378", "pm_score": 5, "selected": false, "text": "/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/i\n" }, { "answer_id": 34841029, "author": "abufct", "author_id": 1319925, "author_profile": "https://Stackoverflow.com/users/1319925", "pm_score": 2, "selected": false, "text": "$UUID_RE = join '-', map { \"[0-9a-f]{$_}\" } 8, 4, 4, 4, 12;\n" }, { "answer_id": 38162719, "author": "Quanlong", "author_id": 622662, "author_profile": "https://Stackoverflow.com/users/622662", "pm_score": 3, "selected": false, "text": "uuidgen [A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}\n uuidgen | grep -E \"[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}\"\n" }, { "answer_id": 38191078, "author": "Ivan Gabriele", "author_id": 2736233, "author_profile": "https://Stackoverflow.com/users/2736233", "pm_score": 7, "selected": false, "text": "4.1.3. Version [VERSION_NUMBER][0-9A-F]{3} /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i\n" }, { "answer_id": 58833439, "author": "asherbret", "author_id": 2016436, "author_profile": "https://Stackoverflow.com/users/2016436", "pm_score": 2, "selected": false, "text": "grep -E \"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}\"\n $> echo \"f2575e6a-9bce-49e7-ae7c-bff6b555bda4\" | grep -E \"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}\"\nf2575e6a-9bce-49e7-ae7c-bff6b555bda4\n" }, { "answer_id": 61022108, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 3, "selected": false, "text": "grep -E [[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\n (…) (?:…)" }, { "answer_id": 62872109, "author": "gildniy", "author_id": 1992866, "author_profile": "https://Stackoverflow.com/users/1992866", "pm_score": 3, "selected": false, "text": "const regex = [0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}\n" }, { "answer_id": 65312002, "author": "Oxydron", "author_id": 1891899, "author_profile": "https://Stackoverflow.com/users/1891899", "pm_score": 1, "selected": false, "text": "([\\d\\w]{8})-?([\\d\\w]{4})-?([\\d\\w]{4})-?([\\d\\w]{4})-?([\\d\\w]{12})|[{0x]*([\\d\\w]{8})[0x, ]{4}([\\d\\w]{4})[0x, ]{4}([\\d\\w]{4})[0x, {]{5}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})[0x, ]{4}([\\d\\w]{2})\n" }, { "answer_id": 71296472, "author": "Vlad", "author_id": 12250254, "author_profile": "https://Stackoverflow.com/users/12250254", "pm_score": 0, "selected": false, "text": "/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i\n" }, { "answer_id": 72568589, "author": "Hitesh Kalwani", "author_id": 4611516, "author_profile": "https://Stackoverflow.com/users/4611516", "pm_score": 0, "selected": false, "text": "^[^\\W_]{8}(-[^\\W_]{4}){4}[^\\W_]{8}$ ^[^\\W_]{8}(-[^\\W_]{4}){3}-[^\\W_]{12}$" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
136,528
<p>I need to generate a new interface at run-time with all the same members as an existing interface, except that I will be putting different attributes on some of the methods (some of the attribute parameters are not known until run-time). How can it be achieved?</p>
[ { "answer_id": 136600, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 4, "selected": true, "text": "TypeAttributes.Interface TypeBuilder.CreateType" }, { "answer_id": 808469, "author": "Colin Burnett", "author_id": 98830, "author_profile": "https://Stackoverflow.com/users/98830", "pm_score": 4, "selected": false, "text": "using System.Reflection;\nusing System.Reflection.Emit;\n\n// Need the output the assembly to a specific directory\nstring outputdir = \"F:\\\\tmp\\\\\";\nstring fname = \"Hello.World.dll\";\n\n// Define the assembly name\nAssemblyName bAssemblyName = new AssemblyName();\nbAssemblyName.Name = \"Hello.World\";\nbAssemblyName.Version = new system.Version(1,2,3,4);\n\n// Define the new assembly and module\nAssemblyBuilder bAssembly = System.AppDomain.CurrentDomain.DefineDynamicAssembly(bAssemblyName, AssemblyBuilderAccess.Save, outputdir);\nModuleBuilder bModule = bAssembly.DefineDynamicModule(fname, true);\n\nTypeBuilder tInterface = bModule.DefineType(\"IFoo\", TypeAttributes.Interface | TypeAttributes.Public);\n\nConstructorInfo con = typeof(FunAttribute).GetConstructor(new Type[] { typeof(string) });\nCustomAttributeBuilder cab = new CustomAttributeBuilder(con, new object[] { \"Hello\" });\ntInterface.SetCustomAttribute(cab);\n\nType tInt = tInterface.CreateType();\n\nbAssembly.Save(fname);\n namespace Hello.World\n{\n [Fun(\"Hello\")]\n public interface IFoo\n {}\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
136,536
<p>FYI: I am running on dotnet 3.5 SP1</p> <p>I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder). After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of <code>myDataset.tables(0).Rows(0)("ID")</code>, but it is System.DBNull (despite the fact that the row was inserted).</p> <p>(Note: I do not want to explicitly write a new stored procedure to do this!)</p> <p>One method often posted <a href="http://forums.asp.net/t/951025.aspx" rel="noreferrer">http://forums.asp.net/t/951025.aspx</a> modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so:</p> <pre><code>SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()" InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord </code></pre> <p>Apparently, this seemed to work for many people in the past, but does not work for me.</p> <p>Another technique: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&amp;SiteID=1" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&amp;SiteID=1</a> doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter).</p> <p>Does anyone know the answer to this???</p>
[ { "answer_id": 137468, "author": "dbugger", "author_id": 15754, "author_profile": "https://Stackoverflow.com/users/15754", "pm_score": 2, "selected": false, "text": "InsertCommand.UpdatedRowSource = UpdateRowSource.Both;\n INSERT INTO [SomeTable] ([Name]) VALUES (@Name)\n" }, { "answer_id": 2028699, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "SqlDataAdapter.InsertCommand.CommandText += \"; SELECT MyTableID = SCOPE_IDENTITY()\" InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;\n" }, { "answer_id": 2377462, "author": "Pedrao", "author_id": 286036, "author_profile": "https://Stackoverflow.com/users/286036", "pm_score": 2, "selected": false, "text": " private static void CloneBuilderCommand(System.Data.Common.DbCommand toClone,System.Data.Common.DbCommand repository)\n {\n repository.CommandText = toClone.CommandText;\n //Copying parameters\n if (toClone.Parameters.Count == 0) return;//No parameters to clone? go away!\n System.Data.Common.DbParameter[] parametersArray= new System.Data.Common.DbParameter[toClone.Parameters.Count];\n toClone.Parameters.CopyTo(parametersArray, 0);\n toClone.Parameters.Clear();//Removing association before link to the repository one\n repository.Parameters.AddRange(parametersArray); \n }\n" }, { "answer_id": 2514144, "author": "Rob Vermeulen", "author_id": 150187, "author_profile": "https://Stackoverflow.com/users/150187", "pm_score": 2, "selected": false, "text": "SqlCommandBuilder commandBuilder = new SqlCommandBuilder(myDataAdapter);\nmyDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;\n" }, { "answer_id": 4375297, "author": "Jay Kidd", "author_id": 533475, "author_profile": "https://Stackoverflow.com/users/533475", "pm_score": 2, "selected": false, "text": " '-- post a new entry and return the column number\n ' get the table stucture\n Dim ds As DataSet = New DataSet()\n Dim da As SqlDataAdapter = New SqlDataAdapter(String.Concat(\"SELECT * FROM [\", fileRegisterSchemaName, \"].[\", fileRegisterTableName, \"] WHERE 1=0\"), sqlConnectionString)\n Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)\n\n ' since we want the identity column back (FileID), we need to write our own INSERT statement\n da.InsertCommand = New SqlCommand(String.Concat(\"INSERT INTO [\", fileRegisterSchemaName, \"].[\", fileRegisterTableName, \"] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT @FileID = SCOPE_IDENTITY();\"))\n da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord\n With da.InsertCommand.Parameters\n .Add(\"@FileName\", SqlDbType.VarChar, 1024, \"FileName\")\n .Add(\"@User\", SqlDbType.VarChar, 24, \"User\")\n .Add(\"@Date\", SqlDbType.DateTime, 0, \"Date\")\n .Add(\"@Table\", SqlDbType.VarChar, 128, \"FileName\")\n ' allow the @FileID to be returned back to us\n .Add(\"@FileID\", SqlDbType.Int, 0, \"FileID\")\n .Item(\"@FileID\").Direction = ParameterDirection.Output\n End With\n\n ' copy the table structure from the server and create a reference to the table(dt)\n da.Fill(ds, fileRegisterTableName)\n Dim dt As DataTable = ds.Tables(fileRegisterTableName)\n\n ' add a new record\n Dim dr As DataRow = dt.NewRow()\n dr(\"FileName\") = fileName\n dr(\"User\") = String.Concat(Environment.UserDomainName, \"\\\", Environment.UserName)\n dr(\"Date\") = DateTime.Now()\n dr(\"Table\") = targetTableName\n dt.Rows.Add(dr)\n\n ' save the new record\n da.Update(dt)\n\n ' return the FileID (Identity)\n Return da.InsertCommand.Parameters(\"@FileID\").Value\n ' add the file record\n Dim sqlCmd As SqlCommand = New SqlCommand(String.Concat(\"INSERT INTO [\", fileRegisterSchemaName, \"].[\", fileRegisterTableName, \"] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT SCOPE_IDENTITY();\"), New SqlConnection(sqlConnectionString))\n With sqlCmd.Parameters\n .AddWithValue(\"@FileName\", fileName)\n .AddWithValue(\"@User\", String.Concat(Environment.UserDomainName, \"\\\", Environment.UserName))\n .AddWithValue(\"@Date\", DateTime.Now())\n .AddWithValue(\"@Table\", targetTableName)\n End With\n sqlCmd.Connection.Open()\n Return sqlCmd.ExecuteScalar\n" }, { "answer_id": 7255577, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 2, "selected": false, "text": "//_dataCommand is an instance of SqlDataAdapter\n//connection is an instance of ConnectionProvider which has a property called DBConnection of type SqlConnection\n//_dataTable is an instance of DataTable\n\nSqlCommandBuilder bldr = new SqlCommandBuilder(_dataCommand);\nSqlCommand cmdInsert = new SqlCommand(bldr.GetInsertCommand().CommandText, connection.DBConnection);\ncmdInsert.CommandText += \";Select SCOPE_IDENTITY() as id\";\n\nSqlParameter[] aParams = new\nSqlParameter[bldr.GetInsertCommand().Parameters.Count];\nbldr.GetInsertCommand().Parameters.CopyTo(aParams, 0);\nbldr.GetInsertCommand().Parameters.Clear();\n\nfor(int i=0 ; i < aParams.Length; i++)\n{\n cmdInsert.Parameters.Add(aParams[i]);\n}\n\n_dataCommand.InsertCommand = cmdInsert;\n_dataCommand.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n_dataCommand.Update(_dataTable);\n" }, { "answer_id": 7280103, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Dim sb As New StringBuilder\nsb.Append(\" Insert into \")\nsb.Append(tbl)\nsb.Append(\" \")\nsb.Append(cnames)\nsb.Append(\" values \")\nsb.Append(cvals)\nsb.Append(\";Select SCOPE_IDENTITY() as id\") 'add identity selection\n\nDim sql As String = sb.ToString\n\nDim cmd As System.Data.Common.DbCommand = connection.CreateCommand\ncmd.Connection = connection\ncmd.CommandText = sql\ncmd.CommandType = CommandType.Text\ncmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord\n\n'retrieve the new identity value, and update the object\nDim dec as decimal = CType(cmd.ExecuteScalar, Decimal)\n" }, { "answer_id": 7613506, "author": "Ray Fitzharris", "author_id": 973478, "author_profile": "https://Stackoverflow.com/users/973478", "pm_score": 3, "selected": false, "text": "SqlDataAdapter da = new SqlDataAdapter(\"select Top 0 \" + GetTableSelectList(dt) + \n\"FROM \" + tableName,_sqlConnectString);\nSqlCommandBuilder custCB = new SqlCommandBuilder(da);\ncustCB.QuotePrefix = \"[\";\ncustCB.QuoteSuffix = \"]\";\nda.TableMappings.Add(\"Table\", dt.TableName);\n\nda.UpdateCommand = custCB.GetUpdateCommand();\nda.InsertCommand = custCB.GetInsertCommand();\nda.DeleteCommand = custCB.GetDeleteCommand();\n\nda.InsertCommand.CommandText = String.Concat(da.InsertCommand.CommandText, \n\"; SELECT \",GetTableSelectList(dt),\" From \", tableName, \n\" where \",pKeyName,\"=SCOPE_IDENTITY()\");\n\nSqlParameter identParam = new SqlParameter(\"@Identity\", SqlDbType.BigInt, 0, pKeyName);\nidentParam.Direction = ParameterDirection.Output;\nda.InsertCommand.Parameters.Add(identParam);\n\nda.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n\n//new adaptor for performing the update \nSqlDataAdapter daAutoNum = new SqlDataAdapter();\ndaAutoNum.DeleteCommand = da.DeleteCommand;\ndaAutoNum.InsertCommand = da.InsertCommand;\ndaAutoNum.UpdateCommand = da.UpdateCommand;\n\ndaAutoNum.Update(dt);\n" }, { "answer_id": 12105428, "author": "David", "author_id": 266281, "author_profile": "https://Stackoverflow.com/users/266281", "pm_score": 2, "selected": false, "text": "void dataSet_RowUpdating(object sender, SqlRowUpdatingEventArgs e)\n{\n if (e.StatementType == StatementType.Insert)\n {\n e.Command.CommandText += \"; SELECT ID = SCOPE_IDENTITY()\";\n e.Command.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n }\n}\n" }, { "answer_id": 40614940, "author": "esc", "author_id": 2594731, "author_profile": "https://Stackoverflow.com/users/2594731", "pm_score": 0, "selected": false, "text": "SqlDataAdapter da = new SqlDataAdapter(\"SELECT * FROM Mytable;\" , sqlConnection);\n\nSqlCommandBuilder cb = new SqlCommandBuilder(da);\n\nda.DeleteCommand = (SqlCommand)cb.GetDeleteCommand().Clone();\nda.UpdateCommand = (SqlCommand)cb.GetUpdateCommand().Clone();\n\nSqlCommand insertCmd = (SqlCommand)cb.GetInsertCommand().Clone();\n\ninsertCmd.CommandText += \";SET @Id = SCOPE_IDENTITY();\";\ninsertCmd.Parameters.Add(\"@Id\", SqlDbType.Int, 0, \"Id\").Direction = ParameterDirection.Output;\nda.InsertCommand = insertCmd;\nda.InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;\n\ncb.Dispose();\n" }, { "answer_id": 67707913, "author": "Kechkouch", "author_id": 7439988, "author_profile": "https://Stackoverflow.com/users/7439988", "pm_score": 0, "selected": false, "text": "SqlCommandBuilder cb = new SqlCommandBuilder(da);\ncb.ConflictOption = ConflictOption.OverwriteChanges;\n\nda.InsertCommand = cb.GetInsertCommand().Clone();\nda.InsertCommand.CommandText += \"; SELECT idTable = SCOPE_IDENTITY()\";\nda.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;\n\nda.Update(dt);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
136,539
<p>Is there a way through the .net framework to determine if a folder is shared or not?</p> <p>Neither Diretory, DirectoryInfo or FileAttributes seem to have any corresponding field.</p> <p>One thing I forgot to mention was that I want to be checking for network shares. But I'll investigate the WMI stuff.</p>
[ { "answer_id": 136551, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 0, "selected": false, "text": "SELECT * FROM Win32_ShareToDirectory" }, { "answer_id": 136663, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 3, "selected": false, "text": "public static List<string> GetSharedFolders()\n{\n\n List<string> sharedFolders = new List<string>();\n\n // Object to query the WMI Win32_Share API for shared files...\n\n ManagementObjectSearcher searcher = new ManagementObjectSearcher(\"select * from win32_share\");\n\n ManagementBaseObject outParams;\n\n ManagementClass mc = new ManagementClass(\"Win32_Share\"); //for local shares\n\n foreach (ManagementObject share in searcher.Get()){\n\n string type = share[\"Type\"].ToString();\n\n if (type == \"0\") // 0 = DiskDrive (1 = Print Queue, 2 = Device, 3 = IPH)\n {\n string name = share[\"Name\"].ToString(); //getting share name\n\n string path = share[\"Path\"].ToString(); //getting share path\n\n string caption = share[\"Caption\"].ToString(); //getting share description\n\n sharedFolders.Add(path);\n }\n\n }\n\n return sharedFolders;\n\n}\n" }, { "answer_id": 136814, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 2, "selected": false, "text": "private void button1_Click(object sender, EventArgs e)\n{\n Runspace rs = RunspaceFactory.CreateRunspace();\n rs.Open();\n Pipeline pl = rs.CreatePipeline();\n pl.Commands.AddScript(\"get-wmiobject win32_share\");\n\n StringBuilder sb = new StringBuilder();\n Collection<PSObject> list = pl.Invoke();\n rs.Close();\n foreach (PSObject obj in list)\n {\n string name = obj.Properties[\"Name\"].Value as string;\n string path = obj.Properties[\"Path\"].Value as string;\n string desc = obj.Properties[\"Description\"].Value as string;\n\n sb.AppendLine(string.Format(\"{0}{1}{2}\",name, path, desc));\n }\n // do something with the results...\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
136,548
<p>In C++ you can initialize a variable in an if statement, like so:</p> <pre><code>if (CThing* pThing = GetThing()) { } </code></pre> <p>Why would one consider this bad or good style? What are the benefits and disadvantages?</p> <p>Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:</p> <pre><code>if (CThing* pThing = GetThing() &amp;&amp; pThing-&gt;IsReallySomeThing()) { } </code></pre> <p>If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.</p> <p><a href="https://stackoverflow.com/questions/136373/initializing-a-variable-in-a-conditional-statment">Question borrowed from here, similar topic but PHP.</a></p>
[ { "answer_id": 136590, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 2, "selected": false, "text": "if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))\n{\n}\n" }, { "answer_id": 136643, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "for(int i = 0; i > 20; i++) {\n // some code\n}\n\ncout << i << endl;\n" }, { "answer_id": 136660, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 0, "selected": false, "text": "{\n CThing *pThing = GetThing();\n if(pThing ? pThing->IsReallySomeThing() : false)\n {\n // Do whatever\n }\n}\n" }, { "answer_id": 136695, "author": "Wesley Tarle", "author_id": 17057, "author_profile": "https://Stackoverflow.com/users/17057", "pm_score": 6, "selected": true, "text": "bool a = (CThing* pThing = GetThing()); // not legit!!\n if(A *a = new A)\n{\n // this is legit and a is scoped here\n}\n if((A *a = new A) && a->test())\n{\n // was a really declared before a->test?\n}\n if (CThing* pThing = GetThing())\n{\n if(pThing->IsReallySomeThing())\n {\n }\n}\n" }, { "answer_id": 2103015, "author": "Daniel Daranas", "author_id": 96780, "author_profile": "https://Stackoverflow.com/users/96780", "pm_score": 2, "selected": false, "text": "if (CThing* pThing = GetThing())\n if CThing* CThing* pThing = GetThing();\nif (pThing != NULL)\n" }, { "answer_id": 50222062, "author": "proski", "author_id": 2962407, "author_profile": "https://Stackoverflow.com/users/2962407", "pm_score": 2, "selected": false, "text": "if (CThing thing {})\n{\n}\n operator bool operator bool if (CThing thing {}; thing.is_good())\n{\n}\n {\n CThing thing {};\n if (thing.is_good())\n {\n }\n}\n" }, { "answer_id": 57270774, "author": "Roman2452809", "author_id": 2452809, "author_profile": "https://Stackoverflow.com/users/2452809", "pm_score": 2, "selected": false, "text": "if switch if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())\n{\n // use pThing here\n}\n// pThing is out of scope here\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ]
136,554
<p>I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.</p> <p>Ideas?</p> <pre><code>#!/usr/bin/expect -- spawn $env(SHELL) match_max 100000 set timeout 2 send "echo This will print timed out\r" expect { timeout { puts "timed out at step 1" } "foo " { puts "it said foo at step 1"} } puts "Starting test two\r" send "echo This will not print timed out\r" expect -re { timeout { puts "timed out at step 2" ; exit } "foo " { puts "it said foo at step 2"} } </code></pre>
[ { "answer_id": 136590, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 2, "selected": false, "text": "if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))\n{\n}\n" }, { "answer_id": 136643, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "for(int i = 0; i > 20; i++) {\n // some code\n}\n\ncout << i << endl;\n" }, { "answer_id": 136660, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 0, "selected": false, "text": "{\n CThing *pThing = GetThing();\n if(pThing ? pThing->IsReallySomeThing() : false)\n {\n // Do whatever\n }\n}\n" }, { "answer_id": 136695, "author": "Wesley Tarle", "author_id": 17057, "author_profile": "https://Stackoverflow.com/users/17057", "pm_score": 6, "selected": true, "text": "bool a = (CThing* pThing = GetThing()); // not legit!!\n if(A *a = new A)\n{\n // this is legit and a is scoped here\n}\n if((A *a = new A) && a->test())\n{\n // was a really declared before a->test?\n}\n if (CThing* pThing = GetThing())\n{\n if(pThing->IsReallySomeThing())\n {\n }\n}\n" }, { "answer_id": 2103015, "author": "Daniel Daranas", "author_id": 96780, "author_profile": "https://Stackoverflow.com/users/96780", "pm_score": 2, "selected": false, "text": "if (CThing* pThing = GetThing())\n if CThing* CThing* pThing = GetThing();\nif (pThing != NULL)\n" }, { "answer_id": 50222062, "author": "proski", "author_id": 2962407, "author_profile": "https://Stackoverflow.com/users/2962407", "pm_score": 2, "selected": false, "text": "if (CThing thing {})\n{\n}\n operator bool operator bool if (CThing thing {}; thing.is_good())\n{\n}\n {\n CThing thing {};\n if (thing.is_good())\n {\n }\n}\n" }, { "answer_id": 57270774, "author": "Roman2452809", "author_id": 2452809, "author_profile": "https://Stackoverflow.com/users/2452809", "pm_score": 2, "selected": false, "text": "if switch if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())\n{\n // use pThing here\n}\n// pThing is out of scope here\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10888/" ]
136,580
<p>I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites. </p> <p>I wrote the following code:</p> <pre><code>composite.addListener (SWT.Paint, new Listener () { public void handleEvent (Event e) { GC gc = e.gc; Rectangle rect = composite.getClientArea (); Color color1 = new Color (display, 0, 0, 0); Color color2 = new Color (display, 255, 255, 255); gc.setForeground(color1); gc.setBackground(color2); gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true); } }); </code></pre> <p>This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite. </p> <p>In these areas, the background is just the plain gray you get when drawing an empty canvas. </p> <p>I've tried forcing the Labels to inherit the background like so:</p> <pre><code>label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either </code></pre> <p>But this leaves me with the same default gray and no gradient behind the components on top of the Composite. </p> <p>Any suggestions for getting the gradient to be the background of each element?</p> <p>I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements. </p> <p>Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient. </p> <p>[edit] I uploaded an example upto twitpic <a href="http://twitpic.com/d5qz" rel="nofollow noreferrer">here</a>.</p> <p>Thanks,</p> <p>Brian Gianforcaro</p>
[ { "answer_id": 136668, "author": "qualidafial", "author_id": 13253, "author_profile": "https://Stackoverflow.com/users/13253", "pm_score": -1, "selected": false, "text": "Listener listener = new Listener () {\n public void handleEvent (Event e) {\n GC gc = e.gc;\n Rectangle rect = composite.getClientArea ();\n Point offset = ((Control)e.widget).toControl(composite.toDisplay(0, 0));\n Color color1 = new Color (display, 0, 0, 0);\n Color color2 = new Color (display, 255, 255, 255);\n gc.setForeground(color1);\n gc.setBackground(color2);\n gc.fillGradientRectangle (rect.x + offset.x, rect.y + offset.y,\n rect.width, rect.height , true);\n }\n}\ncomposite.addListener (SWT.Paint, listener);\nlabel.addListener(SWT.Paint, listener);\n" }, { "answer_id": 138693, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "import org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.*;\nimport org.eclipse.swt.layout.*;\nimport org.eclipse.swt.widgets.*;\n\n/**\n * SWT composite with transparent label\n * \n * @author McDowell\n */\npublic class Sweet {\n\n private Image imageGradient;\n private Label label;\n private Composite composite;\n\n private void createComponents(Shell parent) {\n composite = new Composite(parent, SWT.NONE);\n composite.addListener(SWT.Resize, new Listener() {\n public void handleEvent(Event e) {\n changeImage();\n }\n });\n composite.setLayout(new FormLayout());\n composite.setBackgroundMode(SWT.INHERIT_DEFAULT);\n\n label = new Label(composite, SWT.None);\n label.setText(\"Hello, World!\");\n }\n\n private void changeImage() {\n Image oldImage = imageGradient;\n\n Display display = composite.getDisplay();\n Rectangle rect = composite.getClientArea();\n imageGradient = new Image(display, rect.width, rect.height);\n GC gc = new GC(imageGradient);\n try {\n Color color1 = new Color(display, 200, 200, 255);\n try {\n Color color2 = new Color(display, 255, 255, 255);\n try {\n gc.setForeground(color1);\n gc.setBackground(color2);\n gc.fillGradientRectangle(rect.x, rect.y, rect.width,\n rect.height, true);\n } finally {\n color2.dispose();\n }\n } finally {\n color1.dispose();\n }\n } finally {\n gc.dispose();\n }\n composite.setBackgroundImage(imageGradient);\n\n if (oldImage != null) {\n oldImage.dispose();\n }\n }\n\n private void openShell(Display display) {\n Shell shell = new Shell(display);\n try {\n shell.setSize(200, 100);\n shell.setLayout(new FillLayout());\n createComponents(shell);\n shell.open();\n while (!shell.isDisposed()) {\n if (!display.readAndDispatch()) {\n display.sleep();\n }\n }\n } finally {\n if (!shell.isDisposed()) {\n shell.dispose();\n }\n }\n }\n\n public void run() {\n Display display = Display.getDefault();\n try {\n openShell(display);\n } finally {\n display.dispose();\n }\n }\n\n public void dispose() {\n if (imageGradient != null) {\n imageGradient.dispose();\n }\n }\n\n public static void main(String[] args) {\n Sweet sweet = new Sweet();\n try {\n sweet.run();\n } finally {\n sweet.dispose();\n }\n }\n\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
136,581
<p>Is there a way to keep the "Loading..." graphic from appearing when cfdiv refreshes? I'd like to prevent the flicker of loading the graphic then loading the new html.</p>
[ { "answer_id": 140429, "author": "bhinks", "author_id": 5877, "author_profile": "https://Stackoverflow.com/users/5877", "pm_score": 1, "selected": false, "text": "cfdiv cfdiv" }, { "answer_id": 140576, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 3, "selected": true, "text": " <script language=\"JavaScript\"> \n _cf_loadingtexthtml=\"\"; \n </script> \n" }, { "answer_id": 2268563, "author": "freddy v", "author_id": 273779, "author_profile": "https://Stackoverflow.com/users/273779", "pm_score": 0, "selected": false, "text": "function loadingOrder(){\n _cf_loadingtexthtml=\"Loading Order Form <image src='/CFIDE/scripts/ajax/resources/cf/images/loading.gif'>\"; \n}\n\nfunction loadingNavigation(){\n _cf_loadingtexthtml=\"Loading Menu <image src='/CFIDE/scripts/ajax/resources/cf/images/loading_nav.gif'>\"; \n}\n function locateCreateOrder(){\n loadingOrder();\n ColdFusion.navigate('/functional_areas/orders/orders_actions/cf9_act_orders_index.cfm','main_content');\n loadingNavigation();\n ColdFusion.navigate('/functional_areas/products/products_actions/cf9_products_menu.cfm','left_menu');\n}\n" }, { "answer_id": 2386627, "author": "Mohamad", "author_id": 276959, "author_profile": "https://Stackoverflow.com/users/276959", "pm_score": 1, "selected": false, "text": "#TitleNameloadingicon {visibility:hidden;}\n#TitleName_cf_button {visibility:hidden;}\n#TitleNameautosuggest {background-color:#ffffff;}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
136,604
<p>Sorry if the title is poorly descriptive, but I can't do better right now =(</p> <p>So, I have this master-detail scheme, with the detail being a tree structure (one to many self relation) with n levels (on SQLServer 2005)</p> <p>I need to copy a detail structure from one master to the another using a stored procedure, by passing the source master id and the target master id as parameters (the target is new, so it doesn't has details).</p> <p>I'm having troubles, and asking for your kind help in finding a way to keep track of parent id's and inserting the children without using cursors or nasty things like that...</p> <p><img src="https://i.stack.imgur.com/hBzdZ.jpg" alt="table model for the problem"></p> <p>This is a sample model, of course, and what I'm trying to do is to copy the detail structure from one master to other. In fact, I'm creating a new master using an existing one as template.</p>
[ { "answer_id": 137162, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 2, "selected": true, "text": "INSERT dbo.Master VALUES (@NewMaster_ID, @NewDescription)\n\nINSERT dbo.Detail (parent_id, master_id, [name])\nSELECT detail_ID, @NewMaster_ID, [name]\nFROM dbo.Detail \nWHERE master_id = @OldMaster_ID\n\nUPDATE NewChild\nSET parent_id = NewParent.detail_id\nFROM dbo.Detail NewChild\nJOIN dbo.Detail OldChild\nON NewChild.parent_id = OldChild.detail_id\nJOIN dbo.Detail NewParent\nON NewParent.parent_id = OldChild.parent_ID\nWHERE NewChild.master_id = @NewMaster_ID\nAND NewParent.master_id = @NewMaster_ID\nAND OldChild.master_id = @OldMaster_ID\n detail_id parent_id parent_id detail_id" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6359/" ]
136,615
<p>How can I <em>programmatically</em> determine if I have access to a server (TCP) with a given IP address and port using C#?</p>
[ { "answer_id": 136625, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 5, "selected": true, "text": "IPAddress IP;\nif(IPAddress.TryParse(\"127.0.0.1\",out IP)){\n Socket s = new Socket(AddressFamily.InterNetwork,\n SocketType.Stream,\n ProtocolType.Tcp);\n\n try{ \n s.Connect(IPs[0], port);\n }\n catch(Exception ex){\n // something went wrong\n }\n}\n" }, { "answer_id": 136644, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 4, "selected": false, "text": "System.Net.Sockets.TcpClient client = new TcpClient();\ntry\n{\n client.Connect(address, port);\n Console.WriteLine(\"Connection open, host active\");\n} catch (SocketException ex)\n{\n Console.WriteLine(\"Connection could not be established due to: \\n\" + ex.Message);\n}\nfinally\n{\n client.Close();\n}\n" }, { "answer_id": 136648, "author": "Learning", "author_id": 18275, "author_profile": "https://Stackoverflow.com/users/18275", "pm_score": -1, "selected": false, "text": "bool ssl;\nssl = false;\nint maxWaitMillisec;\nmaxWaitMillisec = 20000;\nint port = 555;\n\nsuccess = socket.Connect(\"Your ip address\",port,ssl,maxWaitMillisec);\n\n\nif (success != true) {\n\n MessageBox.Show(socket.LastErrorText);\n return;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
136,617
<p>How do I programmatically force an onchange event on an input?</p> <p>I've tried something like this:</p> <pre><code>var code = ele.getAttribute('onchange'); eval(code); </code></pre> <p>But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.</p>
[ { "answer_id": 136633, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": -1, "selected": false, "text": "$('#elementId').change(function() { alert('Do Stuff'); });\n $addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });\n <input type=\"text\" onchange=\"alert('Do Stuff');\" id=\"myElement\" />\n $addHandler($get('elementId'), 'change', elementChanged);\nfunction elementChanged(){\n alert('Do Stuff!');\n}\nfunction editElement(){\n var el = $get('elementId');\n el.value = 'something new';\n elementChanged();\n}\n $get('elementId')._events\n" }, { "answer_id": 136636, "author": "Kolten", "author_id": 13959, "author_profile": "https://Stackoverflow.com/users/13959", "pm_score": 6, "selected": false, "text": "document.getElementById(\"test\").onchange()\n" }, { "answer_id": 136768, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 2, "selected": false, "text": "function triggerEvent( elem, type, event ) {\n if ( $.browser.mozilla || $.browser.opera ) {\n event = document.createEvent(\"MouseEvents\");\n event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,\n 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n elem.dispatchEvent( event );\n } else if ( $.browser.msie ) {\n elem.fireEvent(\"on\"+type);\n }\n}\n var event;\ntriggerEvent(ele, \"change\", event);\n" }, { "answer_id": 136810, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 5, "selected": false, "text": "function fireEvent(element,event){\n if (document.createEventObject){\n // dispatch for IE\n var evt = document.createEventObject();\n return element.fireEvent('on'+event,evt)\n }\n else{\n // dispatch for firefox + others\n var evt = document.createEvent(\"HTMLEvents\");\n evt.initEvent(event, true, true ); // event type,bubbling,cancelable\n return !element.dispatchEvent(evt);\n }\n}\n <input id=\"test1\" name=\"test1\" value=\"Hello\" onchange=\"alert(this.value);\"/>\n<input type=\"button\" onclick=\"document.getElementById('test1').onchange();\" value=\"Say Hello\"/>\n" }, { "answer_id": 340330, "author": "Danita", "author_id": 26481, "author_profile": "https://Stackoverflow.com/users/26481", "pm_score": 7, "selected": false, "text": "$(\"#element\").trigger(\"change\");\n" }, { "answer_id": 36447918, "author": "STEEL ITBOY", "author_id": 5901075, "author_profile": "https://Stackoverflow.com/users/5901075", "pm_score": -1, "selected": false, "text": "// for the element which uses ID\n$(\"#id\").trigger(\"change\");\n\n// for the element which uses class name\n$(\".class_name\").trigger(\"change\");\n" }, { "answer_id": 36648958, "author": "Miscreant", "author_id": 1851055, "author_profile": "https://Stackoverflow.com/users/1851055", "pm_score": 9, "selected": true, "text": "Event dispatchEvent var element = document.getElementById('just_an_example');\nvar event = new Event('change');\nelement.dispatchEvent(event);\n addEventListener onchange Event var event = new Event('change', { bubbles: true });\n" }, { "answer_id": 52884431, "author": "Peter Lo", "author_id": 10073434, "author_profile": "https://Stackoverflow.com/users/10073434", "pm_score": 2, "selected": false, "text": "var element = document.getElementById('xxxx');\nvar evt = document.createEvent('HTMLEvents');\nevt.initEvent('change', false, true);\nelement.dispatchEvent(evt);\n" }, { "answer_id": 54902366, "author": "Hareesh Seela", "author_id": 10569864, "author_profile": "https://Stackoverflow.com/users/10569864", "pm_score": -1, "selected": false, "text": " document.getElementById(\"yourid\").addEventListener(\"change\", function({\n //your code here\n})\n" }, { "answer_id": 61263659, "author": "Wntiv Senyh", "author_id": 13160456, "author_profile": "https://Stackoverflow.com/users/13160456", "pm_score": 1, "selected": false, "text": "//put this somewhere in your JavaScript:\nHTMLElement.prototype.addEvent = function(event, callback){\n if(!this.events)this.events = {};\n if(!this.events[event]){\n this.events[event] = [];\n var element = this;\n this['on'+event] = function(e){\n var events = element.events[event];\n for(var i=0;i<events.length;i++){\n events[i](e||event);\n }\n }\n }\n this.events[event].push(callback);\n}\n//use like this:\nelement.addEvent('change', function(e){...});\n element.on<EVENTNAME>() <EVENTNAME> <EVENTNAME>" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
136,628
<p>I have a model and two views set up like this:</p> <pre><code>Model ---&gt; OSortFilterProxyModel ---&gt; OListView Model ------------------------------&gt; OTableView </code></pre> <p>When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work?</p>
[ { "answer_id": 7471773, "author": "j_kubik", "author_id": 455304, "author_profile": "https://Stackoverflow.com/users/455304", "pm_score": 1, "selected": false, "text": "tableView->selection()->select(\n proxyModel->mapSelectionToSource(selected),\n QItemSelectionModel::ClearAndSelect);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
136,635
<p>We have a .NET 2.0 application which we normally run on IIS6, and used to run fine on IIS7, but recently after installing SP1 for Vista IIS7 seems to be choking on a line in the Web.Config file:</p> <pre><code>&lt;system.web AllowLocation="true"&gt; </code></pre> <p>Is it safe to remove the AllowLocation attribute? What does this attribute do?</p>
[ { "answer_id": 136676, "author": "ironsam", "author_id": 3539, "author_profile": "https://Stackoverflow.com/users/3539", "pm_score": 0, "selected": false, "text": "<location>" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8432/" ]
136,638
<p>How can I compare the content of two (or more) large .resx files? With hundreds of Name/Value pairs in each file, it'd be very helpful to view a combined version. I'm especially interested in Name/Value pairs which are present in the neutral culture but are not also specified in a culture-specific version.</p>
[ { "answer_id": 186466, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 3, "selected": false, "text": ".resx .resx" }, { "answer_id": 1960701, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 3, "selected": false, "text": ".resx .resx xmldiffpatch.dll XmlDiffPatch.View.dll .resx label1.Size\nlabel1.Location\nlabel1.Width\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360388/" ]
136,642
<p>I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me.</p> <p>Example input:</p> <blockquote> <p>Is this thing on??? or what???</p> </blockquote> <p>Desired output:</p> <blockquote> <p>Is this thing on? or what?</p> </blockquote> <p>I'm using <a href="http://php.net/preg_replace" rel="nofollow noreferrer">preg_replace()</a> in PHP.</p>
[ { "answer_id": 136654, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 4, "selected": true, "text": "preg_replace('{\\?+}', '?', 'Is this thing on??? or what???');\n" }, { "answer_id": 136655, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "preg_replace( '{\\\\?+}', '?', $text );" }, { "answer_id": 136656, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "preg_replace('/\\?+/', '?', $subject);\n" }, { "answer_id": 136664, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "preg_replace('/\\?{2,}/','?',$text)\n" }, { "answer_id": 136684, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 1, "selected": false, "text": "preg_replace('/(\\?+)/m', '?', 'what is going in here????');\n" }, { "answer_id": 136705, "author": "David Lay", "author_id": 6359, "author_profile": "https://Stackoverflow.com/users/6359", "pm_score": 0, "selected": false, "text": "[?]+\n ?" }, { "answer_id": 136916, "author": "powtac", "author_id": 22470, "author_profile": "https://Stackoverflow.com/users/22470", "pm_score": 0, "selected": false, "text": "str_replace('??', '?', 'Replace ??? in this text');\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
136,672
<p>I'd like to log stuff in my Sharepoint Web Parts, but I want it to go into the ULS. Most examples that I've found log into the Event Log or some other file, but I did not really find one yet for logging into the ULS.</p> <p>Annoyingly, Microsoft.SharePoint.Diagnostics Classes are all marked Internal. I did find <a href="http://www.codeplex.com/SharePointOfView/SourceControl/FileView.aspx?itemId=244213&amp;changeSetId=13835" rel="nofollow noreferrer">one example</a> of how to use them anyway through reflection, but that looks really risky and unstable, because Microsoft may change that class with any hotfix they want.</p> <p>The Sharepoint Documentation wasn't really helpful either - lots of Administrator info about what ULS is and how to configure it, but i have yet to find an example of supported code to actually log my own events.</p> <p>Any hints or tips?</p> <p><strong>Edit:</strong> As you may see from the age of this question, this is for SharePoint 2007. In SharePoint 2010, you can use SPDiagnosticsService.Local and then <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spdiagnosticsservicebase.writetrace.aspx" rel="nofollow noreferrer">WriteTrace</a>. See the answer from Jürgen below.</p>
[ { "answer_id": 137836, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 4, "selected": true, "text": "using System;\nusing System.Runtime.InteropServices;\nusing Microsoft.SharePoint.Administration;\n\nnamespace ManagedTraceProvider\n{\nclass Program\n{\n static void Main(string[] args)\n {\n TraceProvider.RegisterTraceProvider();\n\n TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.High, Guid.Empty, \"MyExeName\", \"Product Name\", \"Category Name\", \"Sample Message\");\n TraceProvider.WriteTrace(TraceProvider.TagFromString(\"abcd\"), TraceProvider.TraceSeverity.Monitorable, Guid.NewGuid(), \"MyExeName\", \"Product Name\", \"Category Name\", \"Sample Message\");\n\n TraceProvider.UnregisterTraceProvider();\n }\n}\n\nstatic class TraceProvider\n{\n static UInt64 hTraceLog;\n static UInt64 hTraceReg;\n\n static class NativeMethods\n {\n internal const int TRACE_VERSION_CURRENT = 1;\n internal const int ERROR_SUCCESS = 0;\n internal const int ERROR_INVALID_PARAMETER = 87;\n internal const int WNODE_FLAG_TRACED_GUID = 0x00020000;\n\n internal enum TraceFlags\n {\n TRACE_FLAG_START = 1,\n TRACE_FLAG_END = 2,\n TRACE_FLAG_MIDDLE = 3,\n TRACE_FLAG_ID_AS_ASCII = 4\n }\n\n // Copied from Win32 APIs\n [StructLayout(LayoutKind.Sequential)]\n internal struct EVENT_TRACE_HEADER_CLASS\n {\n internal byte Type;\n internal byte Level;\n internal ushort Version;\n }\n\n // Copied from Win32 APIs\n [StructLayout(LayoutKind.Sequential)]\n internal struct EVENT_TRACE_HEADER\n {\n internal ushort Size;\n internal ushort FieldTypeFlags;\n internal EVENT_TRACE_HEADER_CLASS Class;\n internal uint ThreadId;\n internal uint ProcessId;\n internal Int64 TimeStamp;\n internal Guid Guid;\n internal uint ClientContext;\n internal uint Flags;\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n internal struct ULSTraceHeader\n {\n internal ushort Size;\n internal uint dwVersion;\n internal uint Id;\n internal Guid correlationID;\n internal TraceFlags dwFlags;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n internal string wzExeName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n internal string wzProduct;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n internal string wzCategory;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 800)]\n internal string wzMessage;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct ULSTrace\n {\n internal EVENT_TRACE_HEADER Header;\n internal ULSTraceHeader ULSHeader;\n }\n\n // Copied from Win32 APIs\n internal enum WMIDPREQUESTCODE\n {\n WMI_GET_ALL_DATA = 0,\n WMI_GET_SINGLE_INSTANCE = 1,\n WMI_SET_SINGLE_INSTANCE = 2,\n WMI_SET_SINGLE_ITEM = 3,\n WMI_ENABLE_EVENTS = 4,\n WMI_DISABLE_EVENTS = 5,\n WMI_ENABLE_COLLECTION = 6,\n WMI_DISABLE_COLLECTION = 7,\n WMI_REGINFO = 8,\n WMI_EXECUTE_METHOD = 9\n }\n\n // Copied from Win32 APIs\n internal unsafe delegate uint EtwProc(NativeMethods.WMIDPREQUESTCODE requestCode, IntPtr requestContext, uint* bufferSize, IntPtr buffer);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode)]\n internal static extern unsafe uint RegisterTraceGuids([In] EtwProc cbFunc, [In] void* context, [In] ref Guid controlGuid, [In] uint guidCount, IntPtr guidReg, [In] string mofImagePath, [In] string mofResourceName, out ulong regHandle);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode)]\n internal static extern uint UnregisterTraceGuids([In]ulong regHandle);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode)]\n internal static extern UInt64 GetTraceLoggerHandle([In]IntPtr Buffer);\n\n // Copied from Win32 APIs\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n internal static extern uint TraceEvent([In]UInt64 traceHandle, [In]ref ULSTrace evnt);\n }\n\n public enum TraceSeverity\n {\n Unassigned = 0,\n CriticalEvent = 1,\n WarningEvent = 2,\n InformationEvent = 3,\n Exception = 4,\n Assert = 7,\n Unexpected = 10,\n Monitorable = 15,\n High = 20,\n Medium = 50,\n Verbose = 100,\n }\n\n public static void WriteTrace(uint tag, TraceSeverity level, Guid correlationGuid, string exeName, string productName, string categoryName, string message)\n {\n const ushort sizeOfWCHAR = 2;\n NativeMethods.ULSTrace ulsTrace = new NativeMethods.ULSTrace();\n\n // Pretty standard code needed to make things work\n ulsTrace.Header.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTrace));\n ulsTrace.Header.Flags = NativeMethods.WNODE_FLAG_TRACED_GUID;\n ulsTrace.ULSHeader.dwVersion = NativeMethods.TRACE_VERSION_CURRENT;\n ulsTrace.ULSHeader.dwFlags = NativeMethods.TraceFlags.TRACE_FLAG_ID_AS_ASCII;\n ulsTrace.ULSHeader.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTraceHeader));\n\n // Variables communicated to SPTrace\n ulsTrace.ULSHeader.Id = tag;\n ulsTrace.Header.Class.Level = (byte)level;\n ulsTrace.ULSHeader.wzExeName = exeName;\n ulsTrace.ULSHeader.wzProduct = productName;\n ulsTrace.ULSHeader.wzCategory = categoryName;\n ulsTrace.ULSHeader.wzMessage = message;\n ulsTrace.ULSHeader.correlationID = correlationGuid;\n\n // Pptionally, to improve performance by reducing the amount of data copied around,\n // the Size parameters can be reduced by the amount of unused buffer in the Message\n if (message.Length < 800)\n {\n ushort unusedBuffer = (ushort) ((800 - (message.Length + 1)) * sizeOfWCHAR);\n ulsTrace.Header.Size -= unusedBuffer;\n ulsTrace.ULSHeader.Size -= unusedBuffer;\n }\n\n if (hTraceLog != 0)\n NativeMethods.TraceEvent(hTraceLog, ref ulsTrace);\n }\n\n public static unsafe void RegisterTraceProvider()\n {\n SPFarm farm = SPFarm.Local;\n Guid traceGuid = farm.TraceSessionGuid;\n uint result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPtr.Zero, null, null, out hTraceReg);\n System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);\n }\n\n public static void UnregisterTraceProvider()\n {\n uint result = NativeMethods.UnregisterTraceGuids(hTraceReg);\n System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);\n }\n\n public static uint TagFromString(string wzTag)\n {\n System.Diagnostics.Debug.Assert(wzTag.Length == 4);\n return (uint) (wzTag[0] << 24 | wzTag[1] << 16 | wzTag[2] << 8 | wzTag[3]);\n }\n\n static unsafe uint ControlCallback(NativeMethods.WMIDPREQUESTCODE RequestCode, IntPtr Context, uint* InOutBufferSize, IntPtr Buffer)\n {\n uint Status;\n switch (RequestCode)\n {\n case NativeMethods.WMIDPREQUESTCODE.WMI_ENABLE_EVENTS:\n hTraceLog = NativeMethods.GetTraceLoggerHandle(Buffer);\n Status = NativeMethods.ERROR_SUCCESS;\n break;\n case NativeMethods.WMIDPREQUESTCODE.WMI_DISABLE_EVENTS:\n hTraceLog = 0;\n Status = NativeMethods.ERROR_SUCCESS;\n break;\n default:\n Status = NativeMethods.ERROR_INVALID_PARAMETER;\n break;\n }\n\n *InOutBufferSize = 0;\n return Status;\n }\n}\n" }, { "answer_id": 17389756, "author": "Amit Bhagat", "author_id": 836551, "author_profile": "https://Stackoverflow.com/users/836551", "pm_score": 2, "selected": false, "text": "private const string PRODUCT_NAME = \"My Custom Solution\";\n UlsLogging.LogInformation(\"This is information message\");\nUlsLogging.LogInformation(\"{0}This is information message\",\"Information:\"); \n\nUlsLogging.LogWarning(\"This is warning message\");\nUlsLogging.LogWarning(\"{0}This is warning message\", \"Warning:\"); \n\nUlsLogging.LogError(\"This is error message\");\nUlsLogging.LogError(\"{0}This is error message\",\"Error:\"); \n using System;\nusing System.Collections.Generic;\nusing Microsoft.SharePoint.Administration;\nnamespace MyLoggingApp\n{\n public class UlsLogging : SPDiagnosticsServiceBase\n {\n // Product name\n private const string PRODUCT_NAME = \"My Custom Solution\";\n\n #region private variables\n\n // Current instance\n private static UlsLogging _current;\n\n // area\n private static SPDiagnosticsArea _area;\n\n // category\n private static SPDiagnosticsCategory _catError;\n private static SPDiagnosticsCategory _catWarning;\n private static SPDiagnosticsCategory _catLogging;\n\n #endregion\n\n private static class CategoryName\n {\n public const string Error = \"Error\";\n public const string Warning = \"Warning\";\n public const string Logging = \"Logging\";\n }\n\n private static UlsLogging Current\n {\n get\n {\n if (_current == null)\n {\n _current = new UlsLogging();\n }\n return _current;\n }\n }\n\n // Get Area\n private static SPDiagnosticsArea Area\n {\n get\n {\n if (_area == null)\n {\n _area = UlsLogging.Current.Areas[PRODUCT_NAME];\n }\n return _area;\n }\n }\n\n // Get error category\n private static SPDiagnosticsCategory CategoryError\n {\n get\n {\n if (_catError == null)\n {\n _catError = Area.Categories[CategoryName.Error];\n }\n return _catError;\n }\n }\n\n // Get warning category\n private static SPDiagnosticsCategory CategoryWarning\n {\n get\n {\n if (_catWarning == null)\n {\n _catWarning = Area.Categories[CategoryName.Warning];\n }\n return _catWarning;\n }\n }\n\n // Get logging category\n private static SPDiagnosticsCategory CategoryLogging\n {\n get\n {\n if (_catLogging == null)\n {\n _catLogging = Area.Categories[CategoryName.Logging];\n }\n return _catLogging;\n }\n }\n\n private UlsLogging()\n : base(PRODUCT_NAME, SPFarm.Local)\n {\n }\n\n protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()\n {\n var cat = new List<SPDiagnosticsCategory>{\n new SPDiagnosticsCategory(CategoryName.Error, TraceSeverity.High,EventSeverity.Error),\n new SPDiagnosticsCategory(CategoryName.Warning, TraceSeverity.Medium,EventSeverity.Warning),\n new SPDiagnosticsCategory(CategoryName.Logging,TraceSeverity.Verbose,EventSeverity.Information)\n };\n var areas = new List<SPDiagnosticsArea>();\n areas.Add(new SPDiagnosticsArea(PRODUCT_NAME, cat));\n\n return areas;\n }\n\n // Log Error\n public static void LogError(string msg)\n {\n UlsLogging.Current.WriteTrace(0, CategoryError, TraceSeverity.High, msg);\n }\n public static void LogError(string msg,params object[] args)\n {\n UlsLogging.Current.WriteTrace(0, CategoryError, TraceSeverity.High, msg,args);\n }\n\n // Log Warning\n public static void LogWarning(string msg)\n {\n UlsLogging.Current.WriteTrace(0, CategoryWarning, TraceSeverity.Medium, msg);\n }\n public static void LogWarning(string msg, params object[] args)\n {\n UlsLogging.Current.WriteTrace(0, CategoryWarning, TraceSeverity.Medium, msg,args);\n }\n\n // Log Information\n public static void LogInformation(string msg)\n {\n UlsLogging.Current.WriteTrace(0, CategoryLogging, TraceSeverity.Verbose, msg); \n }\n public static void LogInformation(string msg,params object[] args)\n {\n UlsLogging.Current.WriteTrace(0, CategoryLogging, TraceSeverity.Verbose, msg,args);\n }\n\n }\n}\n" }, { "answer_id": 23607513, "author": "Vikas Kottari", "author_id": 2757125, "author_profile": "https://Stackoverflow.com/users/2757125", "pm_score": 1, "selected": false, "text": "try\n {\n\n SPSecurity.RunWithElevatedPrivileges(delegate()\n {\n SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;\n diagSvc.WriteTrace(123456, new SPDiagnosticsCategory(\"Category_Name_Here\", TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable, \"{0}:{1}\", new object[] { \"Method_Name\", \"Error_Message\"});\n });\n }\n catch (Exception ex)\n {\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
136,674
<p>I'm looking for a few talking points I could use to convince coworkers that it's NOT OK to run a 24/7 production application by simply opening Visual Studio and running the app in debug mode.</p> <p>What's different about running a compiled console application vs. running that same app in debug mode? </p> <p>Are there ever times when you would use the debugger in a live setting? (live: meaning connected to customer facing databases)</p> <p>Am I wrong in assuming that it's always a bad idea to run a live configuration via the debugger? </p>
[ { "answer_id": 136882, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "#ifdef, Debug.Assert(), etc" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19389/" ]
136,682
<p>I've got a code like this : </p> <pre><code>Dim Document As New mshtml.HTMLDocument Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2) iDoc.write(html) iDoc.close() </code></pre> <p>However when I load an HTML like this it executes all Javascripts in it as well as doing request to some resources from "html" code.</p> <p>I want to disable javascript and all other popups (such as certificate error).</p> <p>My aim is to use DOM from mshtml document to extract some tags from the HTML in a reliable way (instead of bunch of regexes). </p> <p>Or is there another IE/Office DLL which I can just load an HTML wihtout thinking about IE related popups or active scripts?</p>
[ { "answer_id": 139224, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": " if(typeof(DOMParser) == 'undefined') {\n DOMParser = function() {}\n DOMParser.prototype.parseFromString = function(str, contentType) {\n if(typeof(ActiveXObject) != 'undefined') {\n var xmldata = new ActiveXObject('MSXML.DomDocument');\n xmldata.async = false;\n xmldata.loadXML(str);\n return xmldata;\n } else if(typeof(XMLHttpRequest) != 'undefined') {\n var xmldata = new XMLHttpRequest;\n if(!contentType) {\n contentType = 'application/xml';\n }\n xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);\n if(xmldata.overrideMimeType) {\n xmldata.overrideMimeType(contentType);\n }\n xmldata.send(null);\n return xmldata.responseXML;\n }\n }\n}\n" }, { "answer_id": 1031463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "Dim Document As New mshtml.HTMLDocument\nDim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2)\n'add this code\niDoc.designMode=\"On\"\niDoc.write(html)iDoc.close()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
136,696
<p>I have a Hashtable&lt;Integer, Sport> called sportMap and a list of sportIds (List&lt;Integer> sportIds) from my backing bean. The Sport object has a List&lt;String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport?</p> <pre><code>&lt;h:dataTable value="#{bean.sportIds}" var="_sportId" &gt; &lt;c:forEach items="#{bean.sportMap[_sportId].equipmentList}" var="_eqp"&gt; &lt;h:outputText value="#{_eqp}"&gt;&lt;/h:outputText&gt; &lt;br/&gt; &lt;/c:forEach&gt; &lt;/h:dataTable&gt; </code></pre> <p>I get the following exception when trying to run this JSP code.</p> <pre> 15:57:59,438 ERROR [ExceptionFilter] exception root cause javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in &amp;lt;forEach&amp;gt;</pre> <p>Here's a print out of my environment</p> <pre> Server: JBossWeb/2.0.1.GA Servlet Specification: 2.5 JSP version: 2.1 JSTL version: 1.2 Java Version: 1.5.0_14 </pre> <p>Note: The following does work using a JSF tag. It prints out the list of equipment for each sport specified in the list of sportIds. </p> <pre><code>&lt;h:dataTable value="#{bean.sportIds}" var="_sportId" &gt; &lt;h:outputText value="#{bean.sportMap[_sportId].equipmentList}"&gt; &lt;/h:outputText&gt; &lt;/h:dataTable&gt; </code></pre> <p>I would like to use the c:forEach tag. Does anyone know if this is possible? If not, anyone have suggestions? In the end I want a stacked list instead of the comma seperated list provided by equipmentList.toString(); (Also, don't want to override toString()).</p>
[ { "answer_id": 287013, "author": "alexmeia", "author_id": 36587, "author_profile": "https://Stackoverflow.com/users/36587", "pm_score": 2, "selected": false, "text": "<h:dataTable value=\"#{bean.sportIds}\" var=\"_sportId\" > \n <h:dataTable value=\"#{bean.sportMap[_sportId].equipmentList}\" var=\"_eqp\">\n <h:outputText value=\"#{_eqp}\"></h:outputText>\n </h:dataTable>\n</h:dataTable>\n <table>\n <c:forEach items=\"#{bean.sportIds}\" var=\"_sportId\">\n <tr>\n <td>\n <c:forEach items=\"#{bean.sportMap[_sportId].equipmentList\" var=\"_eqp\">\n <h:outputText value=\"#{_eqp} \" />\n </c:forEach>\n </td>\n </tr>\n </c:forEach>\n</table>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
136,703
<p>I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.</p> <p>Equivalent of this if you know Cocoa:</p> <pre><code>NSString *string = [NSString stringWithContentsOfFile:file]; </code></pre>
[ { "answer_id": 136743, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "#include <fstream>\n#include <vector>\nusing namespace std;\n\nifstream f(\"filename.txt\");\nf.seekg(0, ios::end);\nvector<char> buffer(f.tellg());\nf.seekg(0, ios::beg);\nf.read(&buffer[0], buffer.size());\n" }, { "answer_id": 136748, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 4, "selected": false, "text": "#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <string>\n#include <sstream>\n\nusing namespace std;\n\nint main()\n{\n ifstream file(\"filename.txt\");\n string fileContents;\n\n copy(istreambuf_iterator<char>(file),\n istreambuf_iterator<char>(),\n back_inserter(fileContents));\n}\n" }, { "answer_id": 136883, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 2, "selected": false, "text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nint main( void )\n{\n stringstream os(stringstream::out);\n os << ifstream(\"filename.txt\").rdbuf();\n string s(os.str());\n cout << s << endl;\n}\n" }, { "answer_id": 137086, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 0, "selected": false, "text": "\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstdlib>\nusing namespace std;\n\nint main() {\n FILE* in = fopen(\"filename.txt\", \"rb\");\n if (in == NULL) {\n return EXIT_FAILURE;\n }\n if (fseek(in, 0, SEEK_END) != 0) {\n fclose(in);\n return EXIT_FAILURE;\n }\n const long filesize = ftell(in);\n if (filesize == -1) {\n fclose(in);\n return EXIT_FAILURE;\n }\n vector<unsigned char> buffer(filesize);\n if (fseek(in, 0, SEEK_SET) != 0 || fread(&buffer[0], sizeof(buffer[0]), buffer.size(), in) != buffer.size() || ferror(in) != 0) {\n fclose(in);\n return EXIT_FAILURE;\n }\n fclose(in);\n}\n" }, { "answer_id": 137117, "author": "Rexxar", "author_id": 10016, "author_profile": "https://Stackoverflow.com/users/10016", "pm_score": 5, "selected": true, "text": "#include<fstream>\n#include<iostream>\n#include<iterator>\n#include<string>\n\nusing namespace std;\n\nint main()\n{\n // The one-liner\n string fileContents(istreambuf_iterator<char>(ifstream(\"filename.txt\")), istreambuf_iterator<char>());\n\n // Check result\n cout << fileContents;\n}\n" }, { "answer_id": 3599675, "author": "Puppy", "author_id": 298661, "author_profile": "https://Stackoverflow.com/users/298661", "pm_score": 0, "selected": false, "text": "std::string temp, file; std::ifstream if(filename); while(getline(if, temp)) file += temp;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
136,727
<p>From my understanding of the CSS spec, a table above or below a paragraph should collapse vertical margins with it. However, that's not happening here:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { margin: 100px; border: solid red 2px; } p { margin: 100px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; This is a one-celled table with 100px margin all around. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt;This is a paragraph with 100px margin all around.&lt;/p&gt;</code></pre> </div> </div> </p> <p>I thought there would be 100px between the two elements, but there are 200px -- the margins aren't collapsing. </p> <p>Why not?</p> <p><strong>Edit:</strong> It appears to be the table's fault: if I duplicate the table and duplicate the paragraph, the two paragraphs will collapse margins. The two tables won't. And, as noted above, a table won't collapse margins with a paragraph. Is this compliant behaviour?</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { margin: 100px; border: solid red 2px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; This is a one-celled table with 100px margin all around. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; This is a one-celled table with 100px margin all around. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>p { margin: 100px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; &lt;p&gt;This is a paragraph with 100px margin all around.&lt;/p&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 136816, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "display: block table" }, { "answer_id": 136873, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "display: block display: table" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
136,734
<p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p> <p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p> <p>More Info (as requested): I am running windows XP and need to send the keys to another application.</p>
[ { "answer_id": 136759, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 4, "selected": false, "text": "Send {A 100}\n WinActivate Word\nSend {A 100}\n" }, { "answer_id": 136780, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 7, "selected": true, "text": "import win32com.client as comclt\nwsh= comclt.Dispatch(\"WScript.Shell\")\nwsh.AppActivate(\"Notepad\") # select another application\nwsh.SendKeys(\"a\") # send the keys you want\n import win32com.client as comctl\nwsh = comctl.Dispatch(\"WScript.Shell\")\n\n# Google Chrome window title\nwsh.AppActivate(\"icanhazip.com\")\nwsh.SendKeys(\"{F11}\")\n" }, { "answer_id": 1282600, "author": "wearetherock", "author_id": 103583, "author_profile": "https://Stackoverflow.com/users/103583", "pm_score": 2, "selected": false, "text": "hwnd = win32gui.FindWindowEx(0,0,0, \"App title\")\nwin32gui.SetForegroundWindow(hwnd)\n" }, { "answer_id": 33249229, "author": "Malachi Bazar", "author_id": 5231348, "author_profile": "https://Stackoverflow.com/users/5231348", "pm_score": 6, "selected": false, "text": "import pyautogui\n\n\npyautogui.press('Any key combination')\n import pyautogui\n\npyautogui.press('shift')\n import pyautogui\n\npyautogui.typewrite('any text you want to type')\n import pyautogui\n\nfor i in range(999):\n pyautogui.press(\"a\")\n import pyautogui\n\n# Holds down the alt key\npyautogui.keyDown(\"alt\")\n\n# Presses the tab key once\npyautogui.press(\"tab\")\n\n# Lets go of the alt key\npyautogui.keyUp(\"alt\")\n" }, { "answer_id": 44757414, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "pip3 install keyboard\n import keyboard\nkeyboard.write('A',delay=0)\n" }, { "answer_id": 60276594, "author": "jeppoo1", "author_id": 11786575, "author_profile": "https://Stackoverflow.com/users/11786575", "pm_score": 2, "selected": false, "text": "pyautogui.press('tab', presses=5) # press TAB five times in a row\n\npyautogui.press('A', presses=1000) # press A a thousand times in a row\n" }, { "answer_id": 65262817, "author": "jack chyna", "author_id": 14739439, "author_profile": "https://Stackoverflow.com/users/14739439", "pm_score": 2, "selected": false, "text": "import keyboard\n\nkeyboard.press_and_release('anykey')\n" }, { "answer_id": 66243541, "author": "user15105779", "author_id": 15105779, "author_profile": "https://Stackoverflow.com/users/15105779", "pm_score": 1, "selected": false, "text": "import pyautogui\nfor i in range(1000):\n pyautogui.typewrite(\"a\")\n" }, { "answer_id": 68592343, "author": "TheCodeExpert", "author_id": 16108971, "author_profile": "https://Stackoverflow.com/users/16108971", "pm_score": 0, "selected": false, "text": "import pyautogui \nloop = 1\nwhile loop <= 1000: \n pyautogui.press(\"a\")\n loop += 1\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
136,739
<p>I'm starting with Python coming from java. </p> <p>I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it.</p> <p>I've found very helpul to use <em>help( thing )</em> from the Python ( command line ) </p> <p>I have found this also:</p> <p><a href="http://docs.python.org/2/" rel="nofollow noreferrer">http://docs.python.org/2/</a></p> <p><a href="https://docs.python.org/2/py-modindex.html" rel="nofollow noreferrer">https://docs.python.org/2/py-modindex.html</a></p> <p>But it seems to help when you already have the class name you are looking for. In JavaDoc API I have all the classes so if I need something I scroll down to a class that "sounds like" what I need. Or some times I just browse all the classes to see what they do, and when I need a feature my brain recalls me <em>We saw something similar in the javadoc remember!?</em> </p> <p>But I don't seem to find the similar in Python ( yet ) and that why I'm posting this questin. </p> <p>BTW I know that I would eventually will read this:</p> <p><a href="https://docs.python.org/2/library/" rel="nofollow noreferrer">https://docs.python.org/2/library/</a></p> <p>But, well, I think it is not today.</p>
[ { "answer_id": 136783, "author": "apg", "author_id": 22277, "author_profile": "https://Stackoverflow.com/users/22277", "pm_score": 2, "selected": false, "text": "import os \nhelp(os)\n" }, { "answer_id": 136929, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "Directorio de C:\\Python25\n\n9/23/2008 10:45 PM <DIR> .\n9/23/2008 10:45 PM <DIR> ..\n9/23/2008 10:45 PM <DIR> DLLs\n9/23/2008 10:45 PM <DIR> Doc\n9/23/2008 10:45 PM <DIR> include\n9/25/2008 06:34 PM <DIR> Lib\n9/23/2008 10:45 PM <DIR> libs\n2/21/2008 01:05 PM 14,013 LICENSE.txt\n2/21/2008 01:05 PM 119,048 NEWS.txt\n2/21/2008 01:11 PM 24,064 python.exe\n2/21/2008 01:12 PM 24,576 pythonw.exe\n2/21/2008 01:05 PM 56,354 README.txt\n9/23/2008 10:45 PM <DIR> tcl\n9/23/2008 10:45 PM <DIR> Tools\n2/21/2008 01:11 PM 4,608 w9xpopen.exe\n 6 archivos 242,663 bytes\n C:\\Python25>dir Tools\\Scripts\\pydocgui.pyw\n\n10/28/2005 07:06 PM 222 pydocgui.pyw\n 1 archivos 222 bytes\n" }, { "answer_id": 138240, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 1, "selected": false, "text": ">>> help(Exception)\n>>> Help on class Exception in module exceptions:\n\n>>> class Exception(BaseException)\n>>> | Common base class for all non-exit exceptions.\n>>> | \n>>> | Method resolution order:\n>>> | Exception\n" }, { "answer_id": 138317, "author": "Sergey Stolyarov", "author_id": 15958, "author_profile": "https://Stackoverflow.com/users/15958", "pm_score": 0, "selected": false, "text": "pydoc -p 11111\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
136,752
<p>I have a C++ tool that walks the call stack at one point. In the code, it first gets a copy of the live CPU registers (via RtlCaptureContext()), then uses a few "<code>#ifdef ...</code>" blocks to save the CPU-specific register names into <code>stackframe.AddrPC.Offset</code>, ...<code>AddrStack</code>..., and ...<code>AddrFrame</code>...; also, for each of the 3 <code>Addr</code>... members above, it sets <code>stackframe.Addr</code>...<code>.Mode = AddrModeFlat</code>. (This was borrowed from some example code I came across a while back.)</p> <p>With an x86 binary, this works great. With an x64 binary, though, StackWalk64() passes back bogus addresses. <i>(The first time the API is called, the only blatantly bogus address value appears in <code>AddrReturn</code> ( == <code>0xFFFFFFFF'FFFFFFFE</code> -- aka StackWalk64()'s 3rd arg, the pseudo-handle returned by GetCurrentThread()). If the API is called a second time, however, all <code>Addr</code>... variables receive bogus addresses.)</i> This happens regardless of how <code>AddrFrame</code> is set:</p> <ul> <li>using either of the recommended x64 "base/frame pointer" CPU registers: <code>rbp</code> (= <code>0xf</code>), or <code>rdi</code> (= <code>0x0</code>)</li> <li>using <code>rsp</code> <i>(didn't expect it to work, but tried it anyway)</i></li> <li>setting <code>AddrPC</code> and <code>AddrStack</code> normally, but leaving <code>AddrFrame</code> zeroed out <i>(seen in other example code)</i></li> <li>zeroing out all <code>Addr</code>... values, to let StackWalk64() fill them in from the passed-in CPU-register context <i>(seen in other example code)</i></li> </ul> <p>FWIW, the physical stack buffer's contents are also different on x64 vs. x86 (after accounting for different pointer widths &amp; stack buffer locations, of course). Regardless of the reason, StackWalk64() should still be able to walk the call stack correctly -- heck, the debugger is still able to walk the call stack, and it appears to use StackWalk64() itself behind the scenes. The oddity there is that the (correct) call stack reported by the debugger contains base-address &amp; return-address pointer values whose constituent bytes don't actually exist in the stack buffer (below or above the current stack pointer).</p> <p><i>(FWIW #2: Given the stack-buffer strangeness above, I did try disabling ASLR (<code>/dynamicbase:no</code>) to see if it made a difference, but the binary still exhibited the same behavior.)</i></p> <p>So. Any ideas why this would work fine on x86, but have problems on x64? Any suggestions on how to fix it?</p>
[ { "answer_id": 136942, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": " DWORD machine = IMAGE_FILE_MACHINE_AMD64;\n RtlCaptureContext (&c);\n fs.sf.AddrPC.Offset = c.Rip;\n fs.sf.AddrFrame.Offset = c.Rsp;\n fs.sf.AddrStack.Offset = c.Rsp;\n fs.sf.AddrPC.Mode = AddrModeFlat;\n fs.sf.AddrFrame.Mode = AddrModeFlat;\n fs.sf.AddrStack.Mode = AddrModeFlat;\n" }, { "answer_id": 159851, "author": "Quasidart", "author_id": 19505, "author_profile": "https://Stackoverflow.com/users/19505", "pm_score": 1, "selected": false, "text": "CaptureStackBackTrace()" }, { "answer_id": 63977654, "author": "catalin", "author_id": 3636621, "author_profile": "https://Stackoverflow.com/users/3636621", "pm_score": 2, "selected": false, "text": "SymInitialize(process, nullptr, TRUE) StackWalk64()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19505/" ]
136,771
<p>How can I drop sql server agent jobs, if (and only if) it exists?</p> <p>This is a well functioning script for <em>stored procedures</em>. How can I do the same to sql server agent jobs?</p> <pre><code>if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[storedproc] GO CREATE PROCEDURE [dbo].[storedproc] ... </code></pre>
[ { "answer_id": 137159, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 8, "selected": true, "text": "DECLARE @jobId binary(16)\n\nSELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')\nIF (@jobId IS NOT NULL)\nBEGIN\n EXEC msdb.dbo.sp_delete_job @jobId\nEND\n\nDECLARE @ReturnCode int\nEXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job'\n" }, { "answer_id": 138613, "author": "Andy Jones", "author_id": 5096, "author_profile": "https://Stackoverflow.com/users/5096", "pm_score": 2, "selected": false, "text": "DECLARE @JobID BINARY(16) \nDECLARE @ReturnCode INT \nSELECT @ReturnCode = 0 \n-- Delete the job with the same name (if it exists) \nSELECT @JobID = job_id \nFROM msdb.dbo.sysjobs \nWHERE (name = N'My test job') \nIF (@JobID IS NOT NULL) \nBEGIN \n-- Check if the job is a multi-server job \nIF (EXISTS (SELECT * \nFROM msdb.dbo.sysjobservers \nWHERE (job_id = @JobID) AND (server_id <> 0))) \nBEGIN \n-- There is, so abort the script \nRAISERROR (N'Unable to import job ''My test job'' since there is already a multi-server job with this name.', 16, 1) \nEND \nELSE \n-- Delete the [local] job \nEXECUTE msdb.dbo.sp_delete_job @job_name = N'My test job' \nSELECT @JobID = NULL \nEND \n" }, { "answer_id": 10598289, "author": "Seshu", "author_id": 1395830, "author_profile": "https://Stackoverflow.com/users/1395830", "pm_score": 5, "selected": false, "text": "IF EXISTS (SELECT job_id \n FROM msdb.dbo.sysjobs_view \n WHERE name = N'Your Job Name')\nEXEC msdb.dbo.sp_delete_job @job_name=N'Your Job Name'\n , @delete_unused_schedule=1\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
136,782
<p>I have a <code>datetime</code> column in MySQL. </p> <p>How can I convert it to the display as <strong>mm/dd/yy H:M (AM/PM)</strong> using PHP?</p>
[ { "answer_id": 136802, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 3, "selected": false, "text": "<?php\n echo date(\"m/d/y g:i (A)\", $DB_Date_Field);\n?>\n" }, { "answer_id": 136872, "author": "Tim Boland", "author_id": 70, "author_profile": "https://Stackoverflow.com/users/70", "pm_score": 8, "selected": false, "text": "mm/dd/yy H:M (AM/PM) // $datetime is something like: 2014-01-31 13:05:59\n$time = strtotime($datetimeFromMysql);\n$myFormatForView = date(\"m/d/y g:i A\", $time);\n// $myFormatForView is something like: 01/31/14 1:05 PM\n" }, { "answer_id": 136989, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 2, "selected": false, "text": "strtotime() select UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;\n date() <?php\n echo date('l jS \\of F Y h:i:s A', $row->unixtime);\n?>\n <?php\n echo date('F j, Y, g:i a', $row->unixtime);\n?>\n DATE_FORMAT" }, { "answer_id": 137780, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 7, "selected": false, "text": "$oDate = new DateTime($row->createdate);\n$sDate = $oDate->format(\"Y-m-d H:i:s\");\n" }, { "answer_id": 1776427, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$oDate = strtotime($row['PubDate']);\n$sDate = date(\"m/d/y\",$oDate);\necho $sDate\n PubDate" }, { "answer_id": 2695713, "author": "matt.j.crawford", "author_id": 2384400, "author_profile": "https://Stackoverflow.com/users/2384400", "pm_score": 1, "selected": false, "text": "return date(\"F j, Y g:i a\", strtotime(substr($datestring, 0, 15)))\n" }, { "answer_id": 5367048, "author": "kta", "author_id": 539023, "author_profile": "https://Stackoverflow.com/users/539023", "pm_score": 10, "selected": true, "text": "$phpdate = strtotime( $mysqldate );\n$mysqldate = date( 'Y-m-d H:i:s', $phpdate );\n $phpdate = strtotime( $mysqldate ) $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) date" }, { "answer_id": 8056448, "author": "riz", "author_id": 1036374, "author_profile": "https://Stackoverflow.com/users/1036374", "pm_score": 3, "selected": false, "text": "SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename\n" }, { "answer_id": 12421182, "author": "nixis", "author_id": 876093, "author_profile": "https://Stackoverflow.com/users/876093", "pm_score": 3, "selected": false, "text": "$date = date(\"Y-m-d H:i:s\",strtotime(str_replace('/','-',$date)))\n" }, { "answer_id": 15158450, "author": "Tony Stark", "author_id": 718224, "author_profile": "https://Stackoverflow.com/users/718224", "pm_score": 6, "selected": false, "text": "$valid_date = date( 'm/d/y g:i A', strtotime($date));\n" }, { "answer_id": 16862942, "author": "Greg", "author_id": 431780, "author_profile": "https://Stackoverflow.com/users/431780", "pm_score": 3, "selected": false, "text": "DateTime $dtNow = new DateTime();\n$mysqlDateTime = $dtNow->format(DateTime::ISO8601);\n" }, { "answer_id": 20328996, "author": "SagarPPanchal", "author_id": 2351167, "author_profile": "https://Stackoverflow.com/users/2351167", "pm_score": -1, "selected": false, "text": "$date = \"'\".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date']))).\"'\";\n" }, { "answer_id": 21317972, "author": "tfont", "author_id": 1804013, "author_profile": "https://Stackoverflow.com/users/1804013", "pm_score": 3, "selected": false, "text": "function datetime()\n{\n return date( 'Y-m-d H:i:s', time());\n}\n\necho datetime(); // display example: 2011-12-31 07:55:13\n function datetime($date_string = false)\n{\n if (!$date_string)\n {\n $date_string = time();\n }\n return date(\"Y-m-d H:i:s\", strtotime($date_string));\n}\n" }, { "answer_id": 22343357, "author": "Mihir Vadalia", "author_id": 2702490, "author_profile": "https://Stackoverflow.com/users/2702490", "pm_score": 1, "selected": false, "text": "echo date('m/d/y H:i (A)',strtotime($data_from_mysql));\n" }, { "answer_id": 27713112, "author": "Hasenpriester", "author_id": 1021272, "author_profile": "https://Stackoverflow.com/users/1021272", "pm_score": 5, "selected": false, "text": "$date = \\DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);\necho $date->format('m/d/y h:i a');\n $date = \\DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \\DateTimeZone('UTC'));\n$date->setTimezone(new \\DateTimeZone('Europe/Berlin'));\necho $date->format('m/d/y h:i a');\n" }, { "answer_id": 31325161, "author": "Rangel", "author_id": 4773293, "author_profile": "https://Stackoverflow.com/users/4773293", "pm_score": 3, "selected": false, "text": "SELECT \n DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,\n DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil\nFROM demo\n" }, { "answer_id": 61841551, "author": "Vadim Samokhin", "author_id": 618020, "author_profile": "https://Stackoverflow.com/users/618020", "pm_score": 0, "selected": false, "text": "datetime (new ISO8601Formatted(\n new FromISO8601('2038-01-19 11:14:07'),\n 'm/d/Y h:iA'\n))\n ->value();\n 01/19/2038 11:14AM" }, { "answer_id": 72448983, "author": "Alf Müller", "author_id": 14693464, "author_profile": "https://Stackoverflow.com/users/14693464", "pm_score": 0, "selected": false, "text": " echo(date('d.m.Y H:i:s', strtotime($row[\"date_added\"])));\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70/" ]
136,789
<p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow noreferrer">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p> <p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
[ { "answer_id": 137002, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": false, "text": "insert_statement=\"\"\"\n INSERT INTO chats(person_id, message_type, created_at, channel)\n VALUES(:person_id,:message_type,:created_at,:channel)\n\"\"\"\n cursor.execute(insert_statement, person_id='person',message_type='msg',created_at=some_date, channel=3)\n" }, { "answer_id": 137096, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 1, "selected": false, "text": "readlines executemany execute str.rstrip" }, { "answer_id": 137320, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": true, "text": "cursor.execute(\"UPDATE people SET chats_count = chats_count + 1 WHERE id = '%s'\" % person_id)\n SELECT COUNT(*) SELECT COUNT(*) FROM whatever GROUP BY whatever cursor.execute( \"INSERT INTO ... VALUES( %(x)s, %(y)s, %(z)s )\", {'x':person_id, 'y':time_to_string(time), 'z':channel,} )\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15245/" ]
136,793
<p>I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):</p> <pre><code>people = [] info = 'a' # must fill variable with something, otherwise loop won't execute while not info.empty? info = gets.chomp people += [Person.new(info)] if not info.empty? end </code></pre> <p>This code would look much nicer in a do ... while loop:</p> <pre><code>people = [] do info = gets.chomp people += [Person.new(info)] if not info.empty? while not info.empty? </code></pre> <p>In this code I don't have to assign info to some random string.</p> <p>Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?</p>
[ { "answer_id": 136815, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": 8, "selected": false, "text": "Tempfile#initialize begin\n tmpname = File.join(tmpdir, make_tmpname(basename, n))\n lock = tmpname + '.lock'\n n += 1\nend while @@cleanlist.include?(tmpname) or\n File.exist?(lock) or File.exist?(tmpname)\n >> begin\n?> puts \"do {} while ()\" \n>> end while false\ndo {} while ()\n=> nil\n >> n = 3\n=> 3\n>> begin\n?> puts n\n>> n -= 1\n>> end while n > 0\n3\n2\n1\n=> nil\n def expensive\n @expensive ||= 2 + 2\nend\n def expensive\n @expensive ||=\n begin\n n = 99\n buf = \"\" \n begin\n buf << \"#{n} bottles of beer on the wall\\n\" \n # ...\n n -= 1\n end while n > 0\n buf << \"no more bottles of beer\" \n end\nend\n" }, { "answer_id": 136825, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 7, "selected": false, "text": "people = []\n\nbegin\n info = gets.chomp\n people += [Person.new(info)] if not info.empty?\nend while not info.empty?\n" }, { "answer_id": 136846, "author": "AndrewR", "author_id": 2994, "author_profile": "https://Stackoverflow.com/users/2994", "pm_score": 5, "selected": false, "text": "people = []\n\nuntil (info = gets.chomp).empty?\n people += [Person.new(info)]\nend\n" }, { "answer_id": 2044069, "author": "is_that_okay", "author_id": 248294, "author_profile": "https://Stackoverflow.com/users/248294", "pm_score": -1, "selected": false, "text": "ppl = []\nwhile (input=gets.chomp)\n if !input.empty?\n ppl << input\n else\n p ppl; puts \"Goodbye\"; break\n end\nend\n" }, { "answer_id": 3310563, "author": "jvoorhis", "author_id": 331685, "author_profile": "https://Stackoverflow.com/users/331685", "pm_score": 4, "selected": false, "text": "Tempfile#initialize begin\n tmpname = File.join(tmpdir, make_tmpname(basename, n))\n lock = tmpname + '.lock'\n n += 1\nend while @@cleanlist.include?(tmpname) or\n File.exist?(lock) or File.exist?(tmpname)\n while begin...end >> begin\n?> puts \"do {} while ()\" \n>> end while false\ndo {} while ()\n=> nil\n >> n = 3\n=> 3\n>> begin\n?> puts n\n>> n -= 1\n>> end while n > 0\n3\n2\n1\n=> nil\n begin...end def expensive\n @expensive ||= 2 + 2\nend\n def expensive\n @expensive ||=\n begin\n n = 99\n buf = \"\" \n begin\n buf << \"#{n} bottles of beer on the wall\\n\" \n # ...\n n -= 1\n end while n > 0\n buf << \"no more bottles of beer\" \n end\nend\n" }, { "answer_id": 3410762, "author": "Paul Gillard", "author_id": 411392, "author_profile": "https://Stackoverflow.com/users/411392", "pm_score": 2, "selected": false, "text": "a = 1\nwhile true\n puts a\n a += 1\n break if a > 10\nend\n" }, { "answer_id": 8079629, "author": "Moray", "author_id": 1039759, "author_profile": "https://Stackoverflow.com/users/1039759", "pm_score": 2, "selected": false, "text": "people = []\n1.times do\n info = gets.chomp\n unless info.empty? \n people += [Person.new(info)]\n redo\n end\nend\n" }, { "answer_id": 10713963, "author": "Siwei", "author_id": 445908, "author_profile": "https://Stackoverflow.com/users/445908", "pm_score": 10, "selected": true, "text": "begin <code> end while <condition> Kernel#loop loop do \n # some code here\n break if <condition>\nend \n |> Don't use it please. I'm regretting this feature, and I'd like to\n|> remove it in the future if it's possible.\n|\n|I'm surprised. What do you regret about it?\n\nBecause it's hard for users to tell\n\n begin <code> end while <cond>\n\nworks differently from\n\n <code> while <cond>\n" }, { "answer_id": 14918579, "author": "Steely Wing", "author_id": 1877620, "author_profile": "https://Stackoverflow.com/users/1877620", "pm_score": 4, "selected": false, "text": "begin\n # statment\nend until <condition>\n begin loop do\n # ...\n break if <condition>\nend\n" }, { "answer_id": 18495469, "author": "jds", "author_id": 2726610, "author_profile": "https://Stackoverflow.com/users/2726610", "pm_score": 3, "selected": false, "text": "begin\n <multiple_lines_of_code>\nend while <cond>\n <single_line_of_code> while <cond>\n if <cond> then <one_line_code> # matches case-when-then statement\n\nwhile <cond> then <one_line_code>\n\n<one_line_code> while <cond>\n\nbegin <multiple_line_code> end while <cond> # or something similar but left-to-right\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
136,829
<p>In VB.NET (or C#) how can I determine programmatically if a public variable in class helper.vb is used anywhere within a project?</p>
[ { "answer_id": 137094, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "CodeParser CodeCompileUnit CodePropertyReferenceExpression" }, { "answer_id": 141954, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": true, "text": "Sub ActionExample()\n Dim objFind As Find = objTextDoc.DTE.Find\n\n ' Set the find options.\n objFind.Action = vsFindAction.vsFindActionFindAll\n objFind.Backwards = False\n objFind.FilesOfType = \"*.vb\"\n objFind.FindWhat = \"<Variable>\"\n objFind.KeepModifiedDocumentsOpen = False\n objFind.MatchCase = True\n objFind.MatchInHiddenText = True\n objFind.MatchWholeWord = True\n objFind.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral\n objFind.ResultsLocation = vsFindResultsLocation.vsFindResultsNone\n objFind.SearchPath = \"c:\\<Your>\\<Project>\\<Path>\"\n objFind.SearchSubfolders = False\n objFind.Target = vsFindTarget.vsFindTargetCurrentDocument\n ' Perform the Find operation.\n objFind.Execute()\nEnd Sub\n\n\n\n<System.ContextStaticAttribute()> _\nPublic WithEvents FindEvents As EnvDTE.FindEvents\n\nPublic Sub FindEvents_FindDone(ByVal Result As EnvDTE.vsFindResult, _\n ByVal Cancelled As Boolean) _\n Handles FindEvents.FindDone\n Select Case Result \n case vsFindResultFound\n 'Found!\n case else\n 'Not Found\n Ens select\nEnd Sub\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22301/" ]
136,831
<p>After reading this answer: <a href="https://stackoverflow.com/questions/136474/best-way-to-pick-a-random-subset-from-a-collection#136513">best way to pick a random subset from a collection?</a></p> <p>It got me wondering, how does one pick a random seed in Java?</p> <p>And don't say use System.currentTimeMillis() or System.nanoTime(). Read the article to see why not.</p> <p>That's a hard question, but let me make it harder. Let's say you need to generate a random seed without connecting to the internet, without using user input (IE, there's no gui), and it has to be cross platform (therefore no JNI to access hardware).</p> <p>Is there some JVM variables we can monitor as a source of our randomness?</p> <p>Can this be done? Or is it impossible?</p>
[ { "answer_id": 136888, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 0, "selected": false, "text": "System.currentTimeMillis()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
136,836
<p>What is the slickest way to initialize an array of dynamic size in C# that you know of?</p> <p>This is the best I could come up with</p> <pre><code>private bool[] GetPageNumbersToLink(IPagedResult result) { if (result.TotalPages &lt;= 9) return new bool[result.TotalPages + 1].Select(b =&gt; true).ToArray(); ... </code></pre>
[ { "answer_id": 136890, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "return result.Select(p => true).ToArray();\n" }, { "answer_id": 137126, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "return Enumerable.Range(0, count).Select(x => true).ToArray();\n var array = new bool[count];\n\nfor(var i = 0; i < count; i++) {\n array[i] = true;\n}\n\nreturn array;\n" }, { "answer_id": 137160, "author": "Neil Hewitt", "author_id": 22178, "author_profile": "https://Stackoverflow.com/users/22178", "pm_score": 4, "selected": false, "text": "public static T[] SetAllValues<T>(this T[] array, T value) where T : struct\n{\n for (int i = 0; i < array.Length; i++)\n array[i] = value;\n\n return array;\n}\n bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true);\n public static class ArrayOf<T>\n{\n public static T[] Create(int size, T initialValue)\n {\n T[] array = (T[])Array.CreateInstance(typeof(T), size);\n for (int i = 0; i < array.Length; i++)\n array[i] = initialValue;\n return array;\n }\n}\n bool[] tenTrueBoolsInAnArray = ArrayOf<bool>.Create(10, true);\n" }, { "answer_id": 137183, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "Enumerable.Repeat(true, result.TotalPages + 1).ToArray()\n" }, { "answer_id": 1051227, "author": "Nigel Touch", "author_id": 97846, "author_profile": "https://Stackoverflow.com/users/97846", "pm_score": 6, "selected": false, "text": "Initialize with for loop: 85 ms [much faster]\nInitialize with Enumerable.Repeat: 1645 ms \n" }, { "answer_id": 26277437, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 1, "selected": false, "text": "public static void Init<T>(this T[] arr, Func<int, T> factory)\n{\n for (int i = 0; i < arr.Length; i++)\n {\n arr[i] = factory(i);\n }\n}\n public static T[] GenerateInitializedArray<T>(int size, Func<int, T> factory)\n{\n var arr = new T[size];\n for (int i = 0; i < arr.Length; i++)\n {\n arr[i] = factory(i);\n }\n return arr;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
136,837
<p>A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials.</p> <p>One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP.</p> <p>The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent.</p> <p>Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps?</p>
[ { "answer_id": 136874, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": "public Dictionary<String,DateTime> UserDictionary\n{\n get\n {\n if (HttpContext.Current.Cache[\"UserDictionary\"] != null)\n {\n return HttpContext.Current.Cache[\"UserDictionary\"] as Dictionary<String,DateTime>;\n }\n return new Dictionary<String,DateTime>();\n }\n set\n {\n HttpContext.Current.Cache[\"UserDictionary\"] = value;\n }\n}\n\npublic bool IsUserAlreadyLoggedIn(string userName)\n{\n removeIdleUsers();\n return UserDictionary.ContainsKey(userName);\n}\n\npublic void UpdateUser(string userName)\n{\n UserDictionary[userName] = DateTime.Now;\n\n removeIdleUsers();\n}\n\nprivate void removeIdleUsers()\n{\n for (int i = 0; i < UserDictionary.Length; i++)\n {\n if (user[i].Value < DateTime.Now.AddMinutes(-20))\n user.RemoveAt(i);\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
136,880
<p>So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions:</p> <ol> <li><p>It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change <em>another</em> function somewhere else. Is this something that just gets easier with experience?</p></li> <li><p>Are the benefits of using const <em>really</em> enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it?</p></li> </ol> <p>I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.</p>
[ { "answer_id": 136895, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 7, "selected": false, "text": "void foo(const int DEFCON)\n{\n if (DEFCON = 1) //< FLAGGED AS COMPILER ERROR! WORLD SAVED!\n {\n fire_missiles();\n }\n}\n" }, { "answer_id": 136917, "author": "Jordan Parmer", "author_id": 20133, "author_profile": "https://Stackoverflow.com/users/20133", "pm_score": 8, "selected": true, "text": "if( x = y ) // whoops, meant if( x == y )\n" }, { "answer_id": 136938, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "const const const const const const const const const #include <iostream>\n\nclass HelloWorld {\n bool hw_called;\n\npublic:\n HelloWorld() : hw_called(false) {}\n\n void hw() const {\n std::cout << \"Hello, world! (const)\\n\";\n // hw_called = true; <-- not allowed\n }\n\n void hw() {\n std::cout << \"Hello, world! (non-const)\\n\";\n hw_called = true;\n }\n};\n\nint\nmain()\n{\n HelloWorld hw;\n HelloWorld* phw1(&hw);\n HelloWorld const* phw2(&hw);\n\n hw.hw(); // calls non-const version\n phw1->hw(); // calls non-const version\n phw2->hw(); // calls const version\n return 0;\n}\n" }, { "answer_id": 137179, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 5, "selected": false, "text": "const" }, { "answer_id": 137599, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": false, "text": "const const const" }, { "answer_id": 137710, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": "#include <string>\n\nvoid f(const std::string& s)\n{\n\n}\nvoid x( std::string& x)\n{\n}\nvoid main()\n{\n f(\"blah\");\n x(\"blah\"); // won't compile...\n}\n" }, { "answer_id": 1871286, "author": "Peter Kovacs", "author_id": 81214, "author_profile": "https://Stackoverflow.com/users/81214", "pm_score": 4, "selected": false, "text": "class A { ... }\nclass B { A m_a; const A& getA() const { return m_a; } };\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
136,884
<p>Is it possible to have a <code>&lt;div&gt;</code> simultaneously (1) not take up all available width and (2) collapse margins with its neighbors?</p> <p>I learned recently that setting a <code>div</code> to <code>display:table</code> will stop it from expanding to take up the whole width of the parent container -- but now I realize that this introduces a new problem: it stops collapsing margins with its neighbors.</p> <p>In the example below, the red div fails to collapse, and the blue div is too wide.</p> <pre><code>&lt;p style="margin:100px"&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; &lt;div style="margin: 100px; border: solid red 2px; display: table;"&gt; This is a div with 100px margin all around and display:table. &lt;br/&gt; The problem is that it doesn't collapse margins with its neighbors. &lt;/div&gt; &lt;p style="margin:100px"&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; &lt;div style="margin: 100px; border: solid blue 2px; display: block;"&gt; This is a div with 100px margin all around and display:block. &lt;br/&gt; The problem is that it expands to take up all available width. &lt;/div&gt; &lt;p style="margin:100px"&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; </code></pre> <p>Is there a way to meet both criteria simultaneously?</p>
[ { "answer_id": 136921, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": true, "text": "display: table div div div <p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n\n<div style=\"margin: 100px\"><div style=\"border: solid red 2px; display: table;\">\n This is a div which had 100px margin all around and display:table, but the margin was moved to a wrapper div.\n <br/>\n The problem was that it didn't collapse margins with its neighbors.\n</div></div>\n\n<p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n\n<div style=\"margin: 100px; border: solid blue 2px; display: block;\">\n This is a div with 100px margin all around and display:block.\n <br/>\n The problem is that it expands to take up all available width.\n</div>\n\n<p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n" }, { "answer_id": 137397, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "<p style=\"margin:100px\">This is a paragraph with 100px margin all around.</p>\n\n<div style=\"border: solid red 2px; float: left;\">\n This should work.\n</div>\n\n<p style=\"margin:100px;clear:both;\">This is a paragraph with 100px margin all around.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
136,899
<p>In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?</p> <p>If so, in what circumstances would you use this?</p> <p>Code examples are welcome.</p> <p>Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use</p> <pre><code>@fopen($file); </code></pre> <p>and then check afterwards... but you can get rid of the @ by doing</p> <pre><code>if (file_exists($file)) { fopen($file); } else { die('File not found'); } </code></pre> <p>or similar. </p> <p>I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?</p>
[ { "answer_id": 136912, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 5, "selected": false, "text": "fopen() FALSE FALSE" }, { "answer_id": 136955, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 1, "selected": false, "text": "<?php\n error_reporting(0);\n?>\n" }, { "answer_id": 137013, "author": "Eric Lamb", "author_id": 538, "author_profile": "https://Stackoverflow.com/users/538", "pm_score": 2, "selected": false, "text": "error_reporting(0);\n" }, { "answer_id": 137244, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 2, "selected": false, "text": "$data_len = @socket_recvfrom( $sock, $buffer, 512, 0, $remote_host, $remote_port )\n" }, { "answer_id": 137728, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 4, "selected": false, "text": "try {\n if (($fp = @fopen($filename, \"r\")) == false) {\n throw new Exception;\n } else {\n do_file_stuff();\n }\n} catch (Exception $e) {\n handle_exception();\n}\n" }, { "answer_id": 960288, "author": "Gerry", "author_id": 109561, "author_profile": "https://Stackoverflow.com/users/109561", "pm_score": 7, "selected": false, "text": "display_errors" }, { "answer_id": 1133973, "author": "ashnazg", "author_id": 108146, "author_profile": "https://Stackoverflow.com/users/108146", "pm_score": 3, "selected": false, "text": "$orig = error_reporting(); // capture original error level\nerror_reporting(0); // suppress all errors\n$result = native_func(); // native_func() is expected to return FALSE when it errors\nerror_reporting($orig); // restore error reporting to its original level\nif (false === $result) { throw new Exception('native_func() failed'); }\n $result = @native_func();\n" }, { "answer_id": 1156660, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "$script_ok = @eval('return true; '.$script);\n" }, { "answer_id": 2272401, "author": "Sumesh", "author_id": 274301, "author_profile": "https://Stackoverflow.com/users/274301", "pm_score": 0, "selected": false, "text": "# supress error for this statement\nsupress_error_start(); \n$mail_sent = mail($EmailTo, $Subject, $message,$headers);\nsupress_error_end(); #Don't forgot to call this to restore error. \n\nfunction supress_error_start(){\n set_error_handler('nothing');\n error_reporting(0);\n}\n\nfunction supress_error_end(){\n set_error_handler('my_err_handler');\n error_reporting('Set this to a value of your choice');\n}\n\nfunction nothing(){ #Empty function\n}\n\nfunction my_err_handler('arguments will come here'){\n //Your own error handling routines will come here\n}\n" }, { "answer_id": 3870560, "author": "Your Common Sense", "author_id": 285587, "author_profile": "https://Stackoverflow.com/users/285587", "pm_score": 3, "selected": false, "text": "permission denied save mode restriction open_basedir restriction" }, { "answer_id": 60886618, "author": "Daan", "author_id": 987864, "author_profile": "https://Stackoverflow.com/users/987864", "pm_score": 2, "selected": false, "text": "E_NOTICE E_NOTICE function exception_error_handler($severity, $message, $file, $line) { \n throw new ErrorException($message, 0, $severity, $file, $line); \n} \n\nset_error_handler('exception_error_handler'); \n\ntry { \n unserialize('foo');\n} catch(\\Exception $e) {\n // ... will throw the exception here\n} \n" }, { "answer_id": 67541028, "author": "Christopher Schultz", "author_id": 276232, "author_profile": "https://Stackoverflow.com/users/276232", "pm_score": 1, "selected": false, "text": "if(function_exists(\"random_bytes\")) {\n $bytes = random_bytes(32);\n} else {\n @include \"random_compat/random.php\"; // Suppress warnings+errors\n if(function_exists(\"random_bytes\")) {\n $bytes = random_bytes(32);\n } else if(function_exists('openssl_random_pseudo_bytes')) {\n $bytes = openssl_random_pseudo_bytes(4);\n } else {\n // Boooo! We have to generate crappy randomness\n $bytes = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',64)),0,32);\n }\n}\n include file_exists" }, { "answer_id": 68262822, "author": "Emanuel A.", "author_id": 2033076, "author_profile": "https://Stackoverflow.com/users/2033076", "pm_score": 1, "selected": false, "text": "$totalCars = [];\n\n$totalCars['toyota']++; // PHP Notice: Undefined index: toyota\n\n@$totalCars['toyota']++;\n// [\n// \"toyota\" => 2,\n// ]\n" }, { "answer_id": 70197339, "author": "Stanley Aloh", "author_id": 9182496, "author_profile": "https://Stackoverflow.com/users/9182496", "pm_score": 0, "selected": false, "text": "new mysqli($this->host, $this->username, $this->password, $this->db);\n mysqli::errno mysli::error $this->connection = @new mysqli($this->host, $this->username, $this->password, $this->db);\n if($this->connection->connect_errno)\n throw new mysqli_sql_exception($this->connection->error);\n @ @" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
136,937
<p>Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.</p>
[ { "answer_id": 136957, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 1, "selected": false, "text": "onLocationChange" }, { "answer_id": 136965, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": true, "text": "hashchange window.addEventListener(\"hashchange\", function(e) {\n // ...\n})\n hashChange" }, { "answer_id": 9406145, "author": "Tom Penzer", "author_id": 1227266, "author_profile": "https://Stackoverflow.com/users/1227266", "pm_score": 3, "selected": false, "text": "var pageload = {\n ignorehashchange: false,\n loadUrl: function(){\n if (pageload.ignorehashchange == false){\n //code to parse window.location.hash and load content\n };\n }\n};\n pageload.loadUrl window.addEventListener(\"hashchange\", pageload.loadUrl, false);\n window.location.hash window.location.hash = pageload.ignorehashchange = true;\n setTimeout(function(){pageload.ignorehashchange = false;}, 100);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
136,946
<p>What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?</p> <p>For example, when should one use</p> <pre><code>enum {BUFFER = 1234}; </code></pre> <p>over</p> <pre><code>#define BUFFER 1234 </code></pre>
[ { "answer_id": 136954, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 7, "selected": true, "text": "enum #define #define" }, { "answer_id": 136974, "author": "akiva", "author_id": 65724, "author_profile": "https://Stackoverflow.com/users/65724", "pm_score": 3, "selected": false, "text": "enum ERROR_TYPES\n{\n REGULAR_ERR =1,\n OK =0\n}\n" }, { "answer_id": 136978, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 1, "selected": false, "text": "#define" }, { "answer_id": 136992, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "#define" }, { "answer_id": 137099, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 3, "selected": false, "text": "enum openType: OpenExisting openType: 2 #define // Yeah, dumb example\nenum OpenType {\n OpenExisting,\n OpenOrCreate,\n Truncate\n};\n\nvoid OpenFile(const char* filename, OpenType openType, int bufferSize);\n" }, { "answer_id": 147203, "author": "Russell Bryant", "author_id": 23224, "author_profile": "https://Stackoverflow.com/users/23224", "pm_score": 1, "selected": false, "text": "enum {\n STATE_ONE,\n STATE_TWO,\n STATE_THREE\n};\n\n...\n\nswitch (state) {\ncase STATE_ONE:\n handle_state_one();\n break;\ncase STATE_TWO:\n handle_state_two();\n break;\n};\n" }, { "answer_id": 3035591, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "case" }, { "answer_id": 3035598, "author": "PeterK", "author_id": 350605, "author_profile": "https://Stackoverflow.com/users/350605", "pm_score": 1, "selected": false, "text": "const int #define" }, { "answer_id": 3035620, "author": "Andy", "author_id": 339702, "author_profile": "https://Stackoverflow.com/users/339702", "pm_score": 2, "selected": false, "text": "enum fruits{ apple=1234, orange=12345};\n #define apple 1234\n#define orange 12345\n" }, { "answer_id": 3035640, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 2, "selected": false, "text": "enum {\n ONE = 1,\n TWO,\n THREE,\n FOUR\n};\n #define ONE 1\n#define TWO 2\n#define THREE 3\n#define FOUR 4\n" }, { "answer_id": 3035672, "author": "ShinTakezou", "author_id": 354803, "author_profile": "https://Stackoverflow.com/users/354803", "pm_score": 2, "selected": false, "text": "enum action { DO_JUMP, DO_TURNL, DO_TURNR, DO_STOP };\n//...\nvoid do_action( enum action anAction, info_t x );\n void do_action(int anAction, info_t x);\n" }, { "answer_id": 3035720, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "enum #define enum enum #define #define enum enum const int const int enum" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21539/" ]
136,948
<p>I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7.</p> <p>The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is</p> <pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ EIPortal_DEV_2_0_5_4[1].expd" </code></pre> <p>This unfortunately does not resolve to the physical file when calling <code>FileExists()</code> or when attempting to create a <code>TFileStream</code> object.</p> <p>The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of <code>"Content.IE5\ALBKHO3Q"</code> whose absolute path would be expressed as</p> <pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd" </code></pre> <p>Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing.</p> <p>Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of <code>"application/x-expeditors"</code>. The registration of the <code>".expd"</code> / <code>"application/x-expeditors"</code> mime-type looks like this.</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd] @="ExpeditorsInstaller" "Content Type"="application/x-expeditors" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller] "EditFlags"=hex:00,00,01,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell] [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open] @="" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command] @="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\"" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors] "Extension"=".expd" </code></pre> <p>I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix <code>"[n]"</code> may be the unique key.</p> <p>I have tried wininet method <code>GetUrlCacheEntryInfo</code> but that requires the URL, not the virtual path handed over by IE.</p> <p>My hope is that there is a Shell function that given a virtual path will hand back the physical path.</p>
[ { "answer_id": 136954, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 7, "selected": true, "text": "enum #define #define" }, { "answer_id": 136974, "author": "akiva", "author_id": 65724, "author_profile": "https://Stackoverflow.com/users/65724", "pm_score": 3, "selected": false, "text": "enum ERROR_TYPES\n{\n REGULAR_ERR =1,\n OK =0\n}\n" }, { "answer_id": 136978, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 1, "selected": false, "text": "#define" }, { "answer_id": 136992, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "#define" }, { "answer_id": 137099, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 3, "selected": false, "text": "enum openType: OpenExisting openType: 2 #define // Yeah, dumb example\nenum OpenType {\n OpenExisting,\n OpenOrCreate,\n Truncate\n};\n\nvoid OpenFile(const char* filename, OpenType openType, int bufferSize);\n" }, { "answer_id": 147203, "author": "Russell Bryant", "author_id": 23224, "author_profile": "https://Stackoverflow.com/users/23224", "pm_score": 1, "selected": false, "text": "enum {\n STATE_ONE,\n STATE_TWO,\n STATE_THREE\n};\n\n...\n\nswitch (state) {\ncase STATE_ONE:\n handle_state_one();\n break;\ncase STATE_TWO:\n handle_state_two();\n break;\n};\n" }, { "answer_id": 3035591, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "case" }, { "answer_id": 3035598, "author": "PeterK", "author_id": 350605, "author_profile": "https://Stackoverflow.com/users/350605", "pm_score": 1, "selected": false, "text": "const int #define" }, { "answer_id": 3035620, "author": "Andy", "author_id": 339702, "author_profile": "https://Stackoverflow.com/users/339702", "pm_score": 2, "selected": false, "text": "enum fruits{ apple=1234, orange=12345};\n #define apple 1234\n#define orange 12345\n" }, { "answer_id": 3035640, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 2, "selected": false, "text": "enum {\n ONE = 1,\n TWO,\n THREE,\n FOUR\n};\n #define ONE 1\n#define TWO 2\n#define THREE 3\n#define FOUR 4\n" }, { "answer_id": 3035672, "author": "ShinTakezou", "author_id": 354803, "author_profile": "https://Stackoverflow.com/users/354803", "pm_score": 2, "selected": false, "text": "enum action { DO_JUMP, DO_TURNL, DO_TURNR, DO_STOP };\n//...\nvoid do_action( enum action anAction, info_t x );\n void do_action(int anAction, info_t x);\n" }, { "answer_id": 3035720, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "enum #define enum enum #define #define enum enum const int const int enum" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13183/" ]
136,961
<p>I'm using the jQuery Form plugin to upload an image. I've assigned a fade animation to happen the <code>beforeSubmit</code> callback, but as I'm running locally, it doesn't have time to finish before the <code>success</code> function is called. </p> <p>I am using a callback function in my <code>fade();</code> call to make sure that one fade completes, before the next one begins, but that does not seem to guarantee that the function that's calling it is finished.</p> <p>Am I doing something wrong? Shouldn't <code>beforeSubmit</code> complete before the ajax call is submitted?</p> <p>Here's are the two callbacks:</p> <p>beforeSubmit:</p> <pre><code>function prepImageArea() { if (userImage) { userImage.fadeOut(1500, function() { ajaxSpinner.fadeIn(1500); }); } } </code></pre> <p>success:</p> <pre><code>function imageUploaded(data) { var data = evalJson(data); userImage.attr('src', data.large_thumb); ajaxSpinner.fadeOut(1500, function() { userImage.fadeIn(1500); }); } </code></pre>
[ { "answer_id": 137035, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 3, "selected": true, "text": "if (userImage) {\n userImage.fadeOut(1500, function() {\n ajaxSpinner.fadeIn(1500, function(){\n //now trigger the upload and you don't need the before submit anymore\n });\n });\n}\nelse {\n // trigger the upload right away\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4636/" ]
136,975
<p>Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler.</p> <p>In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.</p> <p>It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.</p> <p>Is that possible?</p> <p>EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough. </p>
[ { "answer_id": 136997, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "EventHandler.GetInvocationList().Length > 0\n" }, { "answer_id": 136998, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 8, "selected": true, "text": "+= -= null public bool IsEventHandlerRegistered(Delegate prospectiveHandler)\n{ \n if ( this.EventHandler != null )\n {\n foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )\n {\n if ( existingHandler == prospectiveHandler )\n {\n return true;\n }\n }\n }\n return false;\n}\n -= +=" }, { "answer_id": 137112, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 3, "selected": false, "text": "public class MyClass\n{\n event Action MyEvent;\n}\n\n...\n\nMyClass myClass = new MyClass();\nmyClass.MyEvent += SomeFunction;\n\n...\n\nAction[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example\n\nConsole.WriteLine(handlers[0].Method.Name);//prints the name of the method\n" }, { "answer_id": 7065771, "author": "alf", "author_id": 512507, "author_profile": "https://Stackoverflow.com/users/512507", "pm_score": 8, "selected": false, "text": "myClass.MyEvent -= MyHandler;\nmyClass.MyEvent += MyHandler;\n" }, { "answer_id": 36175516, "author": "Software_developer", "author_id": 5093204, "author_profile": "https://Stackoverflow.com/users/5093204", "pm_score": 2, "selected": false, "text": " try\n {\n control_name.Click -= event_Click;\n main_browser.Document.Click += Document_Click;\n }\n catch(Exception exce)\n {\n main_browser.Document.Click += Document_Click;\n }\n" }, { "answer_id": 56279899, "author": "Xtian11", "author_id": 1108617, "author_profile": "https://Stackoverflow.com/users/1108617", "pm_score": 3, "selected": false, "text": "bool alreadyAdded = false;\n if(!alreadyAdded)\n{\n myClass.MyEvent += MyHandler;\n alreadyAdded = true;\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
136,986
<p>2 tables: </p> <pre><code>Employees - EmployeeID - LeadCount Leads - leadID - employeeID </code></pre> <p>I want to update the <code>Employees.LeadCount</code> column by counting the # of leads in the <code>Leads</code> table that have the same <code>EmployeeID</code>.</p> <p>Note: There may be more than 1 lead with the same employeeID, so I have to do a <code>DISTINCT(SUM(employeeID))</code>.</p>
[ { "answer_id": 137001, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "UPDATE Employees SET LeadCount = (\n SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Employees.employeeId\n)\n" }, { "answer_id": 137009, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "UPDATE\n Employees E\nSET\n E.LeadCount = (\n SELECT COUNT(L.EmployeeID)\n FROM Leads L\n WHERE L.EmployeeID = E.EmployeeID\n )\n" }, { "answer_id": 137032, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "// create tmp -> TBL (EmpID, count)\n\ninsert into TBL \n SELECT employeeID COUNT(employeeID) Di\n FROM Leads WHERE Leads.employeeId = Employees.employeeId GROUP BY EmployeeId\nUPDATE Employees SET LeadCount = (\n SELECT count FROM TBL WHERE TBL.EmpID = Employees.employeeId\n)\n\n// drop TBL\n" }, { "answer_id": 137087, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "UPDATE Employees SET\n LeadCount = Leads.LeadCount\nFROM Employee\nJOIN (\n SELECT EmployeeId, COUNT(*) as LeadCount \n FROM Leads \n GROUP BY EmployeeId\n) as Leads ON\n Employee.EmployeeId = Leads.EmployeeId \n" }, { "answer_id": 137097, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "SELECT employeeID, COUNT(leadId) AS LeadCount\nFROM Leads\nGROUP BY employeeID;\n CREATE TRIGGER leadIns AFTER INSERT ON Leads\nFOR EACH ROW BEGIN\n UPDATE Employees SET LeadCount = LeadCount + 1 WHERE employeeID = NEW.employeeID;\nEND\n\nCREATE TRIGGER leadIns AFTER UPDATE ON Leads\nFOR EACH ROW BEGIN\n UPDATE Employees SET LeadCount = LeadCount - 1 WHERE employeeID = OLD.employeeID;\n UPDATE Employees SET LeadCount = LeadCount + 1 WHERE employeeID = NEW.employeeID;\nEND\n\nCREATE TRIGGER leadIns AFTER DELETE ON Leads\nFOR EACH ROW BEGIN\n UPDATE Employees SET LeadCount = LeadCount - 1 WHERE employeeID = OLD.employeeID;\nEND\n UPDATE Employees SET LeadCount = 0;\nUPDATE Employees AS e JOIN Leads AS l USING (employeeID)\n SET e.LeadCount = e.LeadCount+1;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/136986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
137,006
<p>Is there any way to redefine a class or some of its methods without using typical inheritance? For example:</p> <pre><code>class third_party_library { function buggy_function() { return 'bad result'; } function other_functions(){ return 'blah'; } } </code></pre> <p>What can I do to replace <code>buggy_function()</code>? Obviously this is what I would like to do</p> <pre><code>class third_party_library redefines third_party_library{ function buggy_function() { return 'good result'; } function other_functions(){ return 'blah'; } } </code></pre> <p>This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.</p> <p>I've found this <a href="http://pecl.php.net/package/classkit" rel="noreferrer">library</a> that says it can do it, but I'm wary as it's 4 years old.</p> <p>EDIT:</p> <p>I should have clarified that I cannot rename the class from <code>third_party_library</code> to <code>magical_third_party_library</code> or anything else because of framework limitations.</p> <p>For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a &quot;partial class.&quot;</p>
[ { "answer_id": 137028, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 6, "selected": true, "text": "runkit_method_redefine /tests/runkit_method_redefine.phpt runkit_method_redefine('third_party_library', 'buggy_function', '',\n 'return \\'good result\\''\n);\n" }, { "answer_id": 137030, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "extend <?php\nclass sd_third_party_library extends third_party_library\n{\n function buggy_function() {\n return 'good result';\n }\n function other_functions(){\n return 'blah';\n }\n}\n buggy_function($foo, $bar)" }, { "answer_id": 137034, "author": "Eric Lamb", "author_id": 538, "author_profile": "https://Stackoverflow.com/users/538", "pm_score": -1, "selected": false, "text": "class my_better_class Extends some_buggy_class {\n function non_buggy_function() {\n return 'good result';\n }\n}\n" }, { "answer_id": 347522, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 4, "selected": false, "text": "runkit_method_redefine()" }, { "answer_id": 4385190, "author": "Newbie", "author_id": 534686, "author_profile": "https://Stackoverflow.com/users/534686", "pm_score": 3, "selected": false, "text": "class Wrapper {\n private $third_party_library;\n function __construct() { $this->third_party_library = new Third_party_library(); }\n function __call($method, $args) {\n return call_user_func_array(array($this->third_party_library, $method), $args);\n }\n}\n" }, { "answer_id": 6312192, "author": "JPhilly", "author_id": 759382, "author_profile": "https://Stackoverflow.com/users/759382", "pm_score": 4, "selected": false, "text": "class Patch {\n\nprivate $_code;\n\npublic function __construct($include_file = null) {\n if ( $include_file ) {\n $this->includeCode($include_file);\n }\n}\n\npublic function setCode($code) {\n $this->_code = $code;\n}\n\npublic function includeCode($path) {\n\n $fp = fopen($path,'r');\n $contents = fread($fp, filesize($path));\n $contents = str_replace('<?php','',$contents);\n $contents = str_replace('?>','',$contents);\n fclose($fp); \n\n $this->setCode($contents);\n}\n\nfunction redefineFunction($new_function) {\n\n preg_match('/function (.+)\\(/', $new_function, $aryMatches);\n $func_name = trim($aryMatches[1]);\n\n if ( preg_match('/((private|protected|public) function '.$func_name.'[\\w\\W\\n]+?)(private|protected|public)/s', $this->_code, $aryMatches) ) {\n\n $search_code = $aryMatches[1];\n\n $new_code = str_replace($search_code, $new_function.\"\\n\\n\", $this->_code);\n\n $this->setCode($new_code);\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n}\n\nfunction getCode() {\n return $this->_code;\n}\n}\n $objPatch = new Patch('path_to_class_file.php');\n$objPatch->redefineFunction(\"\n protected function foo(\\$arg1, \\$arg2)\n { \n return \\$arg1+\\$arg2;\n }\");\n eval($objPatch->getCode());\n" }, { "answer_id": 45260210, "author": "Ludo - Off the record", "author_id": 1362815, "author_profile": "https://Stackoverflow.com/users/1362815", "pm_score": 4, "selected": false, "text": "namespace MyCustomName;\n\nclass third_party_library extends \\third_party_library {\n function buggy_function() {\n return 'good result';\n }\n function other_functions(){\n return 'blah';\n }\n}\n use MyCustomName\\third_party_library;\n\n$test = new third_party_library();\n$test->buggy_function();\n//or static.\nthird_party_library::other_functions();\n" }, { "answer_id": 46818982, "author": "That Realty Programmer Guy", "author_id": 578023, "author_profile": "https://Stackoverflow.com/users/578023", "pm_score": 0, "selected": false, "text": "class third_party_library {\n public static $buggy_function;\n public static $ranOnce=false;\n\n public function __construct(){\n if(!self::$ranOnce){\n self::$buggy_function = function(){ return 'bad result'; };\n self::$ranOnce=true;\n }\n .\n .\n .\n }\n function buggy_function() {\n return self::$buggy_function();\n } \n}\n $myObject = new third_party_library() $backup['buggy_function'] = third_party_library::$buggy_function;\nthird_party_library::$buggy_function = function(){\n //do stuff\n return $great_calculation;\n}\n.\n.\n. //do other stuff that needs the override\n. //when finished, restore the original function\n.\nthird_party_library::$buggy_function=$backup['buggy_function'];\n public static $functions['function_name'] = function(...){...};" }, { "answer_id": 61447042, "author": "Arik", "author_id": 1655245, "author_profile": "https://Stackoverflow.com/users/1655245", "pm_score": 1, "selected": false, "text": "class Patch {\n\n private $_code;\n\n public function __construct($include_file = null) {\n if ( $include_file ) {\n $this->includeCode($include_file);\n }\n }\n\n public function setCode($code) {\n $this->_code = $code;\n }\n\n public function includeCode($path) {\n\n $fp = fopen($path,'r');\n $contents = fread($fp, filesize($path));\n $contents = str_replace('<?php','',$contents);\n $contents = str_replace('?>','',$contents);\n fclose($fp); \n\n $this->setCode($contents);\n }\n\n function redefineFunction($new_function) {\n\n preg_match('/function ([^\\(]*)\\(/', $new_function, $aryMatches);\n $func_name = trim($aryMatches[1]);\n\n // capture the function with its body and replace it with the new function\n if ( preg_match('/((private|protected|public)?\\s?function ' . $func_name .'[\\w\\W\\n]+?)(private|protected|public|function|class)/s', $this->_code, $aryMatches) ) {\n\n $search_code = $aryMatches[1];\n\n $new_code = str_replace($search_code, $new_function.\"\\n\\n\", $this->_code);\n\n $this->setCode($new_code);\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n }\n function renameClass($old_name, $new_name) {\n\n $new_code = str_replace(\"class $old_name \", \"class $new_name \", $this->_code);\n\n $this->setCode($new_code);\n\n }\n\n function getCode() {\n return $this->_code;\n }\n}\n $objPatch = new Patch(ABSPATH . 'wp-content/plugins/a-plugin/code.php');\n$objPatch->renameClass(\"Patched_AClass\", \"Patched_Patched_AClass\"); // just to avoid class redefinition\n$objPatch->redefineFunction(\"\n function default_initialize() {\n echo 'my patched function';\n }\");\neval($objPatch->getCode());\n$result = new Patched_AClass();\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
137,011
<p>I have a lot of nice MATLAB code that runs too slowly and would be a pain to write over in C. The MATLAB compiler for C does not seem to help much, if at all. Should it be speeding execution up more? Am I screwed?</p>
[ { "answer_id": 356799, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 1, "selected": false, "text": "s = [];\nfor i = 1:50000\n s(i) = 3;\nend\n s = zeros(50000,1);\nfor i = 1:50000\n s(i) = 3;\nend\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,021
<p>What is the best way to take a given PHP object and serialize it as XML? I am looking at simple_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.</p>
[ { "answer_id": 137037, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": false, "text": "<?php\n$array = array('hello' => 'world', 'good' => 'morning');\n\n$xml = simplexml_load_string(\"<?xml version='1.0' encoding='utf-8'?><foo />\");\nforeach ($array as $k=>$v) {\n $xml->addChild($k, $v);\n}\n?>\n" }, { "answer_id": 137051, "author": "Steve Paulo", "author_id": 9414, "author_profile": "https://Stackoverflow.com/users/9414", "pm_score": -1, "selected": false, "text": "$_xml = '';\nforeach($obj as $key => $val){\n $_xml .= '<' . $key . '>' . $val . '</' . $key . \">\\n\";\n}\n $_xml" }, { "answer_id": 2108136, "author": "significance", "author_id": 112432, "author_profile": "https://Stackoverflow.com/users/112432", "pm_score": 3, "selected": false, "text": "$root = '<?xml version=\"1.0\" encoding=\"UTF-8\"?><Activities/>';\n$object = new simpleXMLElement($root); \n $object = new stdClass;\n" }, { "answer_id": 2194774, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 6, "selected": false, "text": "class XMLSerializer {\n\n // functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/\n\n public static function generateValidXmlFromObj(stdClass $obj, $node_block='nodes', $node_name='node') {\n $arr = get_object_vars($obj);\n return self::generateValidXmlFromArray($arr, $node_block, $node_name);\n }\n\n public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node') {\n $xml = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>';\n\n $xml .= '<' . $node_block . '>';\n $xml .= self::generateXmlFromArray($array, $node_name);\n $xml .= '</' . $node_block . '>';\n\n return $xml;\n }\n\n private static function generateXmlFromArray($array, $node_name) {\n $xml = '';\n\n if (is_array($array) || is_object($array)) {\n foreach ($array as $key=>$value) {\n if (is_numeric($key)) {\n $key = $node_name;\n }\n\n $xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';\n }\n } else {\n $xml = htmlspecialchars($array, ENT_QUOTES);\n }\n\n return $xml;\n }\n\n}\n" }, { "answer_id": 6838042, "author": "Jason T Featheringham", "author_id": 641553, "author_profile": "https://Stackoverflow.com/users/641553", "pm_score": -1, "selected": false, "text": "function xml_encode( $var, $indent = false, $i = 0 ) {\n $version = \"1.0\";\n if ( !$i ) {\n $data = '<?xml version=\"1.0\"?>' . ( $indent ? \"\\r\\n\" : '' )\n . '<root vartype=\"' . gettype( $var ) . '\" xml_encode_version=\"'. $version . '\">' . ( $indent ? \"\\r\\n\" : '' );\n }\n else {\n $data = '';\n }\n\n foreach ( $var as $k => $v ) {\n $data .= ( $indent ? str_repeat( \"\\t\", $i ) : '' ) . '<var vartype=\"' .gettype( $v ) . '\" varname=\"' . htmlentities( $k ) . '\"';\n\n if($v == \"\") {\n $data .= ' />';\n }\n else {\n $data .= '>';\n if ( is_array( $v ) ) {\n $data .= ( $indent ? \"\\r\\n\" : '' ) . xml_encode( $v, $indent, $verbose, ($i + 1) ) . ( $indent ? str_repeat(\"\\t\", $i) : '' );\n }\n else if( is_object( $v ) ) {\n $data .= ( $indent ? \"\\r\\n\" : '' ) . xml_encode( json_decode( json_encode( $v ), true ), $indent, $verbose, ($i + 1)) . ($indent ? str_repeat(\"\\t\", $i) : '');\n }\n else {\n $data .= htmlentities( $v );\n }\n\n $data .= '</var>';\n }\n\n $data .= ($indent ? \"\\r\\n\" : '');\n }\n\n if ( !$i ) {\n $data .= '</root>';\n }\n\n return $data;\n}\n // sample object\n$tests = Array(\n \"stringitem\" => \"stringvalue\",\n \"integeritem\" => 1,\n \"floatitem\" => 1.00,\n \"arrayitems\" => Array(\"arrayvalue1\", \"arrayvalue2\"),\n \"hashitems\" => Array( \"hashkey1\" => \"hashkey1value\", \"hashkey2\" => \"hashkey2value\" ),\n \"literalnull\" => null,\n \"literalbool\" => json_decode( json_encode( 1 ) )\n);\n// add an objectified version of itself as a child\n$tests['objectitem'] = json_decode( json_encode( $tests ), false);\n\n// convert and output\necho xml_encode( $tests );\n\n/*\n// output:\n\n<?xml version=\"1.0\"?>\n<root vartype=\"array\" xml_encode_version=\"1.0\">\n<var vartype=\"integer\" varname=\"integeritem\">1</var>\n<var vartype=\"string\" varname=\"stringitem\">stringvalue</var>\n<var vartype=\"double\" varname=\"floatitem\">1</var>\n<var vartype=\"array\" varname=\"arrayitems\">\n <var vartype=\"string\" varname=\"0\">arrayvalue1</var>\n <var vartype=\"string\" varname=\"1\">arrayvalue2</var>\n</var>\n<var vartype=\"array\" varname=\"hashitems\">\n <var vartype=\"string\" varname=\"hashkey1\">hashkey1value</var>\n <var vartype=\"string\" varname=\"hashkey2\">hashkey2value</var>\n</var>\n<var vartype=\"NULL\" varname=\"literalnull\" />\n<var vartype=\"integer\" varname=\"literalbool\">1</var>\n<var vartype=\"object\" varname=\"objectitem\">\n <var vartype=\"string\" varname=\"stringitem\">stringvalue</var>\n <var vartype=\"integer\" varname=\"integeritem\">1</var>\n <var vartype=\"integer\" varname=\"floatitem\">1</var>\n <var vartype=\"array\" varname=\"arrayitems\">\n <var vartype=\"string\" varname=\"0\">arrayvalue1</var>\n <var vartype=\"string\" varname=\"1\">arrayvalue2</var>\n </var>\n <var vartype=\"array\" varname=\"hashitems\">\n <var vartype=\"string\" varname=\"hashkey1\">hashkey1value</var>\n <var vartype=\"string\" varname=\"hashkey2\">hashkey2value</var>\n </var>\n <var vartype=\"NULL\" varname=\"literalnull\" />\n <var vartype=\"integer\" varname=\"literalbool\">1</var>\n</var>\n</root>\n\n*/\n" }, { "answer_id": 15812814, "author": "Bulki S Maslom", "author_id": 1775844, "author_profile": "https://Stackoverflow.com/users/1775844", "pm_score": 2, "selected": false, "text": " class XMLSerializer {\n\n /**\n * \n * The most advanced method of serialization.\n * \n * @param mixed $obj => can be an objectm, an array or string. may contain unlimited number of subobjects and subarrays\n * @param string $wrapper => main wrapper for the xml\n * @param array (key=>value) $replacements => an array with variable and object name replacements\n * @param boolean $add_header => whether to add header to the xml string\n * @param array (key=>value) $header_params => array with additional xml tag params\n * @param string $node_name => tag name in case of numeric array key\n */\n public static function generateValidXmlFromMixiedObj($obj, $wrapper = null, $replacements=array(), $add_header = true, $header_params=array(), $node_name = 'node') \n {\n $xml = '';\n if($add_header)\n $xml .= self::generateHeader($header_params);\n if($wrapper!=null) $xml .= '<' . $wrapper . '>';\n if(is_object($obj))\n {\n $node_block = strtolower(get_class($obj));\n if(isset($replacements[$node_block])) $node_block = $replacements[$node_block];\n $xml .= '<' . $node_block . '>';\n $vars = get_object_vars($obj);\n if(!empty($vars))\n {\n foreach($vars as $var_id => $var)\n {\n if(isset($replacements[$var_id])) $var_id = $replacements[$var_id];\n $xml .= '<' . $var_id . '>';\n $xml .= self::generateValidXmlFromMixiedObj($var, null, $replacements, false, null, $node_name);\n $xml .= '</' . $var_id . '>';\n }\n }\n $xml .= '</' . $node_block . '>';\n }\n else if(is_array($obj))\n {\n foreach($obj as $var_id => $var)\n {\n if(!is_object($var))\n {\n if (is_numeric($var_id)) \n $var_id = $node_name;\n if(isset($replacements[$var_id])) $var_id = $replacements[$var_id]; \n $xml .= '<' . $var_id . '>'; \n } \n $xml .= self::generateValidXmlFromMixiedObj($var, null, $replacements, false, null, $node_name);\n if(!is_object($var))\n $xml .= '</' . $var_id . '>';\n }\n }\n else\n {\n $xml .= htmlspecialchars($obj, ENT_QUOTES);\n }\n\n if($wrapper!=null) $xml .= '</' . $wrapper . '>';\n\n return $xml;\n } \n\n /**\n * \n * xml header generator\n * @param array $params\n */\n public static function generateHeader($params = array())\n {\n $basic_params = array('version' => '1.0', 'encoding' => 'UTF-8');\n if(!empty($params))\n $basic_params = array_merge($basic_params,$params);\n\n $header = '<?xml';\n foreach($basic_params as $k=>$v)\n {\n $header .= ' '.$k.'='.$v;\n }\n $header .= ' ?>';\n return $header;\n } \n}\n" }, { "answer_id": 44852173, "author": "Siniša Dragičević Martinčić", "author_id": 1128527, "author_profile": "https://Stackoverflow.com/users/1128527", "pm_score": 0, "selected": false, "text": "serialize($object, $name = NULL, $prefix = FALSE) interface SerializeXml {\n\n public function hasAttributes();\n\n public function getAttributes();\n\n public function setAttributes($attribs = array());\n\n public function getNameOwerriden();\n\n public function isNameOwerriden();\n}\n\nabstract class SerializeXmlAbstract implements SerializeXml {\n\n protected $attributes;\n protected $nameOwerriden;\n\n function __construct($name = NULL) {\n $this->nameOwerriden = $name;\n }\n\n public function getAttributes() {\n return $this->attributes;\n }\n\n public function getNameOwerriden() {\n return $this->nameOwerriden;\n }\n\n public function setAttributes($attribs = array()) {\n $this->attributes = $attribs;\n }\n\n public function hasAttributes() {\n return (is_array($this->attributes) && count($this->attributes) > 0) ? TRUE : FALSE;\n }\n\n public function isNameOwerriden() {\n return $this->nameOwerriden != NULL ? TRUE : FALSE;\n }\n\n}\n\nabstract class Entity_list extends SplObjectStorage {\n\n protected $_listItemType;\n\n public function __construct($type) {\n $this->setListItemType($type);\n }\n\n private function setListItemType($param) {\n $this->_listItemType = $param;\n }\n\n public function detach($object) {\n if ($object instanceOf $this->_listItemType) {\n parent::detach($object);\n }\n }\n\n public function attach($object, $data = null) {\n if ($object instanceOf $this->_listItemType) {\n parent::attach($object, $data);\n }\n }\n\n}\n\nabstract class Array_list extends SerializeXmlAbstract {\n\n protected $_listItemType;\n protected $_items;\n\n public function __construct() {\n //$this->setListItemType($type);\n $this->_items = new SplObjectStorage();\n }\n\n protected function setListItemType($param) {\n $this->_listItemType = $param;\n }\n\n public function getArray() {\n $return = array();\n $this->_items->rewind();\n while ($this->_items->valid()) {\n $return[] = $this->_items->current();\n $this->_items->next();\n }\n // print_r($return);\n return $return;\n }\n\n public function detach($object) {\n if ($object instanceOf $this->_listItemType) {\n if (in_array($this->_items->contains($object))) {\n $this->_items->detach($object);\n }\n }\n }\n\n public function attachItem($ob) {\n $this->_items->attach($ob);\n }\n\n}\n\nclass Object2xml {\n\n public $rootPrefix = \"ernm\";\n private $addPrefix;\n public $xml;\n\n public function serialize($object, $name = NULL, $prefix = FALSE) {\n if ($object instanceof SerializeXml) {\n $this->xml = new DOMDocument('1.0', 'utf-8');\n $this->xml->appendChild($this->object2xml($object, $name, TRUE));\n $this->xml->formatOutput = true;\n echo $this->xml->saveXML();\n } else {\n die(\"Not implement SerializeXml interface\");\n }\n }\n\n protected function object2xml(SerializeXmlAbstract $object, $nodeName = NULL, $prefix = null) {\n $single = property_exists(get_class($object), \"value\");\n $nName = $nodeName != NULL ? $nodeName : get_class($object);\n\n if ($prefix) {\n $nName = $this->rootPrefix . \":\" . $nName;\n }\n if ($single) {\n $ref = $this->xml->createElement($nName);\n } elseif (is_object($object)) {\n if ($object->isNameOwerriden()) {\n $nodeName = $object->getNameOwerriden();\n }\n $ref = $this->xml->createElement($nName);\n if ($object->hasAttributes()) {\n foreach ($object->getAttributes() as $key => $value) {\n $ref->setAttribute($key, $value);\n }\n }\n foreach (get_object_vars($object) as $n => $prop) {\n switch (gettype($prop)) {\n case \"object\":\n if ($prop instanceof SplObjectStorage) {\n $ref->appendChild($this->handleList($n, $prop));\n } elseif ($prop instanceof Array_list) {\n $node = $this->object2xml($prop);\n foreach ($object->ResourceGroup->getArray() as $key => $value) {\n $node->appendChild($this->object2xml($value));\n }\n $ref->appendChild($node);\n } else {\n $ref->appendChild($this->object2xml($prop));\n }\n break;\n default :\n if ($prop != null) {\n $ref->appendChild($this->xml->createElement($n, $prop));\n }\n break;\n }\n }\n } elseif (is_array($object)) {\n foreach ($object as $value) {\n $ref->appendChild($this->object2xml($value));\n }\n }\n return $ref;\n }\n\n private function handleList($name, SplObjectStorage $param, $nodeName = NULL) {\n $lst = $this->xml->createElement($nodeName == NULL ? $name : $nodeName);\n $param->rewind();\n while ($param->valid()) {\n if ($param->current() != null) {\n $lst->appendChild($this->object2xml($param->current()));\n }\n $param->next();\n }\n return $lst;\n }\n}\n <InsertMessage priority=\"high\">\n <NodeSimpleValue firstAttrib=\"first\" secondAttrib=\"second\">simple value</NodeSimpleValue>\n <Arrarita>\n <Title>PHP OOP is great</Title>\n <SequenceNumber>1</SequenceNumber>\n <Child>\n <FirstChild>Jimmy</FirstChild>\n </Child>\n <Child2>\n <FirstChild>bird</FirstChild>\n </Child2>\n </Arrarita>\n <ThirdChild>\n <NodeWithChilds>\n <FirstChild>John</FirstChild>\n <ThirdChild>James</ThirdChild>\n </NodeWithChilds>\n <NodeWithChilds>\n <FirstChild>DomDocument</FirstChild>\n <SecondChild>SplObjectStorage</SecondChild>\n </NodeWithChilds>\n </ThirdChild>\n</InsertMessage>\n class NodeWithArrayList extends Array_list {\n\n public $Title;\n public $SequenceNumber;\n\n public function __construct($name = NULL) {\n echo $name;\n parent::__construct($name);\n }\n\n}\n\nclass EntityListNode extends Entity_list {\n\n public function __construct($name = NULL) {\n parent::__construct($name);\n }\n\n}\n\nclass NodeWithChilds extends SerializeXmlAbstract {\n\n public $FirstChild;\n public $SecondChild;\n public $ThirdChild;\n\n public function __construct($name = NULL) {\n parent::__construct($name);\n }\n\n}\n\nclass NodeSimpleValue extends SerializeXmlAbstract {\n\n protected $value;\n\n public function getValue() {\n return $this->value;\n }\n\n public function setValue($value) {\n $this->value = $value;\n }\n\n public function __construct($name = NULL) {\n parent::__construct($name);\n }\n}\n $firstChild = new NodeSimpleValue(\"firstChild\");\n$firstChild->setValue( \"simple value\" );\n$firstChild->setAttributes(array(\"firstAttrib\" => \"first\", \"secondAttrib\" => \"second\"));\n\n$secondChild = new NodeWithArrayList(\"Arrarita\"); \n$secondChild->Title = \"PHP OOP is great\";\n$secondChild->SequenceNumber = 1; \n\n\n$firstListItem = new NodeWithChilds();\n$firstListItem->FirstChild = \"John\";\n$firstListItem->ThirdChild = \"James\";\n\n$firstArrayItem = new NodeWithChilds(\"Child\");\n$firstArrayItem->FirstChild = \"Jimmy\";\n\n$SecondArrayItem = new NodeWithChilds(\"Child2\"); \n$SecondArrayItem->FirstChild = \"bird\";\n\n$secondListItem = new NodeWithChilds();\n$secondListItem->FirstChild = \"DomDocument\";\n$secondListItem->SecondChild = \"SplObjectStorage\";\n\n\n$secondChild->attachItem($firstArrayItem);\n$secondChild->attachItem($SecondArrayItem);\n\n$list = new EntityListNode(\"NodeWithChilds\");\n$list->attach($firstListItem);\n$list->attach($secondListItem);\n\n\n\n$message = New NodeWithChilds(\"InsertMessage\");\n$message->setAttributes(array(\"priority\" => \"high\"));\n$message->FirstChild = $firstChild;\n$message->SecondChild = $secondChild;\n$message->ThirdChild = $list;\n\n\n$object2xml = new Object2xml();\n$object2xml->serialize($message, \"xml\", TRUE);\n" }, { "answer_id": 47074230, "author": "user3175253", "author_id": 3175253, "author_profile": "https://Stackoverflow.com/users/3175253", "pm_score": 1, "selected": false, "text": "class XMLSerializer {\n\n /**\n * Get object class name without namespace\n * @param object $object Object to get class name from\n * @return string Class name without namespace\n */\n private static function GetClassNameWithoutNamespace($object) {\n $class_name = get_class($object);\n return end(explode('\\\\', $class_name));\n }\n\n /**\n * Converts object to XML compatible with .NET XmlSerializer.Deserialize \n * @param type $object Object to serialize\n * @param type $root_node Root node name (if null, objects class name is used)\n * @return string XML string\n */\n public static function Serialize($object, $root_node = null) {\n $xml = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>';\n if (!$root_node) {\n $root_node = self::GetClassNameWithoutNamespace($object);\n }\n $xml .= '<' . $root_node . ' xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">';\n $xml .= self::SerializeNode($object);\n $xml .= '</' . $root_node . '>';\n return $xml;\n }\n\n /**\n * Create XML node from object property\n * @param mixed $node Object property\n * @param string $parent_node_name Parent node name\n * @param bool $is_array_item Is this node an item of an array?\n * @return string XML node as string\n * @throws Exception\n */\n private static function SerializeNode($node, $parent_node_name = false, $is_array_item = false) {\n $xml = '';\n if (is_object($node)) {\n $vars = get_object_vars($node);\n } else if (is_array($node)) {\n $vars = $node;\n } else {\n throw new Exception('Coś poszło nie tak');\n }\n\n foreach ($vars as $k => $v) {\n if (is_object($v)) {\n $node_name = ($parent_node_name ? $parent_node_name : self::GetClassNameWithoutNamespace($v));\n if (!$is_array_item) {\n $node_name = $k;\n }\n $xml .= '<' . $node_name . '>';\n $xml .= self::SerializeNode($v);\n $xml .= '</' . $node_name . '>';\n } else if (is_array($v)) {\n $xml .= '<' . $k . '>';\n if (count($v) > 0) {\n if (is_object(reset($v))) {\n $xml .= self::SerializeNode($v, self::GetClassNameWithoutNamespace(reset($v)), true);\n } else {\n $xml .= self::SerializeNode($v, gettype(reset($v)), true);\n }\n } else {\n $xml .= self::SerializeNode($v, false, true);\n }\n $xml .= '</' . $k . '>';\n } else {\n $node_name = ($parent_node_name ? $parent_node_name : $k);\n if ($v === null) {\n continue;\n } else {\n $xml .= '<' . $node_name . '>';\n if (is_bool($v)) {\n $xml .= $v ? 'true' : 'false';\n } else {\n $xml .= htmlspecialchars($v, ENT_QUOTES);\n }\n $xml .= '</' . $node_name . '>';\n }\n }\n }\n return $xml;\n }\n}\n class GetProductsCommandResult {\n public $description;\n public $Errors;\n}\n\nclass Error {\n public $id;\n public $error;\n}\n\n$obj = new GetProductsCommandResult();\n$obj->description = \"Teścik\";\n$obj->Errors = array();\n$obj->Errors[0] = new Error();\n$obj->Errors[0]->id = 666;\n$obj->Errors[0]->error = \"Sth\";\n$obj->Errors[1] = new Error();\n$obj->Errors[1]->id = 666;\n$obj->Errors[1]->error = null;\n\n\n$xml = XMLSerializer::Serialize($obj);\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<GetProductsCommandResult xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n <description>Teścik</description>\n <Errors>\n <Error>\n <id>666</id>\n <error>Sth</error>\n </Error>\n <Error>\n <id>666</id>\n </Error>\n </Errors>\n</GetProductsCommandResult>\n" }, { "answer_id": 52349574, "author": "tyrodeveloper", "author_id": 3204174, "author_profile": "https://Stackoverflow.com/users/3204174", "pm_score": 0, "selected": false, "text": "private function ReadProperty($xmlElement, $object) {\n foreach ($object as $key => $value) {\n if ($value != null) {\n if (is_object($value)) {\n $element = $this->xml->createElement($key);\n $this->ReadProperty($element, $value);\n $xmlElement->AppendChild($element);\n } elseif (is_array($value)) {\n $this->ReadProperty($xmlElement, $value);\n } else {\n $this->AddAttribute($xmlElement, $key, $value);\n }\n }\n }\n}\n" }, { "answer_id": 59648689, "author": "Andrew Ramshaw", "author_id": 10555044, "author_profile": "https://Stackoverflow.com/users/10555044", "pm_score": 0, "selected": false, "text": "class XMLSerializer {\n private $OpenTag = \"<\";\n private $CloseTag = \">\";\n private $BackSlash = \"/\";\n public $Root = \"root\";\n\n public function __construct() {\n }\n\n private function Array_To_XML($array, $arrayElementName = \"element_\", $xmlString = \"\")\n {\n if($xmlString === \"\")\n {\n $xmlString = \"{$this->OpenTag}{$this->Root}{$this->CloseTag}\";\n }\n $startTag = \"{$this->OpenTag}{$arrayElementName}{$this->CloseTag}\";\n $xmlString .= $startTag;\n foreach($array as $key => $value){\n if(gettype($value) === \"string\" || gettype($value) === \"boolean\" || gettype($value) === \"integer\" || gettype($value) === \"double\" || gettype($value) === \"float\")\n {\n $elementStartTag = \"{$this->OpenTag}{$arrayElementName}_{$key}{$this->CloseTag}\";\n $elementEndTag = \"{$this->OpenTag}{$this->BackSlash}{$arrayElementName}_{$key}{$this->CloseTag}\";\n $xmlString .= \"{$elementStartTag}{$value}{$elementEndTag}\";\n continue;\n }\n else if(gettype($value) === \"array\")\n {\n $xmlString = $this->Array_To_XML($value, $arrayElementName, $xmlString);\n continue;\n }\n else if(gettype($value) === \"object\")\n {\n $xmlString = $this->Object_To_XML($value, $xmlString);\n continue;\n }\n else\n { \n continue;\n }\n }\n $endTag = \"{$this->OpenTag}{$this->BackSlash}{$arrayElementName}{$this->CloseTag}\";\n $xmlString .= $endTag;\n return $xmlString;\n }\n\n private function Object_To_XML($objElement, $xmlString = \"\")\n {\n if($xmlString === \"\")\n {\n $xmlString = \"{$this->OpenTag}{$this->Root}{$this->CloseTag}\";\n }\n foreach($objElement as $key => $value){\n if(gettype($value) !== \"array\" && gettype($value) !== \"object\")\n {\n $startTag = \"{$this->OpenTag}{$key}{$this->CloseTag}\";\n $endTag = \"{$this->OpenTag}{$this->BackSlash}{$key}{$this->CloseTag}\";\n $xmlString .= \"{$startTag}{$value}{$endTag}\";\n continue;\n }\n else if(gettype($value) === \"array\")\n {\n $xmlString = $this->Array_To_XML($value, $key, $xmlString);\n continue;\n }\n else if(gettype($value) === \"object\")\n {\n $xmlString = $this->Object_To_XML($value, $xmlString);\n continue;\n }\n else\n { \n continue;\n }\n }\n return $xmlString;\n }\n\n public function Serialize_Object($element, $xmlString = \"\")\n {\n $endTag = \"{$this->OpenTag}{$this->BackSlash}{$this->Root}{$this->CloseTag}\";\n return \"{$this->Object_To_XML($element, $xmlString)}{$endTag}\";\n }\n\n public function Serialize_Array($element, $xmlString = \"\")\n {\n $endTag = \"{$this->OpenTag}{$this->BackSlash}{$this->Root}{$this->CloseTag}\";\n return \"{$this->Array_To_XML($element, $xmlString)}{$endTag}\";\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
137,031
<p>How can I determine if I have write permission on a remote machine in my intranet using C# in .Net?</p>
[ { "answer_id": 138226, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "bool hasWriteAccess = true;\nstring remoteFileName = \"\\\\server\\share\\file.name\"\n\ntry\n{\n createRemoteFile(remoteFileName); \n}\ncatch (SystemSecurityException)\n{\n hasWriteAccess = false; \n}\n\nif (File.Exists(remoteFileName))\n{\n File.Delete(remoteFileName);\n}\n\nreturn hasWriteAccess;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
137,038
<p>How does one do this?</p> <p>If I want to analyze how something is getting compiled, how would I get the emitted assembly code?</p>
[ { "answer_id": 137044, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 5, "selected": false, "text": "g++ -S main.cpp\n gcc gcc -S main.c\n" }, { "answer_id": 137047, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "gcc -S program.c\n" }, { "answer_id": 137056, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 4, "selected": false, "text": "gcc -S #!/usr/bin/perl -w\n$ptr='(BYTE|WORD|DWORD|QWORD|XMMWORD) PTR ';\n$reg='(?:[er]?(?:[abcd]x|[sd]i|[sb]p)|[abcd][hl]|r1?[0-589][dwb]?|mm[0-7]|xmm1?[0-9])';\nopen FH, '-|', '/usr/bin/objdump', '-w', '-M', 'intel', @ARGV or die;\n$prev = \"\";\nwhile(<FH>){\n if(/$ptr/o) {\n s/$ptr(\\[[^\\[\\]]+\\],$reg)/$2/o or\n s/($reg,)$ptr(\\[[^\\[\\]]+\\])/$1$3/o or\n s/$ptr/lc $1/oe;\n }\n if($prev =~ /\\t(repz )?ret / and\n $_ =~ /\\tnop |\\txchg *ax,ax$/) {\n # drop this line\n } else {\n print $prev;\n $prev = $_;\n }\n}\nprint $prev;\nclose FH;\n gcc -S" }, { "answer_id": 137074, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 10, "selected": true, "text": "gcc g++ gcc -S helloworld.c\n helloworld.s -o - gcc -S -o my_asm_output.s helloworld.c\n --disassemble -d objdump -S --disassemble helloworld > helloworld.dump\n -S file helloworld objdump -rwC -Mintel objdump -drwC -Mintel -S foo.o | less -r .o 00 00 00 00" }, { "answer_id": 137354, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "-S -O0 -O2" }, { "answer_id": 137479, "author": "PhirePhly", "author_id": 20082, "author_profile": "https://Stackoverflow.com/users/20082", "pm_score": 8, "selected": false, "text": "# Create assembler code:\ng++ -S -fverbose-asm -g -O2 test.cc -o test.s\n\n# Create asm interlaced with source lines:\nas -alhnd test.s > test.lst\n" }, { "answer_id": 7871911, "author": "mcandre", "author_id": 350106, "author_profile": "https://Stackoverflow.com/users/350106", "pm_score": 3, "selected": false, "text": "llvm-gcc -emit-llvm -S hello.c\n" }, { "answer_id": 19083877, "author": "Cr McDonough", "author_id": 2829396, "author_profile": "https://Stackoverflow.com/users/2829396", "pm_score": 6, "selected": false, "text": "g++ -g -O -Wa,-aslh horton_ex2_05.cpp >list.txt\n cd C:\\gpp_code\ng++ -g -O -Wa,-aslh horton_ex2_05.cpp > list.txt\n horton_ex2_05.cpp: In function `int main()':\nhorton_ex2_05.cpp:92: warning: assignment to `int' from `double'\n 16:horton_ex2_05.cpp **** using std::setw;\n 17:horton_ex2_05.cpp ****\n 18:horton_ex2_05.cpp **** void disp_Time_Line (void);\n 19:horton_ex2_05.cpp ****\n 20:horton_ex2_05.cpp **** int main(void)\n 21:horton_ex2_05.cpp **** {\n 164 %ebp\n 165 subl $128,%esp\n?GAS LISTING C:\\DOCUME~1\\CRAIGM~1\\LOCALS~1\\Temp\\ccx52rCc.s\n166 0128 55 call ___main\n167 0129 89E5 .stabn 68,0,21,LM2-_main\n168 012b 81EC8000 LM2:\n168 0000\n169 0131 E8000000 LBB2:\n169 00\n170 .stabn 68,0,25,LM3-_main\n171 LM3:\n172 movl $0,-16(%ebp)\n" }, { "answer_id": 48969827, "author": "Ashutosh K Singh", "author_id": 7394522, "author_profile": "https://Stackoverflow.com/users/7394522", "pm_score": 2, "selected": false, "text": "cd C:\\gcc\ngcc -S complete path of the C file ENTER\n gcc -S D:\\Aa_C_Certified\\alternate_letters.c\n cpp filename.s ENTER\n cpp alternate_letters.s <enter>\n" }, { "answer_id": 53513204, "author": "Abhishek D K", "author_id": 7303415, "author_profile": "https://Stackoverflow.com/users/7303415", "pm_score": 2, "selected": false, "text": "gcc main.c // 'main.c' source file\ngdb a.exe // 'gdb a.out' in Linux\n disass main // Note here 'main' is a function\n // Similarly, it can be done for other functions.\n" }, { "answer_id": 53927419, "author": "Himanshu Pal", "author_id": 10697722, "author_profile": "https://Stackoverflow.com/users/10697722", "pm_score": 3, "selected": false, "text": "gcc -S program.c && gcc program.c -o output\n" }, { "answer_id": 56801917, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "gcc -save-temps -c -o main.o main.c\n #define INC 1\n\nint myfunc(int i) {\n return i + INC;\n}\n main.o main.i # 1 \"main.c\"\n# 1 \"<built-in>\"\n# 1 \"<command-line>\"\n# 31 \"<command-line>\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 32 \"<command-line>\" 2\n# 1 \"main.c\"\n\n\nint myfunc(int i) {\n return i + 1;\n}\n main.s .file \"main.c\"\n .text\n .globl myfunc\n .type myfunc, @function\nmyfunc:\n.LFB0:\n .cfi_startproc\n pushq %rbp\n .cfi_def_cfa_offset 16\n .cfi_offset 6, -16\n movq %rsp, %rbp\n .cfi_def_cfa_register 6\n movl %edi, -4(%rbp)\n movl -4(%rbp), %eax\n addl $1, %eax\n popq %rbp\n .cfi_def_cfa 7, 8\n ret\n .cfi_endproc\n.LFE0:\n .size myfunc, .-myfunc\n .ident \"GCC: (Ubuntu 8.3.0-6ubuntu1) 8.3.0\"\n .section .note.GNU-stack,\"\",@progbits\n -save-temps=obj\n -o -v gcc -save-temps -c -o main.o -v main.c\n /tmp /usr/lib/gcc/x86_64-linux-gnu/8/cc1 -E -quiet -v -imultiarch x86_64-linux-gnu main.c -mtune=generic -march=x86-64 -fpch-preprocess -fstack-protector-strong -Wformat -Wformat-security -o main.i\n/usr/lib/gcc/x86_64-linux-gnu/8/cc1 -fpreprocessed main.i -quiet -dumpbase main.c -mtune=generic -march=x86-64 -auxbase-strip main.o -version -fstack-protector-strong -Wformat -Wformat-security -o main.s\nas -v --64 -o main.o main.s\n make help\n make main.s\n Compiling C source to assembly CMakeFiles/main.dir/main.c.s\n/usr/bin/cc -S /home/ciro/hello/main.c -o CMakeFiles/main.dir/main.c.s\n CMakeFiles/main.dir/main.c.s" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
137,040
<p>I have a problem which requires me to parse several log files from a remote machine. There are a few complications: 1) The file may be in use 2) The files can be quite large (100mb+) 3) Each entry may be multi-line</p> <p>To solve the in-use issue, I need to copy it first. I'm currently copying it directly from the remote machine to the local machine, and parsing it there. That leads to issue 2. Since the files are quite large copying it locally can take quite a while.</p> <p>To enhance parsing time, I'd like to make the parser multi-threaded, but that makes dealing with multi-lined entries a bit trickier. </p> <p>The two main issues are: 1) How do i speed up the file transfer (Compression?, Is transferring locally even neccessary?, Can I read an in use file some other way?) 2) How do i deal with multi-line entries when splitting up the lines among threads?</p> <p>UPDATE: The reason I didnt do the obvious parse on the server reason is that I want to have as little cpu impact as possible. I don't want to affect the performance of the system im testing.</p>
[ { "answer_id": 138165, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "new FileStream(\"logfile\", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2712/" ]
137,043
<p>When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this:</p> <pre><code> &lt;table&gt; &lt;tr&gt; &lt;td&gt;blah&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>...into this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; blah &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 137697, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "M-x tidy-buffer\n" }, { "answer_id": 144938, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 6, "selected": true, "text": ".html html-mode nxml-mode nxml-mode nxml-mode nxml-mode M-x nxml-mode\n C-h i g (nxml-mode) RET\n nxml-mode <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n<body>\n<table>\n <tr>\n<td>blah</td></tr></table>\n</body>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n <body>\n <table>\n <tr>\n <td>blah</td></tr></table>\n</body>\n</html>\n C-j defun" }, { "answer_id": 4146331, "author": "nevcx", "author_id": 503449, "author_profile": "https://Stackoverflow.com/users/503449", "pm_score": 3, "selected": false, "text": " M-x replace-regexp\n\n \\(</[^>]+>\\)\n\n \\1C-q-j\n C-x h\n M-x indent-region\n" }, { "answer_id": 6247579, "author": "vava", "author_id": 6258, "author_profile": "https://Stackoverflow.com/users/6258", "pm_score": 7, "selected": false, "text": "sgml-pretty-print indent-for-tab sgml-pretty-print indent-for-tab" }, { "answer_id": 6255409, "author": "jtahlborn", "author_id": 552759, "author_profile": "https://Stackoverflow.com/users/552759", "pm_score": 3, "selected": false, "text": "(defun jta-reformat-xml ()\n \"Reformats xml to make it readable (respects current selection).\"\n (interactive)\n (save-excursion\n (let ((beg (point-min))\n (end (point-max)))\n (if (and mark-active transient-mark-mode)\n (progn\n (setq beg (min (point) (mark)))\n (setq end (max (point) (mark))))\n (widen))\n (setq end (copy-marker end t))\n (goto-char beg)\n (while (re-search-forward \">\\\\s-*<\" end t)\n (replace-match \">\\n<\" t t))\n (goto-char beg)\n (indent-region beg end nil))))\n" }, { "answer_id": 7436381, "author": "Geoff", "author_id": 446564, "author_profile": "https://Stackoverflow.com/users/446564", "pm_score": 2, "selected": false, "text": "M-|\nShell command on region: xmllint --format -\n" }, { "answer_id": 11020114, "author": "user1454331", "author_id": 1454331, "author_profile": "https://Stackoverflow.com/users/1454331", "pm_score": 1, "selected": false, "text": "tidy -i -m <<file_name>> -m tidy -i -o <<tidied_file_name>> <<untidied_file_name>> -i .tidyrc indent: auto\nindent-spaces: 2\nwrap: 72\nmarkup: yes\noutput-xml: no\ninput-xml: no\nshow-warnings: yes\nnumeric-entities: yes\nquote-marks: yes\nquote-nbsp: yes\nquote-ampersand: no\nbreak-before-br: no\nuppercase-tags: no\nuppercase-attributes: no\n tidy -o <<tidied_file_name>> <<untidied_file_name>> man tidy" }, { "answer_id": 27183016, "author": "abhillman", "author_id": 3622198, "author_profile": "https://Stackoverflow.com/users/3622198", "pm_score": 3, "selected": false, "text": "C-x h (setq transient-mark-mode t) .emacs M-x indent-region C-M-q C-M-q js-mode html-mode nxml-mode C-M-q" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
137,054
<p>How can I validate that my ASPNET AJAX installation is correct.</p> <p>I have Visual Studio 2008 and had never previously installed any AJAX version.</p> <p>My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior.</p> <p>I tried installing AJAX from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&amp;displaylang=en" rel="nofollow noreferrer">MSDN</a> followed by an IISRESET yet still it is still not working properly.</p> <p>What can I check to diagnose the problem?</p> <p><strong>Update:</strong> When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler:</p> <pre><code>http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&amp;t=633564733834698722 http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&amp;t=ffffffff867086f6 http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&amp;t=ffffffff867086f6 </code></pre> <p>but when I run within IIS i only get this single request :</p> <pre><code>http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&amp;t=ffffffff867086f6 </code></pre> <p>Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests.</p>
[ { "answer_id": 137697, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "M-x tidy-buffer\n" }, { "answer_id": 144938, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 6, "selected": true, "text": ".html html-mode nxml-mode nxml-mode nxml-mode nxml-mode M-x nxml-mode\n C-h i g (nxml-mode) RET\n nxml-mode <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n<body>\n<table>\n <tr>\n<td>blah</td></tr></table>\n</body>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head></head>\n <body>\n <table>\n <tr>\n <td>blah</td></tr></table>\n</body>\n</html>\n C-j defun" }, { "answer_id": 4146331, "author": "nevcx", "author_id": 503449, "author_profile": "https://Stackoverflow.com/users/503449", "pm_score": 3, "selected": false, "text": " M-x replace-regexp\n\n \\(</[^>]+>\\)\n\n \\1C-q-j\n C-x h\n M-x indent-region\n" }, { "answer_id": 6247579, "author": "vava", "author_id": 6258, "author_profile": "https://Stackoverflow.com/users/6258", "pm_score": 7, "selected": false, "text": "sgml-pretty-print indent-for-tab sgml-pretty-print indent-for-tab" }, { "answer_id": 6255409, "author": "jtahlborn", "author_id": 552759, "author_profile": "https://Stackoverflow.com/users/552759", "pm_score": 3, "selected": false, "text": "(defun jta-reformat-xml ()\n \"Reformats xml to make it readable (respects current selection).\"\n (interactive)\n (save-excursion\n (let ((beg (point-min))\n (end (point-max)))\n (if (and mark-active transient-mark-mode)\n (progn\n (setq beg (min (point) (mark)))\n (setq end (max (point) (mark))))\n (widen))\n (setq end (copy-marker end t))\n (goto-char beg)\n (while (re-search-forward \">\\\\s-*<\" end t)\n (replace-match \">\\n<\" t t))\n (goto-char beg)\n (indent-region beg end nil))))\n" }, { "answer_id": 7436381, "author": "Geoff", "author_id": 446564, "author_profile": "https://Stackoverflow.com/users/446564", "pm_score": 2, "selected": false, "text": "M-|\nShell command on region: xmllint --format -\n" }, { "answer_id": 11020114, "author": "user1454331", "author_id": 1454331, "author_profile": "https://Stackoverflow.com/users/1454331", "pm_score": 1, "selected": false, "text": "tidy -i -m <<file_name>> -m tidy -i -o <<tidied_file_name>> <<untidied_file_name>> -i .tidyrc indent: auto\nindent-spaces: 2\nwrap: 72\nmarkup: yes\noutput-xml: no\ninput-xml: no\nshow-warnings: yes\nnumeric-entities: yes\nquote-marks: yes\nquote-nbsp: yes\nquote-ampersand: no\nbreak-before-br: no\nuppercase-tags: no\nuppercase-attributes: no\n tidy -o <<tidied_file_name>> <<untidied_file_name>> man tidy" }, { "answer_id": 27183016, "author": "abhillman", "author_id": 3622198, "author_profile": "https://Stackoverflow.com/users/3622198", "pm_score": 3, "selected": false, "text": "C-x h (setq transient-mark-mode t) .emacs M-x indent-region C-M-q C-M-q js-mode html-mode nxml-mode C-M-q" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
137,060
<p>I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:</p> <p><a href="http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern" rel="nofollow noreferrer">http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern</a></p> <p>Is this a design smell? Should I impose a limit on this number? </p> <p>I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)</p> <p>All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.</p>
[ { "answer_id": 8592706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "ParserBuilderFactoryImpl(ParserFactory psF) {\n...\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12048/" ]
137,089
<p>I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:</p> <pre><code>#include &lt;boost/signal.hpp&gt; typedef boost::signal&lt;void (void)&gt; Event; int main(int argc, char* argv[]) { Event e; return 0; } </code></pre> <p>Thanks!</p> <p>Edit: This was Boost 1.36.0 compiled with Visual Studio 2008 w/ SP1. Boost::filesystem, like boost::signal also has a library that must be linked in, and it seems to work fine. All the other boost libraries I use are headers-only, I believe.</p>
[ { "answer_id": 3803104, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 1, "selected": false, "text": "_HAS_ITERATOR_DEBUGGING _SECURE_SCL" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
137,091
<p>At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion:</p> <pre><code>function daysToTimestamp(days) { return Math.round(+days * 86400); } </code></pre> <p>By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why?</p>
[ { "answer_id": 137122, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": ">>> import time\n>>> time.gmtime(1199059200)\n(2007, 12, 31, 0, 0, 0, 0, 365, 0)\n time_t >>> time.localtime(1199098800)\n(2008, 1, 1, 0, 0, 0, 1, 1, 1)\n >>> time.gmtime(1199145600)\n(2008, 1, 1, 0, 0, 0, 1, 1, 0)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
137,102
<p>What's the best tool for viewing and editing a merge in Git? I'd like to get a 3-way merge view, with "mine", "theirs" and "ancestor" in separate panels, and a fourth "output" panel.</p> <p>Also, instructions for invoking said tool would be great. (I still haven't figure out how to start kdiff3 in such a way that it doesn't give me an error.)</p> <p>My OS is Ubuntu.</p>
[ { "answer_id": 299335, "author": "user35149", "author_id": 35149, "author_profile": "https://Stackoverflow.com/users/35149", "pm_score": 3, "selected": false, "text": "git mergetool -t=<tool> --tool=<tool> git config merge.tool <tool>" }, { "answer_id": 337717, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "$ diffuse \"mine\" \"output\" \"theirs\"\n" }, { "answer_id": 2235841, "author": "Evgeny", "author_id": 11414, "author_profile": "https://Stackoverflow.com/users/11414", "pm_score": 7, "selected": false, "text": "git mergetool git config --global merge.tool p4merge\n git config --global mergetool.p4merge.cmd p4merge '$BASE $LOCAL $REMOTE $MERGED'\n git config --global mergetool.p4merge.trustExitCode false\n git difftool git config --global diff.tool p4merge\n git config --global difftool.p4merge.cmd p4merge '$LOCAL $REMOTE'\n $BASE" }, { "answer_id": 3642298, "author": "Armel", "author_id": 395344, "author_profile": "https://Stackoverflow.com/users/395344", "pm_score": 2, "selected": false, "text": "git mergetool" }, { "answer_id": 3839827, "author": "Andrew Wagner", "author_id": 139802, "author_profile": "https://Stackoverflow.com/users/139802", "pm_score": 5, "selected": false, "text": ":help vimdiff \n" }, { "answer_id": 45753889, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "opendiff" }, { "answer_id": 47592142, "author": "ephemerr", "author_id": 2656799, "author_profile": "https://Stackoverflow.com/users/2656799", "pm_score": 2, "selected": false, "text": "git config --global diff.tool diffuse\ngit config --global merge.tool kdiff3\n git difftool [BRANCH] -- [FILE or DIR]\n git mergetool" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21482/" ]
137,114
<p>Whats the best way to round in VBA Access?</p> <p>My current method utilizes the Excel method</p> <pre><code>Excel.WorksheetFunction.Round(... </code></pre> <p>But I am looking for a means that does not rely on Excel.</p>
[ { "answer_id": 137164, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 0, "selected": false, "text": "VBA.Round(1.23342, 2) // will return 1.23\n" }, { "answer_id": 137177, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 6, "selected": true, "text": "Round (12.55, 1) would return 12.6 (rounds up) \nRound (12.65, 1) would return 12.6 (rounds down) \nRound (12.75, 1) would return 12.8 (rounds up) \n" }, { "answer_id": 137217, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 1, "selected": false, "text": "return int(var + 0.5)\n" }, { "answer_id": 155710, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "1 place = INT(number x 10 + .5)/10\n3 places = INT(number x 1000 + .5)/1000\n If A > B Then MaxAB = A Else MaxAB = B" }, { "answer_id": 166302, "author": "Oli", "author_id": 15296, "author_profile": "https://Stackoverflow.com/users/15296", "pm_score": 2, "selected": false, "text": "Function roundit(value As Double, precision As Double) As Double\n roundit = Int(value / precision + 0.5) * precision\nEnd Function\n" }, { "answer_id": 266745, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": false, "text": " Debug.Print Round(19.955, 2)\n 'Answer: 19.95\n\n Debug.Print Format(19.955, \"#.00\")\n 'Answer: 19.96\n" }, { "answer_id": 586816, "author": "Will Rickards", "author_id": 290835, "author_profile": "https://Stackoverflow.com/users/290835", "pm_score": 1, "selected": false, "text": "bug ' -----------------------------------------------------------------------------\n' RoundPenny\n'\n' Description:\n' rounds currency amount to nearest penny\n'\n' Arguments:\n' strCurrency - string representation of currency value\n'\n' Dependencies:\n'\n' Notes:\n' based on RoundNear found here:\n' http://advisor.com/doc/08884\n'\n' History:\n' 04/14/2005 - WSR : created\n'\nFunction RoundPenny(ByVal strCurrency As String) As Currency\n\n Dim mnyDollars As Variant\n Dim decCents As Variant\n Dim decRight As Variant\n Dim lngDecPos As Long\n\n1 On Error GoTo RoundPenny_Error\n\n ' find decimal point\n2 lngDecPos = InStr(1, strCurrency, \".\")\n\n ' if there is a decimal point\n3 If lngDecPos > 0 Then\n\n ' take everything before decimal as dollars\n4 mnyDollars = CCur(Mid(strCurrency, 1, lngDecPos - 1))\n\n ' get amount after decimal point and multiply by 100 so cents is before decimal point\n5 decRight = CDec(CDec(Mid(strCurrency, lngDecPos)) / 0.01)\n\n ' get cents by getting integer portion\n6 decCents = Int(decRight)\n\n ' get leftover\n7 decRight = CDec(decRight - decCents)\n\n ' if leftover is equal to or above round threshold\n8 If decRight >= 0.5 Then\n\n9 RoundPenny = mnyDollars + ((decCents + 1) * 0.01)\n\n ' if leftover is less than round threshold\n10 Else\n\n11 RoundPenny = mnyDollars + (decCents * 0.01)\n\n12 End If\n\n ' if there is no decimal point\n13 Else\n\n ' return it\n14 RoundPenny = CCur(strCurrency)\n\n15 End If\n\n16 Exit Function\n\nRoundPenny_Error:\n\n17 Select Case Err.Number\n\n Case 6\n\n18 Err.Raise vbObjectError + 334, c_strComponent & \".RoundPenny\", \"Number '\" & strCurrency & \"' is too big to represent as a currency value.\"\n\n19 Case Else\n\n20 DisplayError c_strComponent, \"RoundPenny\"\n\n21 End Select\n\nEnd Function\n' ----------------------------------------------------------------------------- \n" }, { "answer_id": 1981091, "author": "John OQuin", "author_id": 241019, "author_profile": "https://Stackoverflow.com/users/241019", "pm_score": 0, "selected": false, "text": "BillWt = IIf([Weight]-Int([Weight])=0,[Weight],Int([Weight])+1)\n" }, { "answer_id": 22692373, "author": "user3469318", "author_id": 3469318, "author_profile": "https://Stackoverflow.com/users/3469318", "pm_score": 0, "selected": false, "text": "Function PennySplitR(amount As Double, Optional splitRange As Variant, Optional index As Integer = 0, Optional n As Integer = 0, Optional flip As Boolean = False) As Double\n' This Excel function takes either a range or an index to calculate how to \"evenly\" split up dollar amounts\n' when each split amount must be in pennies. The amounts might vary by a penny but the total of all the\n' splits will add up to the input amount.\n\n' Splits a dollar amount up either over a range or by index\n' Example for passing a range: set range $I$18:$K$21 to =PennySplitR($E$15,$I$18:$K$21) where $E$15 is the amount and $I$18:$K$21 is the range\n' it is intended that the element calling this function will be in the range\n' or to use an index and total items instead of a range: =PennySplitR($E$15,,index,N)\n' The flip argument is to swap rows and columns in calculating the index for the element in the range.\n\n' Thanks to: http://stackoverflow.com/questions/5559279/excel-cell-from-which-a-function-is-called for the application.caller.row hint.\nDim evenSplit As Double, spCols As Integer, spRows As Integer\nIf (index = 0 Or n = 0) Then\n spRows = splitRange.Rows.count\n spCols = splitRange.Columns.count\n n = spCols * spRows\n If (flip = False) Then\n index = (Application.Caller.Row - splitRange.Cells.Row) * spCols + Application.Caller.Column - splitRange.Cells.Column + 1\n Else\n index = (Application.Caller.Column - splitRange.Cells.Column) * spRows + Application.Caller.Row - splitRange.Cells.Row + 1\n End If\n End If\n If (n < 1) Then\n PennySplitR = 0\n Return\n Else\n evenSplit = amount / n\n If (index = 1) Then\n PennySplitR = Round(evenSplit, 2)\n Else\n PennySplitR = Round(evenSplit * index, 2) - Round(evenSplit * (index - 1), 2)\n End If\nEnd If\nEnd Function\n" }, { "answer_id": 23521993, "author": "Sidupac", "author_id": 2199867, "author_profile": "https://Stackoverflow.com/users/2199867", "pm_score": 0, "selected": false, "text": "Function RoundUp(Number As Variant)\n RoundUp = Int(-100 * Number) / -100\n If Round(Number, 2) = Number Then RoundUp = Number\nEnd Function\n Function RoundUp(Number As Variant, Optional RoundDownIfNegative As Boolean = False)\nOn Error GoTo err\nIf Number = 0 Then\nerr:\n RoundUp = 0\nElseIf RoundDownIfNegative And Number < 0 Then\n RoundUp = -1 * Int(-100 * (-1 * Number)) / -100\nElse\n RoundUp = Int(-100 * Number) / -100\nEnd If\nIf Round(Number, 2) = Number Then RoundUp = Number\nEnd Function\n" }, { "answer_id": 36966140, "author": "Gustav", "author_id": 3527297, "author_profile": "https://Stackoverflow.com/users/3527297", "pm_score": 2, "selected": false, "text": "' Common constants.\n'\nPublic Const Base10 As Double = 10\n\n' Rounds Value by 4/5 with count of decimals as specified with parameter NumDigitsAfterDecimals.\n'\n' Rounds to integer if NumDigitsAfterDecimals is zero.\n'\n' Rounds correctly Value until max/min value limited by a Scaling of 10\n' raised to the power of (the number of decimals).\n'\n' Uses CDec() for correcting bit errors of reals.\n'\n' Execution time is about 1µs.\n'\nPublic Function RoundMid( _\n ByVal Value As Variant, _\n Optional ByVal NumDigitsAfterDecimals As Long, _\n Optional ByVal MidwayRoundingToEven As Boolean) _\n As Variant\n\n Dim Scaling As Variant\n Dim Half As Variant\n Dim ScaledValue As Variant\n Dim ReturnValue As Variant\n\n ' Only round if Value is numeric and ReturnValue can be different from zero.\n If Not IsNumeric(Value) Then\n ' Nothing to do.\n ReturnValue = Null\n ElseIf Value = 0 Then\n ' Nothing to round.\n ' Return Value as is.\n ReturnValue = Value\n Else\n Scaling = CDec(Base10 ^ NumDigitsAfterDecimals)\n\n If Scaling = 0 Then\n ' A very large value for Digits has minimized scaling.\n ' Return Value as is.\n ReturnValue = Value\n ElseIf MidwayRoundingToEven Then\n ' Banker's rounding.\n If Scaling = 1 Then\n ReturnValue = Round(Value)\n Else\n ' First try with conversion to Decimal to avoid bit errors for some reals like 32.675.\n ' Very large values for NumDigitsAfterDecimals can cause an out-of-range error \n ' when dividing.\n On Error Resume Next\n ScaledValue = Round(CDec(Value) * Scaling)\n ReturnValue = ScaledValue / Scaling\n If Err.Number <> 0 Then\n ' Decimal overflow.\n ' Round Value without conversion to Decimal.\n ReturnValue = Round(Value * Scaling) / Scaling\n End If\n End If\n Else\n ' Standard 4/5 rounding.\n ' Very large values for NumDigitsAfterDecimals can cause an out-of-range error \n ' when dividing.\n On Error Resume Next\n Half = CDec(0.5)\n If Value > 0 Then\n ScaledValue = Int(CDec(Value) * Scaling + Half)\n Else\n ScaledValue = -Int(-CDec(Value) * Scaling + Half)\n End If\n ReturnValue = ScaledValue / Scaling\n If Err.Number <> 0 Then\n ' Decimal overflow.\n ' Round Value without conversion to Decimal.\n Half = CDbl(0.5)\n If Value > 0 Then\n ScaledValue = Int(Value * Scaling + Half)\n Else\n ScaledValue = -Int(-Value * Scaling + Half)\n End If\n ReturnValue = ScaledValue / Scaling\n End If\n End If\n If Err.Number <> 0 Then\n ' Rounding failed because values are near one of the boundaries of type Double.\n ' Return value as is.\n ReturnValue = Value\n End If\n End If\n\n RoundMid = ReturnValue\n\nEnd Function\n" }, { "answer_id": 69890635, "author": "trs11", "author_id": 15078702, "author_profile": "https://Stackoverflow.com/users/15078702", "pm_score": 0, "selected": false, "text": "Public Function RoundUpDown(value, decimals, updown)\nIf IsNumeric(value) Then\n rValue = Round(value, decimals)\n rDec = 10 ^ (-(decimals))\n rDif = rValue - value\n If updown = \"down\" Then 'rounding for \"down\" explicitly.\n If rDif > 0 Then ' if the difference is more than 0, it rounded up.\n RoundUpDown = rValue - rDec\n ElseIf rDif < 0 Then ' if the difference is less than 0, it rounded down.\n RoundUpDown = rValue\n Else\n RoundUpDown = rValue\n End If\n Else 'rounding for anything thats not \"down\"\n If rDif > 0 Then ' if the difference is more than 0, it rounded up.\n RoundUpDown = rValue\n ElseIf rDif < 0 Then ' if the difference is less than 0, it rounded down.\n RoundUpDown = rValue + rDec\n Else\n RoundUpDown = rValue\n End If\n End If\n\nEnd If\n'RoundUpDown(value, decimals, updown) 'where updown is \"down\" if down. else rounds up. put this in your program.\nEnd Function\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
137,147
<p>For example</p> <pre><code>int f(int a) { ... return a &gt; 10; } </code></pre> <p>is that considered acceptable (not legal, I mean is it ``good code''), or should it always be in a conditional, like this</p> <pre><code>int f(int a) { ... if (a &gt; 10) return 1; else return 0; } </code></pre>
[ { "answer_id": 137185, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 2, "selected": false, "text": "bool f(int); boolean int int f(int) {\n ...\n const int res = (i>42) ? 1 : 0;\n return res;\n}\n if (expr == true)\n mybool = true ; \nelse \n mybool = false;\n mybool = expr;\n" }, { "answer_id": 137198, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 3, "selected": false, "text": " return (a > 10);\n" }, { "answer_id": 137222, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 4, "selected": false, "text": "return a > 10 ? 1 : 0;\n" }, { "answer_id": 140404, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 1, "selected": false, "text": "int x = i && ( j || k );" }, { "answer_id": 3359554, "author": "Roland Illig", "author_id": 225757, "author_profile": "https://Stackoverflow.com/users/225757", "pm_score": 1, "selected": false, "text": "int one(int x) { return (x > 42) ? 1 : 0; }\nint two(int x) { return x > 42; }\nint thr(int x) { if (x > 42) return 1; else return 0; }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,181
<p>I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used?</p>
[ { "answer_id": 137200, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 4, "selected": true, "text": "httpd -V\n httpd -h\n" }, { "answer_id": 14920292, "author": "babyromeo", "author_id": 544611, "author_profile": "https://Stackoverflow.com/users/544611", "pm_score": 0, "selected": false, "text": "if $ac_cs_silent; then\n exec 6>/dev/null\n ac_configure_extra_args=\"$ac_configure_extra_args --silent\"\nfi\n\nif $ac_cs_recheck; then\n set X /bin/sh **'./configure' '--enable-file-cache' '--enable-cache' '--enable-disk-cache' '--enable-mem-cache' '--enable-deflate' '--enable-expires' '--enable-headers' '--enable-usertrack' '--enable-cgi' '--enable-vhost-alias' '--enable-rewrite' '--enable-so' '--with-apr=/usr/local/apache/' '--with-apr-util=/usr/local/apache/' '--prefix=/usr/local/apache' '--with-mpm=worker' '--with-mysql=/var/lib/mysql' '--with-mysql-sock=/var/run/mysqld/mysqld.sock' '--enable-mods-shared=most' '--enable-ssl' 'CFLAGS=-Wall -O3 -ffast-math -frename-registers -mtune=corei7-avx' '--enable-modules=all' '--enable-proxy' '--enable-proxy-fcgi'** $ac_configure_extra_args --no-create --no-recursion\n shift\n $as_echo \"running CONFIG_SHELL=/bin/sh $*\" >&6\n CONFIG_SHELL='/bin/sh'\n export CONFIG_SHELL\n exec \"$@\"\nfi\n" }, { "answer_id": 23370616, "author": "kyle", "author_id": 1874154, "author_profile": "https://Stackoverflow.com/users/1874154", "pm_score": 3, "selected": false, "text": "#! /bin/sh\n#\n# Created by configure\n\n\"./configure\" \\\n\"--prefix=/usr/local/apache2\" \\\n\"--enable-so\" \\\n\"--enable-mods-shared=most\" \\\n\"--enable-ssl\" \\\n\"--with-mpm=worker\" \\\n\"--enable-cgi\" \\\n\"$@\"\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
137,182
<p>How do I launch Windows' <a href="https://en.wikipedia.org/wiki/Windows_Registry#Registry_editors" rel="noreferrer">RegEdit</a> with certain path located, like "<code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0</code>", so I don't have to do the clicking?</p> <p>What's the command line argument to do this? Or is there a place to find the explanation of RegEdit's switches?</p>
[ { "answer_id": 137220, "author": "The Hoss", "author_id": 9469, "author_profile": "https://Stackoverflow.com/users/9469", "pm_score": 3, "selected": false, "text": "'Launches Registry Editor with the chosen branch open automatically\n'Author : Ramesh Srinivasan\n'Website: http://windowsxp.mvps.org\n\nSet WshShell = CreateObject(\"WScript.Shell\")\nDim MyKey\nMyKey = Inputbox(\"Type the Registry path\")\nMyKey = \"My Computer\\\" & MyKey\nWshShell.RegWrite \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\\Lastkey\",MyKey,\"REG_SZ\"\nWshShell.Run \"regedit\", 1,True\nSet WshShell = Nothing\n HKEY_CLASSES_ROOT\\.MP3 MyKey = \"My Computer\\\" & MyKey MyKey = \"Computer\\\" & MyKey My \"My Computer\\\" \"Arbeitsplatz\\\" C:\\Regjump HKEY_CLASSES_ROOT\\.mp3" }, { "answer_id": 12516008, "author": "Byron Persino", "author_id": 1686460, "author_profile": "https://Stackoverflow.com/users/1686460", "pm_score": 5, "selected": false, "text": "filename.bat REG ADD HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit /v LastKey /t REG_SZ /d Computer\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Veritas\\NetBackup\\CurrentVersion\\Config /f\nSTART regedit\n Computer\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Veritas\\NetBackup\\CurrentVersion\\Config\n" }, { "answer_id": 12716999, "author": "Jack", "author_id": 794594, "author_profile": "https://Stackoverflow.com/users/794594", "pm_score": 1, "selected": false, "text": "clipboard.exe > \"%~dp0clipdata.txt\"\nset /p clipdata=input < \"%~dp0clipdata.txt\"\nregjump.exe %clipdata%\n" }, { "answer_id": 14417603, "author": "Clint StLaurent", "author_id": 1803878, "author_profile": "https://Stackoverflow.com/users/1803878", "pm_score": 2, "selected": false, "text": " private void registrySettingsToolStripMenuItem_Click(object sender, EventArgs e)\n {\n string path = string.Format(@\"Computer\\HKEY_CURRENT_USER\\Software\\{0}\\{1}\\\",\n Application.CompanyName, Application.ProductName);\n\n MyCommonFunctions.Registry.OpenToKey(path);\n\n }\n /// <summary>Opens RegEdit to the provided key\n /// <para><example>@\"Computer\\HKEY_CURRENT_USER\\Software\\MyCompanyName\\MyProgramName\\\"</example></para>\n /// </summary>\n /// <param name=\"FullKeyPath\"></param>\n public static void OpenToKey(string FullKeyPath)\n {\n RegistryKey rKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\", true);\n rKey.SetValue(\"LastKey\",FullKeyPath);\n\n Process.Start(\"regedit.exe\");\n }\n" }, { "answer_id": 22697203, "author": "thelionkingrafiki", "author_id": 3470093, "author_profile": "https://Stackoverflow.com/users/3470093", "pm_score": 2, "selected": false, "text": "@ECHO OFF\nSET /P \"showkey=Please enter the path of the registry key: \"\nREG ADD \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\" /v \"LastKey\" /d \"%showkey%\" /f\nstart \"\" regedit\n" }, { "answer_id": 29050939, "author": "Mofi", "author_id": 3074564, "author_profile": "https://Stackoverflow.com/users/3074564", "pm_score": 2, "selected": false, "text": "LastKey @echo off\nsetlocal EnableExtensions DisableDelayedExpansion\nset \"RootName=Computer\"\nset \"RegKey=%~1\"\nif defined RegKey goto PrepareKey\n\necho/\necho Please enter the path of the registry key to open.\necho/\nset \"RegKey=\"\nset /P \"RegKey=Key path: \"\n\nrem Exit batch file without starting Regedit if nothing entered by user.\nif not defined RegKey goto EndBatch\n\n:PrepareKey\nrem Remove double quotes and square brackets from entered key path.\nset \"RegKey=%RegKey:\"=%\"\nif not defined RegKey goto EndBatch\nset \"RegKey=%RegKey:[=%\"\nif not defined RegKey goto EndBatch\nset \"RegKey=%RegKey:]=%\"\nif not defined RegKey goto EndBatch\n\nrem Replace hive name abbreviation by appropriate long name.\nset \"Abbreviation=%RegKey:~0,4%\"\nif /I \"%Abbreviation%\" == \"HKCC\" set \"RegKey=HKEY_CURRENT_CONFIG%RegKey:~4%\" & goto GetRootName\nif /I \"%Abbreviation%\" == \"HKCR\" set \"RegKey=HKEY_CLASSES_ROOT%RegKey:~4%\" & goto GetRootName\nif /I \"%Abbreviation%\" == \"HKCU\" set \"RegKey=HKEY_CURRENT_USER%RegKey:~4%\" & goto GetRootName\nif /I \"%Abbreviation%\" == \"HKLM\" set \"RegKey=HKEY_LOCAL_MACHINE%RegKey:~4%\" & goto GetRootName\nif /I \"%RegKey:~0,3%\" == \"HKU\" set \"RegKey=HKEY_USERS%RegKey:~3%\"\n\n:GetRootName\nrem Try to determine automatically name of registry root.\nif not exist %SystemRoot%\\Sysnative\\reg.exe (set \"RegEXE=%SystemRoot%\\System32\\reg.exe\") else set \"RegEXE=%SystemRoot%\\Sysnative\\reg.exe\"\nfor /F \"skip=2 tokens=1,2*\" %%K in ('%RegEXE% QUERY \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\" /v \"LastKey\"') do if /I \"%%K\" == \"LastKey\" for /F \"delims=\\\" %%N in (\"%%M\") do set \"RootName=%%N\"\n\nrem Is Regedit already running?\n%SystemRoot%\\System32\\tasklist.exe /NH /FI \"IMAGENAME eq regedit.exe\" | %SystemRoot%\\System32\\findstr.exe /B /I /L regedit.exe >nul || goto SetRegPath\n\necho/\necho Regedit is already running. Path can be set only when Regedit is not running.\necho/\nset \"UserChoice=N\"\nset /P \"UserChoice=Terminate Regedit (y/N): \"\nif /I \"%UserChoice:\"=%\" == \"y\" %SystemRoot%\\System32\\taskkill.exe /IM regedit.exe >nul 2>nul & goto SetRegPath\necho Switch to running instance of Regedit without setting entered path.\ngoto StartRegedit\n\n:SetRegPath\nrem Add this key as last key to registry for Regedit.\n%RegEXE% ADD \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\" /v \"LastKey\" /d \"%RootName%\\%RegKey%\" /f >nul 2>nul\n\n:StartRegedit\nstart %SystemRoot%\\regedit.exe\n\n:EndBatch\nendlocal\n HKCC HKCU HKCR HKLM HKU LastKey" }, { "answer_id": 35421364, "author": "rojo", "author_id": 1683264, "author_profile": "https://Stackoverflow.com/users/1683264", "pm_score": 1, "selected": false, "text": "htmlfile LastKey @if (@CodeSection == @Batch) @then\n:: regjump.bat\n@echo off & setlocal & goto main\n\n:usage\necho Usage:\necho * %~nx0 regkey\necho * %~nx0 with no args will search the clipboard for a reg key\ngoto :EOF\n\n:main\nrem // ensure variables are unset\nfor %%I in (hive query regpath) do set \"%%I=\"\n\nrem // if argument, try navigating to argument. Else find key in clipboard.\nif not \"%~1\"==\"\" (set \"query=%~1\") else (\n for /f \"delims=\" %%I in ('cscript /nologo /e:JScript \"%~f0\"') do (\n set \"query=%%~I\"\n )\n)\n\nif not defined query (\n echo No registry key was found in the clipboard.\n goto usage\n)\n\nrem // convert HKLM to HKEY_LOCAL_MACHINE, etc. while checking key exists\nfor /f \"delims=\\\" %%I in ('reg query \"%query%\" 2^>NUL') do (\n set \"hive=%%~I\" & goto next\n)\n\n:next\nif not defined hive (\n echo %query% not found in the registry\n goto usage\n)\n\nrem // normalize query, expanding HKLM, HKCU, etc.\nfor /f \"tokens=1* delims=\\\" %%I in (\"%query%\") do set \"regpath=%hive%\\%%~J\"\nif \"%regpath:~-1%\"==\"\\\" set \"regpath=%regpath:~0,-1%\"\n\nrem // https://stackoverflow.com/a/22697203/1683264\n>NUL 2>NUL (\n REG ADD \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\"^\n /v \"LastKey\" /d \"%regpath%\" /f\n)\n\necho %regpath%\n\nstart \"\" regedit\ngoto :EOF\n\n@end // begin JScript hybrid chimera\n// https://stackoverflow.com/a/15747067/1683264\nvar clip = WSH.CreateObject('htmlfile').parentWindow.clipboardData.getData('text');\n\nclip.replace(/\"[^\"]+\"|\\S+/g, function($0) {\n if (/^\\\"?(HK[CLU]|HKEY_)/i.test($0)) {\n WSH.Echo($0);\n WSH.Quit(0);\n }\n});\n" }, { "answer_id": 43352707, "author": "Alex Kwitny", "author_id": 1179573, "author_profile": "https://Stackoverflow.com/users/1179573", "pm_score": 2, "selected": false, "text": "function jumpReg ($registryPath)\n{\n New-ItemProperty -Path \"HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\" `\n -Name \"LastKey\" `\n -Value $registryPath `\n -PropertyType String `\n -Force\n\n regedit\n}\n\njumpReg (\"Computer\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\") | Out-Null\n HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit" }, { "answer_id": 63993839, "author": "kapex", "author_id": 897024, "author_profile": "https://Stackoverflow.com/users/897024", "pm_score": 0, "selected": false, "text": "Computer\\ HKEY_CURRENT_USER\\..." }, { "answer_id": 66999194, "author": "AndrewZtrhgf", "author_id": 3747420, "author_profile": "https://Stackoverflow.com/users/3747420", "pm_score": 0, "selected": false, "text": "# key you want to open\n$regKey = \"Computer\\HKEY_LOCAL_MACHINE\\Software\\Microsoft\\IntuneManagementExtension\\Policies\\\"\n# set starting location for regedit\nSet-ItemProperty \"HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\" \"LastKey\" $regKey\n# open regedit (-m allows multiple regedit windows)\nregedit.exe -m\n" }, { "answer_id": 73573499, "author": "AntonyMan", "author_id": 7230602, "author_profile": "https://Stackoverflow.com/users/7230602", "pm_score": 0, "selected": false, "text": "@echo off\nset /p regPath=\"Open regedit at path: \" \nREG ADD HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit /v LastKey /t REG_SZ /d \"%regPath%\" /f\nSTART regedit\nexit\n:: source: \nhttps://stackoverflow.com/questions/137182/how-to-launch-windows-regedit-with-certain-path?answertab=modifieddesc#tab-top\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18561/" ]
137,212
<p>If you want a cryptographically strong random numbers in Java, you use <code>SecureRandom</code>. Unfortunately, <code>SecureRandom</code> can be very slow. If it uses <code>/dev/random</code> on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty?</p> <p>Has anyone used <a href="https://uncommons-maths.dev.java.net/" rel="noreferrer">Uncommon Maths</a> as a solution to this problem?</p> <p>Can anybody confirm that this performance problem has been solved in JDK 6?</p>
[ { "answer_id": 137252, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 3, "selected": false, "text": "/dev/random SecureRandom SecureRandom SecureRandom SecureRandomSpi" }, { "answer_id": 137288, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 8, "selected": true, "text": "SecureRandom SecureRandom /dev/random SecureRandom.getInstance(\"SHA1PRNG\");\n SecureRandom Security.getProviders() Provider.getService() setSeed() next() nextBytes()" }, { "answer_id": 138745, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 5, "selected": false, "text": "SecureRandom NativePRNG SHA1PRNG NativePRNG SHA1PRNG /dev/urandom SHA1PRNG NativePRNG" }, { "answer_id": 140921, "author": "Chris Kite", "author_id": 9573, "author_profile": "https://Stackoverflow.com/users/9573", "pm_score": 4, "selected": false, "text": "/dev/random /dev/random /dev/random" }, { "answer_id": 2325109, "author": "Thomas Leonard", "author_id": 50926, "author_profile": "https://Stackoverflow.com/users/50926", "pm_score": 8, "selected": false, "text": "-Djava.security.egd=file:/dev/urandom\n -Djava.security.egd=file:/dev/./urandom\n /./" }, { "answer_id": 12159344, "author": "David K", "author_id": 1324595, "author_profile": "https://Stackoverflow.com/users/1324595", "pm_score": 3, "selected": false, "text": "rngd -r /dev/urandom\n" }, { "answer_id": 18816044, "author": "user2781824", "author_id": 2781824, "author_profile": "https://Stackoverflow.com/users/2781824", "pm_score": 2, "selected": false, "text": "RDRAND SecureRandom rdrand RdRandRandom() Provider" }, { "answer_id": 30358935, "author": "thunder", "author_id": 3438692, "author_profile": "https://Stackoverflow.com/users/3438692", "pm_score": 4, "selected": false, "text": "SecureRandom haveged /dev/random SecureRandom" }, { "answer_id": 40885767, "author": "Lachlan", "author_id": 94152, "author_profile": "https://Stackoverflow.com/users/94152", "pm_score": 3, "selected": false, "text": "SecureRandom.getInstanceStrong() NativePRNGBlocking NativePRNGNonBlocking new SecureRandom() /dev/urandom /dev/random SecureRandom.getInstanceStrong()" }, { "answer_id": 47097219, "author": "rustyx", "author_id": 485343, "author_profile": "https://Stackoverflow.com/users/485343", "pm_score": 5, "selected": false, "text": "/dev/random /dev/random /dev/random apt-get install haveged\nupdate-rc.d haveged defaults\nservice haveged start\n yum install haveged\nsystemctl enable haveged\nsystemctl start haveged\n /dev/urandom jre/lib/security/java.security /dev/urandom /dev/./urandom #securerandom.source=file:/dev/random\nsecurerandom.source=file:/dev/./urandom\n" }, { "answer_id": 58182522, "author": "SQB", "author_id": 2936460, "author_profile": "https://Stackoverflow.com/users/2936460", "pm_score": 3, "selected": false, "text": "nextBytes() /dev/urandom generateSeed() /dev/random nextBytes() generateSeed() /dev/random nextBytes() generateSeed() /dev/urandom SecureRandom random = new SecureRandom() /dev/random /dev/urandom /dev/random /dev/urandom SecureRandom SecureRandom random = SecureRandom.getInstance(\"NativePRNGNonBlocking\") SecureRandom random;\ntry {\n random = SecureRandom.getInstance(\"NativePRNGNonBlocking\");\n} catch (NoSuchAlgorithmException nsae) {\n random = new SecureRandom();\n}\n /dev/urandom /dev/urandom /dev/random /dev/urandom/ /dev/urandom" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3150/" ]
137,219
<p>I am looking for the way to mount NTFS hard disk on FreeBSD 6.2 in read/write mode.</p> <p>searching google, I found that NTFS-3G can be a help.</p> <p>Using NTFS-3G, there is no problem when I try to mount/unmount NTFS manually:</p> <p>mount: ntfs-3g /dev/ad1s1 /home/admin/data -o uid=1002,</p> <p>or</p> <p>umount: umount /home/admin/data</p> <p>But I have a problem when try to mount ntfs hard disk automatically at boot time.</p> <p>I have tried: </p> <ul> <li>adding fstab: /dev/ad1s1 /home/admin/data ntfs-3g uid=1002 0 0</li> <li>make a script, that automatically mount ntfs partition at start up, on /usr/local/etc/rc.d/ directory.</li> </ul> <p>But it is still failed. The script works well when it is executed manually.</p> <p>Does anyone know an alternative method/ solution to have read/write access NTFS on FreeBSD 6.2?</p> <p>Thanks.</p>
[ { "answer_id": 137252, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 3, "selected": false, "text": "/dev/random SecureRandom SecureRandom SecureRandom SecureRandomSpi" }, { "answer_id": 137288, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 8, "selected": true, "text": "SecureRandom SecureRandom /dev/random SecureRandom.getInstance(\"SHA1PRNG\");\n SecureRandom Security.getProviders() Provider.getService() setSeed() next() nextBytes()" }, { "answer_id": 138745, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 5, "selected": false, "text": "SecureRandom NativePRNG SHA1PRNG NativePRNG SHA1PRNG /dev/urandom SHA1PRNG NativePRNG" }, { "answer_id": 140921, "author": "Chris Kite", "author_id": 9573, "author_profile": "https://Stackoverflow.com/users/9573", "pm_score": 4, "selected": false, "text": "/dev/random /dev/random /dev/random" }, { "answer_id": 2325109, "author": "Thomas Leonard", "author_id": 50926, "author_profile": "https://Stackoverflow.com/users/50926", "pm_score": 8, "selected": false, "text": "-Djava.security.egd=file:/dev/urandom\n -Djava.security.egd=file:/dev/./urandom\n /./" }, { "answer_id": 12159344, "author": "David K", "author_id": 1324595, "author_profile": "https://Stackoverflow.com/users/1324595", "pm_score": 3, "selected": false, "text": "rngd -r /dev/urandom\n" }, { "answer_id": 18816044, "author": "user2781824", "author_id": 2781824, "author_profile": "https://Stackoverflow.com/users/2781824", "pm_score": 2, "selected": false, "text": "RDRAND SecureRandom rdrand RdRandRandom() Provider" }, { "answer_id": 30358935, "author": "thunder", "author_id": 3438692, "author_profile": "https://Stackoverflow.com/users/3438692", "pm_score": 4, "selected": false, "text": "SecureRandom haveged /dev/random SecureRandom" }, { "answer_id": 40885767, "author": "Lachlan", "author_id": 94152, "author_profile": "https://Stackoverflow.com/users/94152", "pm_score": 3, "selected": false, "text": "SecureRandom.getInstanceStrong() NativePRNGBlocking NativePRNGNonBlocking new SecureRandom() /dev/urandom /dev/random SecureRandom.getInstanceStrong()" }, { "answer_id": 47097219, "author": "rustyx", "author_id": 485343, "author_profile": "https://Stackoverflow.com/users/485343", "pm_score": 5, "selected": false, "text": "/dev/random /dev/random /dev/random apt-get install haveged\nupdate-rc.d haveged defaults\nservice haveged start\n yum install haveged\nsystemctl enable haveged\nsystemctl start haveged\n /dev/urandom jre/lib/security/java.security /dev/urandom /dev/./urandom #securerandom.source=file:/dev/random\nsecurerandom.source=file:/dev/./urandom\n" }, { "answer_id": 58182522, "author": "SQB", "author_id": 2936460, "author_profile": "https://Stackoverflow.com/users/2936460", "pm_score": 3, "selected": false, "text": "nextBytes() /dev/urandom generateSeed() /dev/random nextBytes() generateSeed() /dev/random nextBytes() generateSeed() /dev/urandom SecureRandom random = new SecureRandom() /dev/random /dev/urandom /dev/random /dev/urandom SecureRandom SecureRandom random = SecureRandom.getInstance(\"NativePRNGNonBlocking\") SecureRandom random;\ntry {\n random = SecureRandom.getInstance(\"NativePRNGNonBlocking\");\n} catch (NoSuchAlgorithmException nsae) {\n random = new SecureRandom();\n}\n /dev/urandom /dev/urandom /dev/random /dev/urandom/ /dev/urandom" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,221
<p>I've searched around for a while today, but I haven't been able to come up with an AutoComplete TextBox code sample for Silverlight 2 Beta 2. The most promising reference was found on <a href="http://www.nikhilk.net/Silverlight-AutoComplete.aspx/" rel="nofollow noreferrer">nikhilk.net</a> but the online demo doesn't currently render and after downloading a getting the code to compile with Beta 2, I couldn't get the Silverlight plugin it to render either. I think it is fair to say it is a compatibility issue, but I'm not sure. Does anyone have any alternate sample code or implementation suggestions?</p>
[ { "answer_id": 140167, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 3, "selected": true, "text": "manas:Autocomplete.Suggest=\"DoSuggest\"\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115/" ]
137,226
<ol> <li>What are the patterns you use to determine the frequent queries? </li> <li>How do you select the optimization factors?</li> <li>What are the types of changes one can make?</li> </ol>
[ { "answer_id": 137330, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "select diskusage from x where date = '2008-01-01'\n select date from x where diskusage > 90\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65724/" ]
137,227
<p>How can I list all the types that are declared by a module in Ruby?</p>
[ { "answer_id": 137311, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 6, "selected": true, "text": "p Class.constants\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
137,229
<p>I bumped into a strange situation with MSBuild just now. There's a solution which has three projects: LibX, LibY and Exe. Exe references LibX. LibX in its turn references LibY, has some content files, and also references to a third-party library (several pre-built assemblies installed in both GAC and local lib folder). The third-party library is marked as "Copy Local" ("private") and appears in the output of the LibX project, as the LibY's output and LibX's content files do. Now, Exe project's output has LibX project output, content files of the LibX project, LibY project output (coming from LibX), but NO third-party library's assemblies.</p> <p>Now I worked this around by referencing the third-party library directly in Exe project, but I don't feel this is a "right" solution.</p> <p>Anyone had this problem before?</p>
[ { "answer_id": 164417, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 2, "selected": false, "text": "References=\"@(ReferencePath)\"\n References=\"@(ReferencePath);@(ReferenceDependencyPaths)\"\n" }, { "answer_id": 9327874, "author": "agilejoshua", "author_id": 1191834, "author_profile": "https://Stackoverflow.com/users/1191834", "pm_score": 4, "selected": false, "text": " <Target Name=\"AfterResolveReferences\">\n <!-- Redefine referencepath to add dependencyies-->\n <ItemGroup>\n <ReferencePath Include=\"@(ReferenceDependencyPaths)\">\n </ReferencePath>\n </ItemGroup> \n </Target>\n" }, { "answer_id": 14656287, "author": "Jim", "author_id": 211025, "author_profile": "https://Stackoverflow.com/users/211025", "pm_score": 2, "selected": false, "text": "<Target Name=\"AfterResolveReferences\">\n <!-- Redefine referencepath to add dependencies-->\n <ItemGroup Condition=\" '$(BuildingInsideVisualStudio)' != 'true' \">\n <ReferencePath Include=\"@(ReferenceDependencyPaths)\"></ReferencePath>\n </ItemGroup>\n</Target>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21952/" ]
137,255
<p>How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?</p>
[ { "answer_id": 137347, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 4, "selected": true, "text": "internal static class Win32\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);\n\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n long freeBytesForUser;\n long totalBytes;\n long freeBytes;\n\n if (Win32.GetDiskFreeSpaceEx(@\"\\\\prime\\cargohold\", out freeBytesForUser, out totalBytes, out freeBytes)) {\n Console.WriteLine(freeBytesForUser);\n Console.WriteLine(totalBytes);\n Console.WriteLine(freeBytes);\n }\n }\n}\n" }, { "answer_id": 137348, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "public class DriveWrapper\n{ \n [StructLayout(LayoutKind.Sequential)]\n public struct NETRESOURCEA\n {\n public int dwScope;\n public int dwType;\n public int dwDisplayType;\n public int dwUsage;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpLocalName;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpRemoteName;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpComment;\n [MarshalAs(UnmanagedType.LPStr)]\n public string lpProvider;\n public override String ToString()\n {\n String str = \"LocalName: \" + lpLocalName + \" RemoteName: \" + lpRemoteName\n + \" Comment: \" + lpComment + \" lpProvider: \" + lpProvider;\n return (str);\n }\n }\n\n [DllImport(\"mpr.dll\")]\n public static extern int WNetAddConnection2A(\n [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,\n [MarshalAs(UnmanagedType.LPStr)] string lpPassword,\n [MarshalAs(UnmanagedType.LPStr)] string UserName,\n int dwFlags); \n [DllImport(\"mpr.dll\", CharSet = System.Runtime.InteropServices.CharSet.Auto)]\n private static extern int WNetCancelConnection2A(\n [MarshalAs(UnmanagedType.LPStr)]\n string lpName,\n int dwFlags,\n int fForce\n );\n\n public int GetDriveSpace(string shareName, string userName, string password)\n {\n NETRESOURCEA[] n = new NETRESOURCEA[1];\n n[0] = new NETRESOURCEA();\n\n n[0].dwScope = 0;\n n[0].dwType = 0;\n n[0].dwDisplayType = 0;\n n[0].dwUsage = 0;\n\n n[0].dwType = 1;\n\n n[0].lpLocalName = \"x:\";\n n[0].lpRemoteName = shareName;\n n[0].lpProvider = null;\n\n int res = WNetAddConnection2A(n, userName, password, 1);\n\n DriveInfo info = new DriveInfo(\"x:\");\n int space = info.AvailableFreeSpace;\n\n int err = 0;\n err = WNetCancelConnection2A(\"x:\", 0, 1);\n\n return space;\n }\n}\n" }, { "answer_id": 137357, "author": "s d", "author_id": 20911, "author_profile": "https://Stackoverflow.com/users/20911", "pm_score": 3, "selected": false, "text": "using System.Management;\n\n// Get all the network drives (drivetype=4)\nSelectQuery query = new SelectQuery(\"select Name, VolumeName, FreeSpace from win32_logicaldisk where drivetype=4\");\nManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\nforeach (ManagementObject drive in searcher.Get())\n{\n string Name = (string)drive[\"Name\"];\n string VolumeName = (string)drive[\"VolumeName\"];\n UInt64 freeSpace = (UInt64)drive[\"FreeSpace\"];\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
137,258
<p>Here's a common code pattern I have to work with:</p> <pre><code>class foo { public: void InitMap(); void InvokeMethodsInMap(); static void abcMethod(); static void defMethod(); private: typedef std::map&lt;const char*, pMethod&gt; TMyMap; TMyMap m_MyMap; } void foo::InitMap() { m_MyMap["abc"] = &amp;foo::abcMethod; m_MyMap["def"] = &amp;foo::defMethod; } void foo::InvokeMethodsInMap() { for (TMyMap::const_iterator it = m_MyMap.begin(); it != m_MyMap.end(); it++) { (*it-&gt;second)(it-&gt;first); } } </code></pre> <p>However, I have found that the <em>order</em> that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order.</p> <p>I thought that by using <code>begin()</code> in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed.</p> <p>This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build).</p> <p>Can anyone explain this strange behaviour?</p>
[ { "answer_id": 137264, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "const char* std::string std::map <" }, { "answer_id": 137477, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "struct StringLess\n{\n bool operator()(const char* const& left,const char* const& right) const\n {\n return strcmp(left,right) < 0;\n }\n};\n\n///\n\ntypedef std::map<const char*, int,StringLess> TMyMap;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
137,260
<p>I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.</p> <p>I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?</p>
[ { "answer_id": 137324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "class Base {\n public Base() {\n InitializeComponent();\n }\n protected virtual void InitializeComponent() {\n ...\n }\n}\n\nclass Derived : Base {\n private Button button1;\n public Derived() : base() {\n button1 = new Button();\n }\n protected override void InitializeComponent() {\n button1.Text = \"I'm gonna throw a null reference exception\"\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
137,282
<p><a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="noreferrer">http://en.wikipedia.org/wiki/Diamond_problem</a></p> <p>I know what it means, but what steps can I take to avoid it?</p>
[ { "answer_id": 139329, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 7, "selected": true, "text": "class A {};\nclass B : public A {};\nclass C : public A {};\nclass D : public B, public C {};\n class A {};\nclass B : virtual public A {};\nclass C : virtual public A {};\nclass D : public B, public C {};\n" }, { "answer_id": 143104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "class Employee : public WidgetListener, public LectureAttendee\n{\npublic:\n Employee(int x, int y)\n WidgetListener(x), LectureAttendee(y)\n {}\n};\n class Employee\n{\npublic:\n Employee(int x, int y)\n : listener(this, x), attendee(this, y)\n {}\n\n WidgetListener listener;\n LectureAttendee attendee;\n};\n" }, { "answer_id": 11494762, "author": "NItish", "author_id": 1527338, "author_profile": "https://Stackoverflow.com/users/1527338", "pm_score": 2, "selected": false, "text": "class A {}; \nclass B : public A {}; \nclass C : public A {}; \nclass D : public B, public C {};\n" }, { "answer_id": 72211282, "author": "mada", "author_id": 16972547, "author_profile": "https://Stackoverflow.com/users/16972547", "pm_score": 0, "selected": false, "text": "struct A { int a; };\nstruct B : A { int b; };\nstruct C : A { int c; };\nstruct D : B, C {};\n\nD d;\nd.a = 10; //error: ambiguous request for 'a'\n d.B::a = 10; // OK\nd.C::a = 100; // OK\nd.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a\n static_cast<B&>(static_cast<D&>(d)).a = 10;\nstatic_cast<C&>(static_cast<D&>(d)).a = 100;\nd.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a\n struct A { int a; };\nstruct B : A { int b; };\nstruct C : A { int c; };\nstruct D : B, C { int a; };\n \nD d;\nd.a = 10; // OK: D::a = 10\nd.A::a = 20; // ambiguous: which path the compiler has to take D::B::A or D::C::A to initialize A::a\n struct A { int a; };\nstruct B : virtual A { int b; };\nstruct C : virtual A { int c; };\nstruct D : B, C {};\n \nD d;\nd.a = 10; // OK: D has only one copy of A - D::a = 10\nd.A::a = 20; // OK: D::a = 20\n struct A { int a; };\nstruct B : A { int b; };\nstruct C : virtual A { int c; };\nstruct D : B, C {};\n\nOr\n\nstruct A { int a; };\nstruct B : virtual A { int b; };\nstruct C : A { int c; };\nstruct D : B, C {};\n\nOr\n\nstruct A { int a; };\nstruct B : A { int b; };\nstruct C : virtual A { int c; };\nstruct D : virtual B, C {};\n\nOr\n\nstruct A { int a; };\nstruct B : virtual A { int b; };\nstruct C : A { int c; };\nstruct D : virtual B, C {};\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
137,285
<p>What is the best way to read an HTTP response from GetResponseStream ?</p> <p>Currently I'm using the following approach.</p> <pre><code>Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream) SourceCode = SReader.ReadToEnd() End Using </code></pre> <p>I'm not quite sure if this is the most efficient way to read an http response.</p> <p>I need the output as string, I've seen an <a href="http://www.informit.com/guides/content.aspx?g=dotnet&amp;seqNum=583" rel="noreferrer">article</a> with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites.</p> <p>How do you read web responses?</p>
[ { "answer_id": 137300, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": false, "text": "if (!Directory.Exists(localFolder))\n{\n Directory.CreateDirectory(localFolder); \n}\n\n\ntry\n{\n HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));\n httpRequest.Method = \"GET\";\n\n // if the URI doesn't exist, an exception will be thrown here...\n using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())\n {\n using (Stream responseStream = httpResponse.GetResponseStream())\n {\n using (FileStream localFileStream = \n new FileStream(Path.Combine(localFolder, filename), FileMode.Create))\n {\n var buffer = new byte[4096];\n long totalBytesRead = 0;\n int bytesRead;\n\n while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)\n {\n totalBytesRead += bytesRead;\n localFileStream.Write(buffer, 0, bytesRead);\n }\n }\n }\n }\n}\ncatch (Exception ex)\n{\n // You might want to handle some specific errors : Just pass on up for now...\n // Remove this catch if you don't want to handle errors here.\n throw;\n}\n" }, { "answer_id": 161621, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "using ( FileStream localFileStream = .... \n{ \n byte[] buffer = new byte[ 255 ]; \n int bytesRead; \n double totalBytesRead = 0; \n\n while ((bytesRead = .... \n" }, { "answer_id": 846188, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 4, "selected": false, "text": "using System.Net;\n\nnamespace WebClientExample\n{\n class Program\n {\n static void Main(string[] args)\n {\n var remoteUri = \"http://www.contoso.com/library/homepage/images/\";\n var fileName = \"ms-banner.gif\";\n WebClient myWebClient = new WebClient();\n myWebClient.DownloadFile(remoteUri + fileName, fileName);\n }\n }\n}\n" }, { "answer_id": 2945166, "author": "Robert MacLean", "author_id": 53236, "author_profile": "https://Stackoverflow.com/users/53236", "pm_score": 4, "selected": false, "text": "true StreamReader string target = string.Empty;\nHttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(\"http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=583\");\n\nHttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();\ntry\n{\n StreamReader streamReader = new StreamReader(response.GetResponseStream(),true); \n try\n {\n target = streamReader.ReadToEnd();\n }\n finally\n {\n streamReader.Close();\n }\n}\nfinally\n{\n response.Close();\n}\n" }, { "answer_id": 10528832, "author": "Stew-au", "author_id": 182260, "author_profile": "https://Stackoverflow.com/users/182260", "pm_score": 3, "selected": false, "text": "function GetWebPage\n{param ($Url, $Outfile)\n $request = [System.Net.HttpWebRequest]::Create($SearchBoxBuilderURL)\n $request.AuthenticationLevel = \"None\"\n $request.TimeOut = 600000 #10 mins \n $response = $request.GetResponse() #Appending \"|Out-Host\" anulls the variable\n Write-Host \"Response Status Code: \"$response.StatusCode\n Write-Host \"Response Status Description: \"$response.StatusDescription\n $requestStream = $response.GetResponseStream()\n $readStream = new-object System.IO.StreamReader $requestStream\n new-variable db | Out-Host\n $db = $readStream.ReadToEnd()\n $readStream.Close()\n $response.Close()\n #Create a new file and write the web output to a file\n $sw = new-object system.IO.StreamWriter($Outfile)\n $sw.writeline($db) | Out-Host\n $sw.close() | Out-Host\n}\n $SearchBoxBuilderURL = $SiteUrl + \"nin_searchbox/DailySearchBoxBuilder.asp\"\n$SearchBoxBuilderOutput=\"D:\\ecom\\tmp\\ss2.txt\"\nGetWebPage $SearchBoxBuilderURL $SearchBoxBuilderOutput\n" }, { "answer_id": 43981770, "author": "João Paulo Melo", "author_id": 2791237, "author_profile": "https://Stackoverflow.com/users/2791237", "pm_score": 1, "selected": false, "text": "GetResponseStream() try\n{\n response = basicHTTPBindingClient.CallOperation(request);\n}\ncatch (ProtocolException exception)\n{\n var webException = exception.InnerException as WebException;\n\n var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;\n using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))\n using (var reader = new StreamReader(brandNewStream))\n rawResponse = reader.ReadToEnd();\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
137,313
<p>I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns.</p> <p>I wrote a small Perl script to do this:</p> <pre><code>#!/usr/bin/perl die("need max length\n") unless $#ARGV == 0; while (&lt;STDIN&gt;) { $_ = substr($_, 0, $ARGV[0]); chomp($_); print "$_\n"; } </code></pre> <p>But I have a feeling that this functionality is probably built into some other tools (sed?) That I just don't know enough about to use for this task.</p> <p>So my question sort of a reverse question: how do I truncate a line of stdin Without writing a program to do it?</p>
[ { "answer_id": 137323, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 5, "selected": true, "text": "cut -b 1-LIMIT\n" }, { "answer_id": 137642, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 2, "selected": false, "text": "$ perl -pe's/(?<=.{25}).*//' filename\n" }, { "answer_id": 138192, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "perl -wlne'print substr($_,0,80)'\n perl -nE'say/(.{0,80})/'\n" }, { "answer_id": 141112, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 0, "selected": false, "text": "typeset -L70 line\nwhile read line\ndo\n print $line\ndone\n" }, { "answer_id": 142098, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 0, "selected": false, "text": "#! /usr/bin/perl -w\n\nuse strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n" }, { "answer_id": 848356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "use strict;\nuse warnings\nuse String::FixedLen;\n\ntie my $str, 'String::FixedLen', 4;\n\nwhile (defined($str = <>)) {\n chomp;\n print \"$str\\n\";\n}\n" }, { "answer_id": 12899735, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 0, "selected": false, "text": "$ cat file\nthe quick brown fox jumped over the lazy dog's back\n\n$ fold -w20 file\nthe quick brown fox\njumped over the lazy\n dog's back\n\n$ fold -w10 file\nthe quick\nbrown fox\njumped ove\nr the lazy\n dog's bac\nk\n\n$ fold -s -w10 file\nthe quick\nbrown fox\njumped\nover the\nlazy\ndog's back\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]