qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
15,979
<p>I use solr to search for documents and when trying to search for documents using this query "<code>id:*</code>", I get this query parser exception telling that it cannot parse the query with * or ? as the first character. </p> <pre><code>HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery type Status report message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery). </code></pre> <p>Is there any patch for getting this to work with just * ? Or is it very costly to do such a query?</p>
[ { "answer_id": 17458, "author": "cnu", "author_id": 1448, "author_profile": "https://Stackoverflow.com/users/1448", "pm_score": 1, "selected": false, "text": "id:A*" }, { "answer_id": 23554, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 3, "selected": false, "text": "id:[a* TO z*] id:[0* TO 9*] etc.\n new indexReader(\"DirectoryName\") indexReader numDocs() document(int n)" }, { "answer_id": 6899858, "author": "Daniel Rijkhof", "author_id": 648458, "author_profile": "https://Stackoverflow.com/users/648458", "pm_score": 2, "selected": false, "text": "public SolrQueryParser(IndexSchema schema, String defaultField) { \n ... \n setAllowLeadingWildcard(true); \n setLowercaseExpandedTerms(true); \n ... \n}\n\n ...\n\npublic SolrQueryParser(QParser parser, String defaultField, Analyzer analyzer) {\n ... \n setAllowLeadingWildcard(true); \n setLowercaseExpandedTerms(true);\n ... \n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/15979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
15,995
<p>Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and * that we see in the examples?</p> <p>Refer <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196" rel="noreferrer">Fate of reduce() in Python 3000</a> by GvR</p>
[ { "answer_id": 16049, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 2, "selected": false, "text": "reduce()" }, { "answer_id": 16091, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 1, "selected": false, "text": "files = []\nfiles.extend(reduce(lambda x, y: x + y, map(glob.glob, args)))\n files = []\nfor f in args:\n files.extend(glob.glob(f))\n" }, { "answer_id": 16198, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "files = sum([glob.glob(f) for f in args], [])\n" }, { "answer_id": 21247, "author": "Tomi Kyöstilä", "author_id": 616, "author_profile": "https://Stackoverflow.com/users/616", "pm_score": 2, "selected": false, "text": "reduce(operator.mul, xrange(1, x+1) or (1,))\n" }, { "answer_id": 41660, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 4, "selected": false, "text": "reduce make_and reduce(make_and,l) reduce(make_and,l,make_true) reduce + * min max make_and make_or reduce sum reduce sum reduce reduce" }, { "answer_id": 280242, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 6, "selected": false, "text": "any all foldl foldr [[1, 2, 3], [4, 5], [6, 7, 8]] [1, 2, 3, 4, 5, 6, 7, 8] reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])\n [1, 2, 3, 4, 5, 6, 7, 8] 12345678 int(\"\".join(map(str, [1,2,3,4,5,6,7,8])))\n reduce reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)\n" }, { "answer_id": 282206, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": false, "text": "reduce() #!/usr/bin/env python\nfrom math import gcd\nfrom functools import reduce\n\ndef lcm(*args):\n return reduce(lambda a,b: a * b // gcd(a, b), args)\n >>> lcm(100, 23, 98)\n112700\n>>> lcm(*range(1, 20))\n232792560\n" }, { "answer_id": 282678, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": "reduce() eval() >>> import __main__\n>>> reduce(getattr, \"os.path.abspath\".split('.'), __main__)\n<function abspath at 0x009AB530>\n" }, { "answer_id": 2701826, "author": "ben", "author_id": 309368, "author_profile": "https://Stackoverflow.com/users/309368", "pm_score": 2, "selected": false, "text": "complexop = compose(stage4, stage3, stage2, stage1)\n complexop(expression)\n stage4(stage3(stage2(stage1(expression))))\n Lambda([Symbol('x')], Apply(stage4, Apply(stage3, Apply(stage2, Apply(stage1, Symbol('x'))))))\n reduce(lambda x,y: Apply(y, x), reversed(args + [Symbol('x')]))\n reduce(lambda x, y: (x, y), range(1, 11))\nreduce(lambda x, y: (y, x), reversed(range(1, 11)))\n" }, { "answer_id": 3272453, "author": "ssoler", "author_id": 170912, "author_profile": "https://Stackoverflow.com/users/170912", "pm_score": 5, "selected": false, "text": "input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]\n\nresult = reduce(set.intersection, map(set, input_list))\n result = set([3, 4, 5])\n" }, { "answer_id": 12026042, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "value = json_obj['a']['b']['c']['d']['e'] value = reduce(dict.__getitem__, 'abcde', json_obj)\n a/b/c/.." }, { "answer_id": 12171466, "author": "Chris X", "author_id": 1567046, "author_profile": "https://Stackoverflow.com/users/1567046", "pm_score": 4, "selected": false, "text": "reduce(lambda hold,next:hold+chr(((ord(next.upper())-65)+13)%26+65),'znlorabggbbhfrshy','')\n" }, { "answer_id": 12310900, "author": "tborg", "author_id": 1116899, "author_profile": "https://Stackoverflow.com/users/1116899", "pm_score": 2, "selected": false, "text": "articles articles reduce from lxml import etree\nfrom Reader import Reader\n\nclass IssueReader(Reader):\n def articles(self):\n arts = self.q('//div3') # inherited ... runs an xpath query against the issue\n subsection = etree.XPath('./ancestor::div2/@type')\n section = etree.XPath('./ancestor::div1/@type')\n header_text = etree.XPath('./head//text()')\n return map(lambda art: {\n 'text_id': self.id,\n 'path': self.getpath(art)[0],\n 'subsection': (subsection(art)[0] or '[none]'),\n 'section': (section(art)[0] or '[none]'),\n 'headline': (''.join(header_text(art)) or '[none]')\n }, arts)\n\n def by_section(self):\n arts = self.articles()\n\n def extract(acc, art): # acc for accumulator\n section = acc.get(art['section'], False)\n if section:\n subsection = acc.get(art['subsection'], False)\n if subsection:\n subsection.append(art)\n else:\n section[art['subsection']] = [art]\n else:\n acc[art['section']] = {art['subsection']: [art]}\n return acc\n\n return reduce(extract, arts, {})\n extract" }, { "answer_id": 15541396, "author": "Sidharth C. Nadhan", "author_id": 2094708, "author_profile": "https://Stackoverflow.com/users/2094708", "pm_score": 2, "selected": false, "text": "reduce(lambda x,y: x if x[2] > y[2] else y,[[1,2,3,4],[5,2,5,7],[1,6,0,2]])\n" }, { "answer_id": 21144816, "author": "beardc", "author_id": 386279, "author_profile": "https://Stackoverflow.com/users/386279", "pm_score": 4, "selected": false, "text": "color = lambda x: x.replace('brown', 'blue')\nspeed = lambda x: x.replace('quick', 'slow')\nwork = lambda x: x.replace('lazy', 'industrious')\nfs = [str.lower, color, speed, work, str.title]\n >>> call = lambda s, func: func(s)\n>>> s = \"The Quick Brown Fox Jumps Over the Lazy Dog\"\n>>> reduce(call, fs, s)\n'The Slow Blue Fox Jumps Over The Industrious Dog'\n f1(f2(f3(f4(x))))" }, { "answer_id": 21956185, "author": "lessthanl0l", "author_id": 3285376, "author_profile": "https://Stackoverflow.com/users/3285376", "pm_score": 0, "selected": false, "text": "from datetime import date, timedelta\n\n\ndef checked(d1, d2):\n \"\"\"\n We assume the date list is sorted.\n If d2 & d1 are different by 1, everything up to d2 is consecutive, so d2\n can advance to the next reduction.\n If d2 & d1 are not different by 1, returning d1 - 1 for the next reduction\n will guarantee the result produced by reduce() to be something other than\n the last date in the sorted date list.\n\n Definition 1: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider consecutive\n Definition 2: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider not consecutive\n\n \"\"\"\n #if (d2 - d1).days == 1 or (d2 - d1).days == 0: # for Definition 1\n if (d2 - d1).days == 1: # for Definition 2\n return d2\n else:\n return d1 + timedelta(days=-1)\n\n# datelist = [date(2014, 1, 1), date(2014, 1, 3),\n# date(2013, 12, 31), date(2013, 12, 30)]\n\n# datelist = [date(2014, 2, 19), date(2014, 2, 19), date(2014, 2, 20),\n# date(2014, 2, 21), date(2014, 2, 22)]\n\ndatelist = [date(2014, 2, 19), date(2014, 2, 21),\n date(2014, 2, 22), date(2014, 2, 20)]\n\ndatelist.sort()\n\nif datelist[-1] == reduce(checked, datelist):\n print \"dates are consecutive\"\nelse:\n print \"dates are not consecutive\"\n" }, { "answer_id": 21956201, "author": "lessthanl0l", "author_id": 3285376, "author_profile": "https://Stackoverflow.com/users/3285376", "pm_score": 1, "selected": false, "text": "from collections import Counter\n\nstat2011 = Counter({\"January\": 12, \"February\": 20, \"March\": 50, \"April\": 70, \"May\": 15,\n \"June\": 35, \"July\": 30, \"August\": 15, \"September\": 20, \"October\": 60,\n \"November\": 13, \"December\": 50})\n\nstat2012 = Counter({\"January\": 36, \"February\": 15, \"March\": 50, \"April\": 10, \"May\": 90,\n \"June\": 25, \"July\": 35, \"August\": 15, \"September\": 20, \"October\": 30,\n \"November\": 10, \"December\": 25})\n\nstat2013 = Counter({\"January\": 10, \"February\": 60, \"March\": 90, \"April\": 10, \"May\": 80,\n \"June\": 50, \"July\": 30, \"August\": 15, \"September\": 20, \"October\": 75,\n \"November\": 60, \"December\": 15})\n\nstat_list = [stat2011, stat2012, stat2013]\n\nprint reduce(lambda x, y: x & y, stat_list) # MIN\nprint reduce(lambda x, y: x | y, stat_list) # MAX\n" }, { "answer_id": 23764928, "author": "Aleksei astynax Pirogov", "author_id": 590667, "author_profile": "https://Stackoverflow.com/users/590667", "pm_score": 2, "selected": false, "text": "import os\n\nfiles = [\n # full filenames\n \"var/log/apache/errors.log\",\n \"home/kane/images/avatars/crusader.png\",\n \"home/jane/documents/diary.txt\",\n \"home/kane/images/selfie.jpg\",\n \"var/log/abc.txt\",\n \"home/kane/.vimrc\",\n \"home/kane/images/avatars/paladin.png\",\n]\n\n# unfolding of plain filiname list to file-tree\nfs_tree = ({}, # dict of folders\n []) # list of files\nfor full_name in files:\n path, fn = os.path.split(full_name)\n reduce(\n # this fucction walks deep into path\n # and creates placeholders for subfolders\n lambda d, k: d[0].setdefault(k, # walk deep\n ({}, [])), # or create subfolder storage\n path.split(os.path.sep),\n fs_tree\n )[1].append(fn)\n\nprint fs_tree\n#({'home': (\n# {'jane': (\n# {'documents': (\n# {},\n# ['diary.txt']\n# )},\n# []\n# ),\n# 'kane': (\n# {'images': (\n# {'avatars': (\n# {},\n# ['crusader.png',\n# 'paladin.png']\n# )},\n# ['selfie.jpg']\n# )},\n# ['.vimrc']\n# )},\n# []\n# ),\n# 'var': (\n# {'log': (\n# {'apache': (\n# {},\n# ['errors.log']\n# )},\n# ['abc.txt']\n# )},\n# [])\n#},\n#[])\n" }, { "answer_id": 24061830, "author": "JulienD", "author_id": 2197181, "author_profile": "https://Stackoverflow.com/users/2197181", "pm_score": 1, "selected": false, "text": "__and__ class Exon:\n def __init__(self):\n ...\n def __and__(self,other):\n ...\n length = self.length + other.length # (e.g.)\n return self.__class__(...length,...)\n intersection = reduce(lambda x,y: x&y, exons)\n" }, { "answer_id": 24321770, "author": "Jian", "author_id": 1205529, "author_profile": "https://Stackoverflow.com/users/1205529", "pm_score": 3, "selected": false, "text": "reduce reduce(getattr, ('request', 'user', 'email'), self)\n self.request.user.email\n" }, { "answer_id": 24322230, "author": "Jian", "author_id": 1205529, "author_profile": "https://Stackoverflow.com/users/1205529", "pm_score": 3, "selected": false, "text": "reduce set >>> reduce(operator.or_, ({1}, {1, 2}, {1, 3})) # union\n{1, 2, 3}\n>>> reduce(operator.and_, ({1}, {1, 2}, {1, 3})) # intersection\n{1}\n set bool any all >>> any((True, False, True))\nTrue\n" }, { "answer_id": 32611847, "author": "deddu", "author_id": 2168258, "author_profile": "https://Stackoverflow.com/users/2168258", "pm_score": 1, "selected": false, "text": "def dump(fname,iterable):\n with open(fname,'w') as f:\n reduce(lambda x, y: f.write(unicode(y,'utf-8')), iterable)\n" }, { "answer_id": 33895037, "author": "MatthewRock", "author_id": 2373609, "author_profile": "https://Stackoverflow.com/users/2373609", "pm_score": 2, "selected": false, "text": "reduce reduce(lambda acc, elem: acc[:-1] + [acc[-1] + elem] if elem == \"\\n\" else acc + [elem], re.split(\"(\\n)\", \"a\\nb\\nc\\n\"), [])\n ['a\\n', 'b\\n', 'c\\n', '']\n" }, { "answer_id": 34625496, "author": "bjmc", "author_id": 845210, "author_profile": "https://Stackoverflow.com/users/845210", "pm_score": 2, "selected": false, "text": "reduce || vectors = (self.column_vector(getattr(self.table.c, column_name))\n for column_name in self.indexed_columns)\nconcatenated = reduce(lambda x, y: x.op('||')(y), vectors)\ncompiled = concatenated.compile(self.conn)\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/15995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
16,007
<p>Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.</p> <pre><code>if (System.IO.Directory.Exists(photosLocation)) { string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg"); if (files.Length &gt; 0) { // TODO: return the url of the first file found; } } </code></pre>
[ { "answer_id": 16032, "author": "Robin Robinson", "author_id": 1629, "author_profile": "https://Stackoverflow.com/users/1629", "pm_score": -1, "selected": false, "text": "string url = Request.ApplicationPath + \"/\" + photosLocation + \"/\" + files[0];\n" }, { "answer_id": 16039, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 5, "selected": true, "text": "photosLocation \"~/Images/\" ResolveUrl System.IO.Path string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);\nif (Directory.Exists(photosLocationPath))\n{\n string[] files = Directory.GetFiles(photosLocationPath, \"*.jpg\");\n if (files.Length > 0)\n {\n string filenameRelative = photosLocation + Path.GetFilename(files[0]) \n return Page.ResolveUrl(filenameRelative);\n }\n}\n" }, { "answer_id": 16040, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "// Here is your path\nString p = photosLocation + \"whatever.jpg\";\n\n// Here is the page address\nString pa = Page.Request.Url.AbsoluteUri;\n\n// Take the page name \nString pn = Page.Request.Url.LocalPath;\n\n// Here is the server address \nString sa = pa.Replace(pn, \"\");\n\n// Take the physical location of the page \nString pl = Page.Request.PhysicalPath;\n\n// Replace the backslash with slash in your path \npl = pl.Replace(\"\\\\\", \"/\"); \np = p.Replace(\"\\\\\", \"/\");\n\n// Root path \nString rp = pl.Replace(pn, \"\");\n\n// Take out same path \nString final = p.Replace(rp, \"\");\n\n// So your picture's address is \nString path = sa + final;\n" }, { "answer_id": 16188, "author": "Andy Rose", "author_id": 1762, "author_profile": "https://Stackoverflow.com/users/1762", "pm_score": 3, "selected": false, "text": "myImage.ImageUrl = Page.ResolveUrl(photoURL);\nmyImage.ImageUrl = myImage.ResolveUrl(photoURL);\n myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);\n" }, { "answer_id": 8985747, "author": "NxtWhat", "author_id": 1166821, "author_profile": "https://Stackoverflow.com/users/1166821", "pm_score": 2, "selected": false, "text": "HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + \"ImageName\";\n" }, { "answer_id": 12897607, "author": "Rafael Herscovici", "author_id": 572771, "author_profile": "https://Stackoverflow.com/users/572771", "pm_score": 4, "selected": false, "text": "private string MapURL(string path)\n{\n string appPath = Server.MapPath(\"/\").ToLower();\n return string.Format(\"/{0}\", path.ToLower().Replace(appPath, \"\").Replace(@\"\\\", \"/\"));\n }\n" }, { "answer_id": 13101286, "author": "Ross Presser", "author_id": 864696, "author_profile": "https://Stackoverflow.com/users/864696", "pm_score": 4, "selected": false, "text": "Site named \"tempuri.com/\" rooted at c:\\domains\\site\nvirtual directory \"~/files\" at c:\\data\\files\nvirtual directory \"~/files/vip\" at c:\\data\\VIPcust\\files\n Server.MapPath(\"~/files/vip/readme.txt\") \n = \"c:\\data\\VIPcust\\files\\readme.txt\"\n MagicResolve(\"c:\\data\\VIPcust\\files\\readme.txt\") \n = \"http://tempuri.com/files/vip/readme.txt\"\n" }, { "answer_id": 13452579, "author": "adripanico", "author_id": 1552386, "author_profile": "https://Stackoverflow.com/users/1552386", "pm_score": 0, "selected": false, "text": "?HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)\n\"http://localhost:1714\"\n ?HttpRuntime.AppDomainAppVirtualPath\n\"/\"\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762/" ]
16,067
<p>I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran.</p> <p>What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, <a href="http://www.swig.org/" rel="nofollow noreferrer">SWIG</a>, <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html" rel="nofollow noreferrer">Boost.Python</a>, <a href="http://cython.org/" rel="nofollow noreferrer">Cython</a> or <a href="http://www.riverbankcomputing.co.uk/software/sip/intro" rel="nofollow noreferrer">Python SIP</a>?</p> <p>For this particular use case (a fitting library), I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.</p>
[ { "answer_id": 28467, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 3, "selected": false, "text": "Image* unary(boost::python::object op, Image& im)\n{\n Image* out = new Image(im.width(), im.height(), im.channels());\n for(unsigned int i=0; i<im.size(); i++)\n {\n (*out)[i] == extract<float>(op(im[i]));\n }\n return out;\n}\n import image\nim = image.load('somefile.tiff')\ndouble_im = image.unary(lambda x: 2.0*x, im)\n" }, { "answer_id": 151006, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "numpy" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199/" ]
16,074
<p>Is it possible to open a project in Visual Studio 2008 without opening all the files that were previously opened last time I had the project open. I have a habit of keeping many files open as I am working on them, so next time I open the project, it (very slowly) loads up a bunch of files into the editor that I may not even need open. I have searched through the settings and cannot find anything to stop this behavior. </p>
[ { "answer_id": 16251, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": false, "text": "Options > Environment > Keyboard Window.CloseAllDocuments ALT+X" }, { "answer_id": 57848, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 5, "selected": false, "text": "EnvironmentEvents EnvironmentEvents Public Sub CloseDocsOnExit() Handles SolutionEvents.BeforeClosing\n DTE.ExecuteCommand(\"Window.CloseAllDocuments\")\nEnd Sub\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1749/" ]
16,096
<p>In WPF, how would I apply multiple styles to a <code>FrameworkElement</code>? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other.</p>
[ { "answer_id": 16108, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 5, "selected": false, "text": "<Style TargetType=\"TextBlock\">\n <Setter Property=\"Margin\" Value=\"3\" />\n</Style>\n\n<Style x:Key=\"AlwaysVerticalStyle\" TargetType=\"TextBlock\" \n BasedOn=\"{StaticResource {x:Type TextBlock}}\">\n <Setter Property=\"VerticalAlignment\" Value=\"Top\" />\n</Style>\n" }, { "answer_id": 167308, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 8, "selected": true, "text": "BasedOn <Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Page.Resources>\n <Style x:Key=\"baseStyle\" TargetType=\"FrameworkElement\">\n <Setter Property=\"HorizontalAlignment\" Value=\"Left\"/>\n </Style>\n <Style TargetType=\"Button\" BasedOn=\"{StaticResource baseStyle}\">\n <Setter Property=\"Content\" Value=\"Hello World\"/>\n </Style>\n </Page.Resources>\n <Grid>\n <Button Width=\"200\" Height=\"50\"/>\n </Grid>\n</Page>\n TargetType ButtonBase <Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Page.Resources>\n <Style x:Key=\"baseStyle\" TargetType=\"FrameworkElement\">\n <Setter Property=\"HorizontalAlignment\" Value=\"Left\"/>\n </Style>\n <Style x:Key=\"derivedStyle\" TargetType=\"ButtonBase\" BasedOn=\"{StaticResource baseStyle}\">\n <Setter Property=\"Content\" Value=\"Hello World\"/>\n </Style>\n </Page.Resources>\n <Grid>\n <Button Width=\"200\" Height=\"50\" Style=\"{StaticResource derivedStyle}\"/>\n </Grid>\n</Page>\n" }, { "answer_id": 204311, "author": "Dave", "author_id": 28197, "author_profile": "https://Stackoverflow.com/users/28197", "pm_score": 1, "selected": false, "text": "public class MyTreeStyleSelector : StyleSelector\n{\n public Style DefaultStyle\n {\n get;\n set;\n }\n\n public Style NewStyle\n {\n get;\n set;\n }\n\n public override Style SelectStyle(object item, DependencyObject container)\n {\n ItemsControl ctrl = ItemsControl.ItemsControlFromItemContainer(container);\n\n //apply to only the first element in the container (new node)\n if (item == ctrl.Items[0])\n {\n return NewStyle;\n }\n else\n {\n //otherwise use the default style\n return DefaultStyle;\n }\n }\n}\n" }, { "answer_id": 410430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<Button\n Content=\"This is an example of a button using two merged styles\">\n <Button.Style>\n <ext:MergedStyles\n BasedOn=\"{StaticResource FirstStyle}\"\n MergeStyle=\"{StaticResource SecondStyle}\"/>\n </Button.Style>\n</Button>\n" }, { "answer_id": 1866600, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 6, "selected": false, "text": "<Style TargetType=\"Button\" x:Key=\"BaseButtonStyle\">\n <Setter Property=\"Margin\" Value=\"10\" />\n</Style>\n<Style TargetType=\"Button\" x:Key=\"RedButtonStyle\" BasedOn=\"{StaticResource BaseButtonStyle}\">\n <Setter Property=\"Foreground\" Value=\"Red\" />\n</Style>\n [MarkupExtensionReturnType(typeof(Style))]\npublic class MultiStyleExtension : MarkupExtension\n{\n}\n public MultiStyleExtension(params string[] inputResourceKeys)\n{\n}\n <Button Style=\"{local:MultiStyle BigButtonStyle, GreenButtonStyle}\" … />\n public MultiStyleExtension(string inputResourceKey1, string inputResourceKey2)\n{\n}\n private string[] resourceKeys;\n\npublic MultiStyleExtension(string inputResourceKeys)\n{\n if (inputResourceKeys == null)\n {\n throw new ArgumentNullException(\"inputResourceKeys\");\n }\n\n this.resourceKeys = inputResourceKeys.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (this.resourceKeys.Length == 0)\n {\n throw new ArgumentException(\"No input resource keys specified.\");\n }\n}\n public static void Merge(this Style style1, Style style2)\n{\n if (style1 == null)\n {\n throw new ArgumentNullException(\"style1\");\n }\n if (style2 == null)\n {\n throw new ArgumentNullException(\"style2\");\n }\n\n if (style1.TargetType.IsAssignableFrom(style2.TargetType))\n {\n style1.TargetType = style2.TargetType;\n }\n\n if (style2.BasedOn != null)\n {\n Merge(style1, style2.BasedOn);\n }\n\n foreach (SetterBase currentSetter in style2.Setters)\n {\n style1.Setters.Add(currentSetter);\n }\n\n foreach (TriggerBase currentTrigger in style2.Triggers)\n {\n style1.Triggers.Add(currentTrigger);\n }\n\n // This code is only needed when using DynamicResources.\n foreach (object key in style2.Resources.Keys)\n {\n style1.Resources[key] = style2.Resources[key];\n }\n}\n style1.Merge(style2);\n <Button Style=\"{local:MultiStyle {StaticResource BigButtonStyle}, {StaticResource GreenButtonStyle}}\" … />\n public MultiStyleExtension(params Style[] styles)\n{\n}\n Style currentStyle = new StaticResourceExtension(currentResourceKey).ProvideValue(serviceProvider)\n public override object ProvideValue(IServiceProvider serviceProvider)\n{\n Style resultStyle = new Style();\n\n foreach (string currentResourceKey in resourceKeys)\n {\n Style currentStyle = new StaticResourceExtension(currentResourceKey).ProvideValue(serviceProvider)\n if (currentStyle == null)\n {\n throw new InvalidOperationException(\"Could not find style with resource key \" + currentResourceKey + \".\");\n }\n\n resultStyle.Merge(currentStyle);\n }\n return resultStyle;\n}\n <Window.Resources>\n <Style TargetType=\"Button\" x:Key=\"SmallButtonStyle\">\n <Setter Property=\"Width\" Value=\"120\" />\n <Setter Property=\"Height\" Value=\"25\" />\n <Setter Property=\"FontSize\" Value=\"12\" />\n </Style>\n\n <Style TargetType=\"Button\" x:Key=\"GreenButtonStyle\">\n <Setter Property=\"Foreground\" Value=\"Green\" />\n </Style>\n\n <Style TargetType=\"Button\" x:Key=\"BoldButtonStyle\">\n <Setter Property=\"FontWeight\" Value=\"Bold\" />\n </Style>\n</Window.Resources>\n\n<Button Style=\"{local:MultiStyle SmallButtonStyle GreenButtonStyle BoldButtonStyle}\" Content=\"Small, green, bold\" />\n" }, { "answer_id": 12730626, "author": "Shahar Prish", "author_id": 594571, "author_profile": "https://Stackoverflow.com/users/594571", "pm_score": 2, "selected": false, "text": "<TextBlock Text=\"Test\"\n local:CompoundStyle.StyleKeys=\"headerStyle,textForMessageStyle,centeredStyle\"/>\n" }, { "answer_id": 21568120, "author": "Sérgio Henrique", "author_id": 3273517, "author_profile": "https://Stackoverflow.com/users/3273517", "pm_score": 1, "selected": false, "text": " public override Style SelectStyle(object item, DependencyObject container)\n {\n\n PropertyInfo p = item.GetType().GetProperty(\"GroupBy\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n PropertyGroupDescription propertyGroupDescription = (PropertyGroupDescription)p.GetValue(item);\n\n if (propertyGroupDescription != null && propertyGroupDescription.PropertyName == \"Title\" )\n {\n return this.TitleStyle;\n }\n\n if (propertyGroupDescription != null && propertyGroupDescription.PropertyName == \"Date\")\n {\n return this.DateStyle;\n }\n\n return null;\n }\n" }, { "answer_id": 46163919, "author": "google dev", "author_id": 7206675, "author_profile": "https://Stackoverflow.com/users/7206675", "pm_score": 2, "selected": false, "text": "AttachedProperty public static class Css\n{\n\n public static string GetClass(DependencyObject element)\n {\n if (element == null)\n throw new ArgumentNullException(\"element\");\n\n return (string)element.GetValue(ClassProperty);\n }\n\n public static void SetClass(DependencyObject element, string value)\n {\n if (element == null)\n throw new ArgumentNullException(\"element\");\n\n element.SetValue(ClassProperty, value);\n }\n\n\n public static readonly DependencyProperty ClassProperty =\n DependencyProperty.RegisterAttached(\"Class\", typeof(string), typeof(Css), \n new PropertyMetadata(null, OnClassChanged));\n\n private static void OnClassChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ui = d as FrameworkElement;\n Style newStyle = new Style();\n\n if (e.NewValue != null)\n {\n var names = e.NewValue as string;\n var arr = names.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (var name in arr)\n {\n Style style = ui.FindResource(name) as Style;\n foreach (var setter in style.Setters)\n {\n newStyle.Setters.Add(setter);\n }\n foreach (var trigger in style.Triggers)\n {\n newStyle.Triggers.Add(trigger);\n }\n }\n }\n ui.Style = newStyle;\n }\n}\n <Window x:Class=\"MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:style_a_class_like_css\"\n mc:Ignorable=\"d\"\n Title=\"MainWindow\" Height=\"150\" Width=\"325\">\n <Window.Resources>\n\n <Style TargetType=\"TextBlock\" x:Key=\"Red\" >\n <Setter Property=\"Foreground\" Value=\"Red\"/>\n </Style>\n\n <Style TargetType=\"TextBlock\" x:Key=\"Green\" >\n <Setter Property=\"Foreground\" Value=\"Green\"/>\n </Style>\n \n <Style TargetType=\"TextBlock\" x:Key=\"Size18\" >\n <Setter Property=\"FontSize\" Value=\"18\"/>\n <Setter Property=\"Margin\" Value=\"6\"/>\n </Style>\n\n <Style TargetType=\"TextBlock\" x:Key=\"Bold\" >\n <Setter Property=\"FontWeight\" Value=\"Bold\"/>\n </Style>\n\n </Window.Resources>\n <StackPanel>\n \n <Button Content=\"Button\" local:Css.Class=\"Red Bold\" Width=\"75\"/>\n <Button Content=\"Button\" local:Css.Class=\"Red Size18\" Width=\"75\"/>\n <Button Content=\"Button\" local:Css.Class=\"Green Size18 Bold\" Width=\"75\"/>\n\n </StackPanel>\n</Window>\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ]
16,097
<p>Here is the scenario that I have. I have a cvs repository in one location (A) and I want to replicate it and keep it in sync with a repository in another location(B). This would be a single directional sync from A to B. What is the best way to do this? If it is not really feasible in CVS then which source code control system would you recommend to accomplish this? Thanks</p>
[ { "answer_id": 16101, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": true, "text": "rsync xcopy robocopy" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1353/" ]
16,100
<p>What's the best way to convert a string to an enumeration value in C#?</p> <p>I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.</p> <p>In an ideal world, I could do something like this:</p> <pre><code>StatusEnum MyStatus = StatusEnum.Parse(&quot;Active&quot;); </code></pre> <p>but that isn't a valid code.</p>
[ { "answer_id": 16103, "author": "DavidWhitney", "author_id": 1297, "author_profile": "https://Stackoverflow.com/users/1297", "pm_score": 7, "selected": false, "text": "SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), \"EnumValue\");\n" }, { "answer_id": 16104, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 12, "selected": true, "text": "Enum.TryParse(\"Active\", out StatusEnum myStatus);\n out myStatus StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), \"Active\", true);\n public static T ParseEnum<T>(string value)\n{\n return (T) Enum.Parse(typeof(T), value, true);\n}\n StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>(\"Active\");\n public static T ToEnum<T>(this string value)\n{\n return (T) Enum.Parse(typeof(T), value, true);\n}\n\nStatusEnum MyStatus = \"Active\".ToEnum<StatusEnum>();\n public static T ToEnum<T>(this string value, T defaultValue) \n{\n if (string.IsNullOrEmpty(value))\n {\n return defaultValue;\n }\n\n T result;\n return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;\n}\n StatusEnum MyStatus = \"Active\".ToEnum(StatusEnum.None);\n string string 1234.ToString().ToEnum(StatusEnum.None)" }, { "answer_id": 16107, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 4, "selected": false, "text": "StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), \"Active\");\n" }, { "answer_id": 16112, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 5, "selected": false, "text": "object Enum.Parse(System.Type enumType, string value, bool ignoreCase);\n enum Mood\n {\n Angry,\n Happy,\n Sad\n } \n\n // ...\n Mood m = (Mood) Enum.Parse(typeof(Mood), \"Happy\", true);\n Console.WriteLine(\"My mood is: {0}\", m.ToString());" }, { "answer_id": 16131, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "// str.ToEnum<EnumType>()\nT static ToEnum<T>(this string str) \n{ \n return (T) Enum.Parse(typeof(T), str);\n}\n" }, { "answer_id": 38711, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 8, "selected": false, "text": "Enum.Parse() Enum.ToString() Dictionary<String,YourEnum>" }, { "answer_id": 12199994, "author": "gap", "author_id": 438205, "author_profile": "https://Stackoverflow.com/users/438205", "pm_score": 4, "selected": false, "text": "public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct\n{\n TEnum tmp; \n if (!Enum.TryParse<TEnum>(value, true, out tmp))\n {\n tmp = new TEnum();\n }\n return tmp;\n}\n" }, { "answer_id": 19431735, "author": "jite.gs", "author_id": 2891293, "author_profile": "https://Stackoverflow.com/users/2891293", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Parses string to TEnum without try/catch and .NET 4.5 TryParse()\n/// </summary>\npublic static bool TryParseToEnum<TEnum>(string probablyEnumAsString_, out TEnum enumValue_) where TEnum : struct\n{\n enumValue_ = (TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0);\n if(!Enum.IsDefined(typeof(TEnum), probablyEnumAsString_))\n return false;\n\n enumValue_ = (TEnum) Enum.Parse(typeof(TEnum), probablyEnumAsString_);\n return true;\n}\n" }, { "answer_id": 20394856, "author": "Erwin Mayer", "author_id": 541420, "author_profile": "https://Stackoverflow.com/users/541420", "pm_score": 9, "selected": false, "text": "Enum.TryParse<T>(String, T) StatusEnum myStatus;\nEnum.TryParse(\"Active\", out myStatus);\n Enum.TryParse(\"Active\", out StatusEnum myStatus);\n" }, { "answer_id": 21674259, "author": "Foyzul Karim", "author_id": 326597, "author_profile": "https://Stackoverflow.com/users/326597", "pm_score": 5, "selected": false, "text": "public static T ToEnum<T>(this string value, bool ignoreCase = true)\n{\n return (T) Enum.Parse(typeof (T), value, ignoreCase);\n}\n FilterType FilterType filterType = type.ToEnum<FilterType>();\n" }, { "answer_id": 27378161, "author": "Nelly", "author_id": 3181564, "author_profile": "https://Stackoverflow.com/users/3181564", "pm_score": 4, "selected": false, "text": "public static T ParseEnum<T>(string value, T defaultValue) where T : struct\n{\n try\n {\n T enumValue;\n if (!Enum.TryParse(value, true, out enumValue))\n {\n return defaultValue;\n }\n return enumValue;\n }\n catch (Exception)\n {\n return defaultValue;\n }\n}\n StatusEnum MyStatus = EnumUtil.ParseEnum(\"Active\", StatusEnum.None);\n" }, { "answer_id": 31157772, "author": "Patrik Lindström", "author_id": 648076, "author_profile": "https://Stackoverflow.com/users/648076", "pm_score": 2, "selected": false, "text": "StatusEnum MyStatus = Enum<StatusEnum>.Parse(\"Active\");\n" }, { "answer_id": 32064171, "author": "Rae Lee", "author_id": 5113582, "author_profile": "https://Stackoverflow.com/users/5113582", "pm_score": 2, "selected": false, "text": "public static T ParseEnum<T>(string value) //function declaration \n{\n return (T) Enum.Parse(typeof(T), value);\n}\n\nImportance imp = EnumUtil.ParseEnum<Importance>(\"Active\"); //function call\n using System;\n\nclass Program\n{\n enum PetType\n {\n None,\n Cat = 1,\n Dog = 2\n }\n\n static void Main()\n {\n\n // Possible user input:\n string value = \"Dog\";\n\n // Try to convert the string to an enum:\n PetType pet = (PetType)Enum.Parse(typeof(PetType), value);\n\n // See if the conversion succeeded:\n if (pet == PetType.Dog)\n {\n Console.WriteLine(\"Equals dog.\");\n }\n }\n}\n-------------\nOutput\n\nEquals dog.\n" }, { "answer_id": 32897493, "author": "alhpe", "author_id": 2998185, "author_profile": "https://Stackoverflow.com/users/2998185", "pm_score": 3, "selected": false, "text": "namespace System\n{\n public static class StringExtensions\n {\n\n public static bool TryParseAsEnum<T>(this string value, out T output) where T : struct\n {\n T result;\n\n var isEnum = Enum.TryParse(value, out result);\n\n output = isEnum ? result : default(T);\n\n return isEnum;\n }\n }\n}\n using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;\nusing static System.Console;\n\nprivate enum Countries\n {\n NorthAmerica,\n Europe,\n Rusia,\n Brasil,\n China,\n Asia,\n Australia\n }\n\n [TestMethod]\n public void StringExtensions_On_TryParseAsEnum()\n {\n var countryName = \"Rusia\";\n\n Countries country;\n var isCountry = countryName.TryParseAsEnum(out country);\n\n WriteLine(country);\n\n IsTrue(isCountry);\n AreEqual(Countries.Rusia, country);\n\n countryName = \"Don't exist\";\n\n isCountry = countryName.TryParseAsEnum(out country);\n\n WriteLine(country);\n\n IsFalse(isCountry);\n AreEqual(Countries.NorthAmerica, country); // the 1rst one in the enumeration\n }\n" }, { "answer_id": 34267134, "author": "Timo", "author_id": 543814, "author_profile": "https://Stackoverflow.com/users/543814", "pm_score": 5, "selected": false, "text": "enum Example\n{\n One = 1,\n Two = 2,\n Three = 3\n}\n Enum.(Try)Parse() | var x = Enum.Parse(\"One,Two\"); // x is now Three\n Three x 3 public static bool TryParse<T>(string value, out T result)\n where T : struct\n {\n var cacheKey = \"Enum_\" + typeof(T).FullName;\n\n // [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.\n // [Implementation off-topic.]\n var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);\n\n return enumDictionary.TryGetValue(value.Trim(), out result);\n }\n\n private static Dictionary<string, T> CreateEnumDictionary<T>()\n {\n return Enum.GetValues(typeof(T))\n .Cast<T>()\n .ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);\n }\n" }, { "answer_id": 37970592, "author": "Koray", "author_id": 1266873, "author_profile": "https://Stackoverflow.com/users/1266873", "pm_score": 2, "selected": false, "text": " private static Dictionary<Type, Dictionary<string, object>> dicEnum = new Dictionary<Type, Dictionary<string, object>>();\n public static T ToEnum<T>(this string value, T defaultValue)\n {\n var t = typeof(T);\n Dictionary<string, object> dic;\n if (!dicEnum.ContainsKey(t))\n {\n dic = new Dictionary<string, object>();\n dicEnum.Add(t, dic);\n foreach (var en in Enum.GetValues(t))\n dic.Add(en.ToString(), en);\n }\n else\n dic = dicEnum[t];\n if (!dic.ContainsKey(value))\n return defaultValue;\n else\n return (T)dic[value];\n }\n" }, { "answer_id": 39857622, "author": "isxaker", "author_id": 364429, "author_profile": "https://Stackoverflow.com/users/364429", "pm_score": 2, "selected": false, "text": "using System.Runtime.Serialization;\n\npublic static TEnum ToEnum<TEnum>(this string value, TEnum defaultValue) where TEnum : struct\n{\n if (string.IsNullOrEmpty(value))\n {\n return defaultValue;\n }\n\n TEnum result;\n var enumType = typeof(TEnum);\n foreach (var enumName in Enum.GetNames(enumType))\n {\n var fieldInfo = enumType.GetField(enumName);\n var enumMemberAttribute = ((EnumMemberAttribute[]) fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true)).FirstOrDefault();\n if (enumMemberAttribute?.Value == value)\n {\n return Enum.TryParse(enumName, true, out result) ? result : defaultValue;\n }\n }\n\n return Enum.TryParse(value, true, out result) ? result : defaultValue;\n}\n public enum OracleInstanceStatus\n{\n Unknown = -1,\n Started = 1,\n Mounted = 2,\n Open = 3,\n [EnumMember(Value = \"OPEN MIGRATE\")]\n OpenMigrate = 4\n}\n" }, { "answer_id": 40796886, "author": "Brian Rice", "author_id": 1027031, "author_profile": "https://Stackoverflow.com/users/1027031", "pm_score": 3, "selected": false, "text": "var value = \"Active\";\n\nStatusEnum status;\nif (!Enum.TryParse<StatusEnum>(value, out status))\n status = StatusEnum.Unknown;\n" }, { "answer_id": 42111987, "author": "Bartosz Gawron", "author_id": 6888393, "author_profile": "https://Stackoverflow.com/users/6888393", "pm_score": 2, "selected": false, "text": "public T ConvertStringValueToEnum<T>(string valueToParse){\n return Convert.ChangeType(Enum.Parse(typeof(T), valueToParse, true), typeof(T));\n}\n" }, { "answer_id": 52588251, "author": "AmirReza-Farahlagha", "author_id": 7059557, "author_profile": "https://Stackoverflow.com/users/7059557", "pm_score": 2, "selected": false, "text": " public static T GetEnum<T>(string model)\n {\n var newModel = GetStringForEnum(model);\n\n if (!Enum.IsDefined(typeof(T), newModel))\n {\n return (T)Enum.Parse(typeof(T), \"None\", true);\n }\n\n return (T)Enum.Parse(typeof(T), newModel.Result, true);\n }\n\n private static Task<string> GetStringForEnum(string model)\n {\n return Task.Run(() =>\n {\n Regex rgx = new Regex(\"[^a-zA-Z0-9 -]\");\n var nonAlphanumericData = rgx.Matches(model);\n if (nonAlphanumericData.Count < 1)\n {\n return model;\n }\n foreach (var item in nonAlphanumericData)\n {\n model = model.Replace((string)item, \"\");\n }\n return model;\n });\n }\n Enum Enum Enum" }, { "answer_id": 56251256, "author": "AHMED RABEE", "author_id": 1294770, "author_profile": "https://Stackoverflow.com/users/1294770", "pm_score": 1, "selected": false, "text": " <Extension()>\n Public Function ToEnum(Of TEnum)(ByVal value As String, ByVal defaultValue As TEnum) As TEnum\n If String.IsNullOrEmpty(value) Then\n Return defaultValue\n End If\n\n Return [Enum].Parse(GetType(TEnum), value, True)\n End Function\n" }, { "answer_id": 56251321, "author": "AHMED RABEE", "author_id": 1294770, "author_profile": "https://Stackoverflow.com/users/1294770", "pm_score": 2, "selected": false, "text": "public TEnum ToEnum<TEnum>(this string value, TEnum defaultValue){\nif (string.IsNullOrEmpty(value))\n return defaultValue;\n\nreturn Enum.Parse(typeof(TEnum), value, true);}\n" }, { "answer_id": 59076571, "author": "JCisar", "author_id": 1179562, "author_profile": "https://Stackoverflow.com/users/1179562", "pm_score": 3, "selected": false, "text": "Parse<TEnum>(stringValue) var MyStatus = Enum.Parse<StatusEnum >(\"Active\") var MyStatus = Enum.Parse<StatusEnum >(\"active\", true) [NullableContext(0)]\n public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct\n {\n return Enum.Parse<TEnum>(value, false);\n }\n\n [NullableContext(0)]\n public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct\n {\n TEnum result;\n Enum.TryParse<TEnum>(value, ignoreCase, true, out result);\n return result;\n }\n" }, { "answer_id": 59897419, "author": "Joel Wiklund", "author_id": 583037, "author_profile": "https://Stackoverflow.com/users/583037", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Runtime.Serialization;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Converters;\n\n[JsonConverter(typeof(StringEnumConverter))]\npublic enum MyType\n{\n [EnumMember(Value = \"person\")]\n Person,\n [EnumMember(Value = \"annan_deltagare\")]\n OtherPerson,\n [EnumMember(Value = \"regel\")]\n Rule,\n}\n using System;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Converters;\n\npublic static class EnumExtensions\n{\n public static TEnum ToEnum<TEnum>(this string value) where TEnum : Enum\n {\n var jsonString = $\"'{value.ToLower()}'\";\n return JsonConvert.DeserializeObject<TEnum>(jsonString, new StringEnumConverter());\n }\n\n public static bool EqualsTo<TEnum>(this string strA, TEnum enumB) where TEnum : Enum\n {\n TEnum enumA;\n try\n {\n enumA = strA.ToEnum<TEnum>();\n }\n catch\n {\n return false;\n }\n return enumA.Equals(enumB);\n }\n}\n public class Program\n{\n static public void Main(String[] args) \n { \n var myString = \"annan_deltagare\";\n var myType = myString.ToEnum<MyType>();\n var isEqual = myString.EqualsTo(MyType.OtherPerson);\n //Output: true\n } \n}\n" }, { "answer_id": 62345657, "author": "MBWise", "author_id": 2454604, "author_profile": "https://Stackoverflow.com/users/2454604", "pm_score": 1, "selected": false, "text": " public static T ParseEnum<T>(this string s, T defaultValue, bool ignoreCase = false) \n where T : struct, IComparable, IConvertible, IFormattable//If C# >=7.3: struct, System.Enum \n {\n if ((s?.Length ?? 0) == 0)\n {\n return defaultValue;\n }\n\n var valid = Enum.TryParse<T>(s, ignoreCase, out T res);\n\n if (!valid || !Enum.IsDefined(typeof(T), res))\n {\n throw new InvalidOperationException(\n $\"'{s}' is not a valid value of enum '{typeof(T).FullName}'!\");\n }\n return res;\n }\n" }, { "answer_id": 66977781, "author": "Felipe Augusto", "author_id": 8104755, "author_profile": "https://Stackoverflow.com/users/8104755", "pm_score": -1, "selected": false, "text": " public enum Store : short\n{\n [Description(\"Rio Big Store\")]\n Rio = 1\n}\n //The class also needs to be static, ok?\npublic static string GetDescription(this System.Enum enumValue)\n {\n FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());\n\n DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(\n typeof(DescriptionAttribute), false);\n\n if (attributes != null && attributes.Length > 0) return attributes[0].Description;\n else return enumValue.ToString();\n }\n var Desc = Store.Rio.GetDescription(); //Store is your Enum\n" }, { "answer_id": 69637069, "author": "Jordan Ryder", "author_id": 2088676, "author_profile": "https://Stackoverflow.com/users/2088676", "pm_score": 4, "selected": false, "text": "ColorEnum color = Enum.Parse<ColorEnum>(\"blue\");\n" }, { "answer_id": 71249113, "author": "Bloggrammer", "author_id": 12476466, "author_profile": "https://Stackoverflow.com/users/12476466", "pm_score": 3, "selected": false, "text": " public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct\n {\n if (string.IsNullOrWhiteSpace(value))\n return default(TEnum);\n\n return Enum.TryParse(value, true, out TEnum result) ? result : default(TEnum);\n\n }\n public static TEnum ToEnum<TEnum>(this string value, TEnum defaultValue = default) where TEnum : struct\n {\n if (string.IsNullOrWhiteSpace(value))\n return defaultValue ;\n\n return Enum.TryParse(value, true, out TEnum result) ? result : defaultValue ;\n\n }\n public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct\n{\n if (string.IsNullOrWhiteSpace(value))\n return default;\n\n return Enum.TryParse(value, true, out TEnum result) ? result : default;\n\n}\n" }, { "answer_id": 72832417, "author": "shvets", "author_id": 7432218, "author_profile": "https://Stackoverflow.com/users/7432218", "pm_score": 0, "selected": false, "text": "public enum StatusType {\n Success,\n Pending,\n Rejected\n}\n\nstatic class StatusTypeMethods {\n\n public static StatusType GetEnum(string type) {\n switch (type) {\n case nameof(StatusType.Success): return StatusType.Success;\n case nameof(StatusType.Pending): return StatusType.Pending;\n case nameof(StatusType.Rejected): return StatusType.Rejected;\n default:\n throw new ArgumentOutOfRangeException(nameof(type), type, null);\n };\n }\n}\n StatusType = StatusType.GetEnum(\"Success\");\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203/" ]
16,110
<p>I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents. </p> <p>The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome. </p> <p>The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.</p> <p><strong>Edit:</strong> The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again.</p>
[ { "answer_id": 16130, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": true, "text": "TextBox1.Select(0, TextBox1.Text.Length);\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1629/" ]
16,113
<p>Can I get some recommendations (preferably with some reasons) for good log analysis software for Apache 2.2 access log files?</p> <p>I have heard of <a href="http://www.webalizer.org/" rel="noreferrer">Webalizer</a> and <a href="http://awstats.sourceforge.net/" rel="noreferrer">AWStats</a>, but have never really used any of them, and would like to know:</p> <ul> <li>What they can do</li> <li>Why they are useful</li> <li>Interesting uses for them</li> </ul> <p>Any and all comments and thoughts are welcome.</p>
[ { "answer_id": 677965, "author": "cdonner", "author_id": 58880, "author_profile": "https://Stackoverflow.com/users/58880", "pm_score": 2, "selected": false, "text": " Google Woopra Awstats\nSunday, March 1, 2009 10 11 69\nMonday, March 2, 2009 13 14 85\nTuesday, March 3, 2009 13 14 96\nWednesday, March 4, 2009 21 28 91\nThursday, March 5, 2009 19 25 107\nFriday, March 6, 2009 12 10 88\nSaturday, March 7, 2009 12 14 100\nSunday, March 8, 2009 10 11 65\nMonday, March 9, 2009 13 14 78\nTuesday, March 10, 2009 17 13 96\nWednesday, March 11, 2009 18 16 87\nThursday, March 12, 2009 19 18 87\nFriday, March 13, 2009 12 13 66\nSaturday, March 14, 2009 11 7 52\nSunday, March 15, 2009 11 12 57\nMonday, March 16, 2009 13 15 92\nTuesday, March 17, 2009 24 22 102\nWednesday, March 18, 2009 18 16 79\nThursday, March 19, 2009 17 18 73\nFriday, March 20, 2009 16 11 70\nSaturday, March 21, 2009 24 26 67\nSunday, March 22, 2009 103 114 216\nMonday, March 23, 2009 232 223 117\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
16,142
<p>I've seen these words a lot around Subversion (and I guess general repository) discussions.<br> I have been using <strong>SVN</strong> for my projects for the last few years, but I've never grasped the complete concept of these directories.</p> <p>What do they mean?</p>
[ { "answer_id": 16151, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 5, "selected": false, "text": "branch trunk" }, { "answer_id": 16203, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 7, "selected": false, "text": "main rel1-maint 1.0" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914/" ]
16,155
<p><strong>Is there a way in PHP to overwrite a method declared by one interface in an interface extending that interface?</strong></p> <p>The Example:</p> <p>I'm probably doing something wrong, but here is what I have:</p> <pre><code>interface iVendor{ public function __construct($vendors_no = null); public function getName(); public function getVendors_no(); public function getZip(); public function getCountryCode(); public function setName($name); public function setVendors_no($vendors_no); public function setZip($zip); public function setCountryCode($countryCode); } interface iShipper extends iVendor{ public function __construct($vendors_no = null, $shipment = null); public function getTransitTime($shipment = null); public function getTransitCost($shipment = null); public function getCurrentShipment(); public function setCurrentShipment($shipment); public function getStatus($shipment = null); } </code></pre> <p>Normally in PHP, when you extend something, you can overwrite any method contained therein (right?). However, when one interface extends another, it won't let you. Unless I'm thinking about this wrong... When I implement the iShipper interface, I don't have to make the Shipper object extend the Vendor object (that implements the iVendor interface). I just say:</p> <pre><code>class FedEx implements iShipper{} </code></pre> <p>and make FedEx implement all of the methods from iVendor and iShipper. However, I need the <code>__construct</code> functions in iVendor and iShipper to be unique. I know I could take out the <code>$shipment = null</code>, but then it wouldn't be as convenient to create Shippers (by just passing in the vendors_no and the shipment while instantiating).</p> <p>Anyone know how to make this work? My fallback is to have to set the shipment by calling <code>$shipper-&gt;setShipment($shipment);</code> on the Shipper after I instantiate it, but I'm hoping for a way to get around having to do that...</p> <p><em>A little more explanation for the curious:</em><br> <em>The FedEx Object has methods that go to the FedEx site (using cURL) and gets an estimate for the Shipment in question. I have a UPS Object, a BAXGlobal Object, a Conway Object, etc. Each one has COMPLETELY different methods for actually getting the shipping estimate, but all the system needs to know is that they are a "shipper" and that the methods listed in the interface are callable on them (so it can treat them all exactly the same, and loop through them in a "shippers" array calling <code>getTransitX()</code> to find the best shipper for a shipment).</em> </p> <p><em>Each "Shipper" is also a "Vendor" though, and is treated as such in other parts of the system (getting and putting in the DB, etc. Our data design is a pile of crap, so FedEx is stored right alongside companies like Dunder Mifflin in the "Vendors" table, which means it gets to have all the properties of every other Vendor, but needs the extra properties and methods supplied by iShipper).</em></p>
[ { "answer_id": 16245, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 4, "selected": true, "text": "interface iVendor{\n public function getName();\n public function getVendors_no();\n public function getZip();\n public function getCountryCode();\n public function setName($name);\n public function setVendors_no($vendors_no);\n public function setZip($zip);\n public function setCountryCode($countryCode);\n}\n\ninterface iShipper extends iVendor{\n public function getTransitTime($shipment = null);\n public function getTransitCost($shipment = null);\n public function getCurrentShipment();\n public function setCurrentShipment($shipment);\n public function getStatus($shipment = null);\n}\n\nabstract class Shipper implements iShipper{ \n abstract public function __construct($vendors_no = null, $shipment = null); \n //a bunch of non-abstract common methods... \n}\n\nclass FedEx extends Shipper implements iShipper{ \n public function __construct($vendors_no = null, $shipment = null){\n //a bunch of setup code...\n }\n //all my FedEx specific methods...\n}\n" }, { "answer_id": 16409, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 0, "selected": false, "text": "abstract class Vendor implements iVendor {\n public function __construct() {\n whatever();\n }\n}\n\nabstract class Shipper implements iShipper {\n public function __construct() {\n something();\n }\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
16,178
<p>I need to programatically determine whether .NET 3.5 is installed. I thought it would be easy:</p> <pre><code>&lt;% Response.Write(Environment.Version.ToString()); %&gt; </code></pre> <p>Which returns "2.0.50727.1434" so no such luck...</p> <p>In my research I have that there are some rather obscure registry keys I can look at but I'm not sure if that is the route to go. Does anyone have any suggestions?</p>
[ { "answer_id": 16187, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "System.Web.Extensions\n" }, { "answer_id": 16202, "author": "sestocker", "author_id": 285, "author_profile": "https://Stackoverflow.com/users/285", "pm_score": 1, "selected": false, "text": "<%@ Page Language=\"C#\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<HTML>\n <HEAD>\n <TITLE>Test for the .NET Framework 3.5</TITLE>\n <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\" />\n <SCRIPT LANGUAGE=\"JavaScript\">\n <!--\n var dotNETRuntimeVersion = \"3.5.0.0\";\n\n function window::onload()\n {\n if (HasRuntimeVersion(dotNETRuntimeVersion))\n {\n result.innerText = \n \"This machine has the correct version of the .NET Framework 3.5.\"\n } \n else\n {\n result.innerText = \n \"This machine does not have the correct version of the .NET Framework 3.5.\" +\n \" The required version is v\" + dotNETRuntimeVersion + \".\";\n }\n result.innerText += \"\\n\\nThis machine's userAgent string is: \" + \n navigator.userAgent + \".\";\n }\n\n //\n // Retrieve the version from the user agent string and \n // compare with the specified version.\n //\n function HasRuntimeVersion(versionToCheck)\n {\n var userAgentString = \n navigator.userAgent.match(/.NET CLR [0-9.]+/g);\n\n if (userAgentString != null)\n {\n var i;\n\n for (i = 0; i < userAgentString.length; ++i)\n {\n if (CompareVersions(GetVersion(versionToCheck), \n GetVersion(userAgentString[i])) <= 0)\n return true;\n }\n }\n\n return false;\n }\n\n //\n // Extract the numeric part of the version string.\n //\n function GetVersion(versionString)\n {\n var numericString = \n versionString.match(/([0-9]+)\\.([0-9]+)\\.([0-9]+)/i);\n return numericString.slice(1);\n }\n\n //\n // Compare the 2 version strings by converting them to numeric format.\n //\n function CompareVersions(version1, version2)\n {\n for (i = 0; i < version1.length; ++i)\n {\n var number1 = new Number(version1[i]);\n var number2 = new Number(version2[i]);\n\n if (number1 < number2)\n return -1;\n\n if (number1 > number2)\n return 1;\n }\n\n return 0;\n }\n\n -->\n </SCRIPT>\n </HEAD>\n\n <BODY>\n <div id=\"result\" />\n </BODY>\n</HTML>\n" }, { "answer_id": 16229, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": true, "text": "static bool HasNet35()\n{\n try\n {\n AppDomain.CurrentDomain.Load(\n \"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\");\n return true;\n }\n catch\n {\n return false;\n }\n}\n" }, { "answer_id": 16299, "author": "sestocker", "author_id": 285, "author_profile": "https://Stackoverflow.com/users/285", "pm_score": 2, "selected": false, "text": "RegistryKey key = Registry\n .LocalMachine\n .OpenSubKey(\"Software\\\\Microsoft\\\\NET Framework Setup\\\\NDP\\\\v3.5\");\nreturn (key != null);\n" }, { "answer_id": 33974, "author": "skolima", "author_id": 3205, "author_profile": "https://Stackoverflow.com/users/3205", "pm_score": 0, "selected": false, "text": "GC.Collect Method (Int32, GCCollectionMode)" }, { "answer_id": 1612249, "author": "Phil", "author_id": 193962, "author_profile": "https://Stackoverflow.com/users/193962", "pm_score": 1, "selected": false, "text": " Environment.Version.CompareTo(new Version(4, 0));\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285/" ]
16,233
<p>The collection of fonts available to a web developer is depressingly limited. I remember reading long ago about TrueDoc, as a way of shipping fonts alongside a website - but it seems to have languished. Has anybody used this, or something similar? Is it supported by enough browsers? Am I missing a good solution?</p> <p>Note that a responsible web developer does not use fonts that are only available on Windows (and <em>especially</em> ones that are only available on Vista), nor do they use a technology that isn't supported by at least the majority of browsers.</p> <hr> <p><strong>Update:</strong> As several people have pointed out, there's nothing wrong with providing a list of fallback fonts for people who don't have the specific font you use. I do in fact always do this, and didn't mean to suggest that this was wrong.</p> <p>While my question was badly phrased, what I meant was that a designer should not make too many assumptions about what the client will have available. You should plan for how all users will see your site, not just for people using your own preferred setup.</p>
[ { "answer_id": 16247, "author": "Sven Hecht", "author_id": 1168, "author_profile": "https://Stackoverflow.com/users/1168", "pm_score": 1, "selected": false, "text": "@font-face {\n font-family: Garamond;\n src: url(garamond.eot), url(garamond.pfr);\n}\n" }, { "answer_id": 16255, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 5, "selected": true, "text": "@font-face" }, { "answer_id": 16456, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "font-family: Calibri, Tahoma, Helvetica, Sans-Serif;\n" }, { "answer_id": 18150, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 1, "selected": false, "text": "@font-face" }, { "answer_id": 18259, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 1, "selected": false, "text": "Verdana, Arial, Helvetica, sans-serif\n Gill Sans, Verdana, Arial, Helvetica, sans-serif\n Gill Sans\n" }, { "answer_id": 8691065, "author": "Ry-", "author_id": 707111, "author_profile": "https://Stackoverflow.com/users/707111", "pm_score": 2, "selected": false, "text": "@font-face @font-face {\n src: url('path to your font') format('woff|ttf|svg|eot|…');\n font-family: the name to use;\n font-weight: an optional weight;\n font-style: an optional style;\n} format('woff')" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000/" ]
16,248
<p>I'd like to implement a way of recording the version of a project within code, so that it can be used when testing and to help track bugs. It seems the best version number to use would just be the current revision number from Subversion. Is there an easy way to hook this number into a (C++ in my case) header file or something, which I can then get at in code? I guess this is a post commit hook or something?</p> <p>Does anyone have any experience of implementing this (with code to share, please?), or can suggest a better alternative? Thanks.</p>
[ { "answer_id": 16264, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "svn:keywords Rev $Rev$ $Rev: 256 $" }, { "answer_id": 16276, "author": "jmanning2k", "author_id": 1480, "author_profile": "https://Stackoverflow.com/users/1480", "pm_score": 5, "selected": false, "text": "echo -n \"#define VERSION 1.0.1-\" > version.h\nsvnversion -n . >> version.h\n" }, { "answer_id": 16492697, "author": "iCoder", "author_id": 666953, "author_profile": "https://Stackoverflow.com/users/666953", "pm_score": 3, "selected": false, "text": "SVNDEV := -D'SVN_REV=\"$(shell svnversion -n .)\"'\nCFLAGS := $(SVNDEV) ...\n SVN_REV printf (\"Version: SVN %s\\n\", SVN_REV);\n" }, { "answer_id": 43468392, "author": "Jesse", "author_id": 7603292, "author_profile": "https://Stackoverflow.com/users/7603292", "pm_score": 0, "selected": false, "text": "Makefile YourFile.dox sed \"s~RevNumber~$(shell svnversion ../)~g\" YourFile.dox > YourFileDummy.dox; doxygen YourFileDummy.dox\n YourFile.dox ...\nPROJECT_NUMBER = \"Revision RevNumber\"\n...\n sed RevNumber svnversion YourFileDummy.dox doxygen YourFileDummy.dox" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1169/" ]
16,265
<p>I'm working with LINQ for the first time and wanted to get the Mapping to work when I have a money type in SQL, but my domain object property is of type double. How can I express this in the XML file, or in code so that the mapping does not throw the usual "invalid cast" exception?</p>
[ { "answer_id": 16335, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": " <Column Name=\"Table1.Amount\" DbType=\"smallint\" Type=\"System.Int32\" \n Expression=\"CAST(Table1.Amount as int)\" />\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
16,298
<p>I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two:</p> <pre><code>subdomain.hostone.com --&gt; subdomain.hosttwo.com </code></pre> <p>I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '<strong>400 Bad Request</strong>' Error.</p> <p>Can anyone see what I'm doing wrong?</p>
[ { "answer_id": 16311, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 5, "selected": true, "text": "CNAME CNAME" }, { "answer_id": 16630, "author": "Brian G Swanson", "author_id": 1795, "author_profile": "https://Stackoverflow.com/users/1795", "pm_score": 4, "selected": false, "text": "\n<?\nHeader( \"HTTP/1.1 301 Moved Permanently\" ); \nHeader( \"Location: http://subdomain.hosttwo.com\" ); \n?>\n \n<%@ Language=VBScript %>\n<%\nResponse.Status=\"301 Moved Permanently\"\nResponse.AddHeader \"Location\",\"http://subdomain.hosttwo.com\"\n%>\n \n<script runat=\"server\">\nprivate void Page_Load(object sender, System.EventArgs e)\n{\nResponse.Status = \"301 Moved Permanently\";\nResponse.AddHeader(\"Location\",\"http://subdomain.hosttwo.com\");\n}\n</script>\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
16,306
<p>What would be the easiest way to separate the directory name from the file name when dealing with <code>SaveFileDialog.FileName</code> in C#?</p>
[ { "answer_id": 16313, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 0, "selected": false, "text": "string filename = dialog.Filename;\nstring path = filename.Substring(0, filename.LastIndexOf(\"\\\"));\nstring file = filename.Substring(filename.LastIndexOf(\"\\\") + 1);\n" }, { "answer_id": 16315, "author": "Jay Mooney", "author_id": 733, "author_profile": "https://Stackoverflow.com/users/733", "pm_score": 1, "selected": false, "text": "System.IO" }, { "answer_id": 16316, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 2, "selected": false, "text": "var file = new FileInfo(saveFileDialog.FileName);\nConsole.WriteLine(\"File is: \" + file.Name);\nConsole.WriteLine(\"Directory is: \" + file.DirectoryName);\n" }, { "answer_id": 16318, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 5, "selected": true, "text": "System.IO.Path.GetDirectoryName(saveDialog.FileName)\n System.IO.Path.GetFileName" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41/" ]
16,320
<p>I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions. </p> <blockquote> <p>Which is "better" and why?</p> </blockquote>
[ { "answer_id": 16342, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 1, "selected": false, "text": "DbController acrhive = new DbController(\"dev\");\nDbController prod = new DbController(\"prod\");\n" }, { "answer_id": 16357, "author": "Barrett Conrad", "author_id": 1227, "author_profile": "https://Stackoverflow.com/users/1227", "pm_score": 2, "selected": false, "text": "objPerson = new Person(id)\n\nobjPerson.name = \"George\"\n\nobjPerson.save()\n aryPeople = Person::getPeopleFromState(\"LA\")\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
16,330
<p>If you had to provide a wizard like form entry experience in mvc how would you abstract the page flow?</p>
[ { "answer_id": 41878, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "public class CreateAccountWizardController : Controller\n{\n public ActionRresult Step1()\n {\n }\n\n\n public ActionResult Step2()\n {\n }\n}\n" }, { "answer_id": 257555, "author": "CodeClimber", "author_id": 4724, "author_profile": "https://Stackoverflow.com/users/4724", "pm_score": 1, "selected": false, "text": "[RequiredStep(FlowStart = true)]\npublic ActionResult Confirm()\n{\n return View();\n}\n\n[RequiredStep (PreviousStep = \"Confirm\")]\npublic ActionResult ExecuteOrder()\n{\n return RedirectToAction(\"ThankYou\");\n}\n\n[RequiredStep(PreviousStep = \"ExecuteOrder\")]\npublic ActionResult ThankYou()\n{\n return View();\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
16,340
<p>Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).</p> <p>Here's what I have today:</p> <pre><code>struct SomeData : IEquatable&lt;SomeData&gt; { private readonly byte[] data; public SomeData(byte[] data) { if (null == data || data.Length &lt;= 0) { throw new ArgumentException("data"); } this.data = new byte[data.Length]; Array.Copy(data, this.data, data.Length); } public override bool Equals(object obj) { return obj is SomeData &amp;&amp; Equals((SomeData)obj); } public bool Equals(SomeData other) { if (other.data.Length != data.Length) { return false; } for (int i = 0; i &lt; data.Length; ++i) { if (data[i] != other.data[i]) { return false; } } return true; } public override int GetHashCode() { return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0); } } </code></pre> <p>Any thoughts?</p> <hr> <p>dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes). for example:</p> <pre><code>byte[] b1 = new byte[] { 1 }; byte[] b2 = new byte[] { 1 }; int h1 = b1.GetHashCode(); int h2 = b2.GetHashCode(); </code></pre> <p>With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.</p>
[ { "answer_id": 16381, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 6, "selected": false, "text": "Equals GetHashCode HashTable Dictionary<> GetHashCode Equals" }, { "answer_id": 425184, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": " public override int GetHashCode()\n {\n unchecked\n {\n var result = 0;\n foreach (byte b in _key)\n result = (result*31) ^ b;\n return result;\n }\n }\n" }, { "answer_id": 468084, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": " public static int ComputeHash(params byte[] data)\n {\n unchecked\n {\n const int p = 16777619;\n int hash = (int)2166136261;\n\n for (int i = 0; i < data.Length; i++)\n hash = (hash ^ data[i]) * p;\n\n hash += hash << 13;\n hash ^= hash >> 7;\n hash += hash << 3;\n hash ^= hash >> 17;\n hash += hash << 5;\n return hash;\n }\n }\n" }, { "answer_id": 22363320, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 2, "selected": false, "text": "public class MyHash : IEquatable<MyHash>\n{ \n public byte[] Val { get; private set; }\n\n public MyHash(byte[] val)\n {\n Val = val;\n }\n\n /// <summary>\n /// Test if this Class is equal to another class\n /// </summary>\n /// <param name=\"other\"></param>\n /// <returns></returns>\n public bool Equals(MyHash other)\n {\n if (other.Val.Length == this.Val.Length)\n {\n for (var i = 0; i < this.Val.Length; i++)\n {\n if (other.Val[i] != this.Val[i])\n {\n return false;\n }\n }\n\n return true;\n }\n else\n {\n return false;\n } \n }\n\n public override int GetHashCode()\n { \n var str = Convert.ToBase64String(Val);\n return str.GetHashCode(); \n }\n}\n // dictionary we use to check for collisions\n Dictionary<MyHash, bool> checkForDuplicatesDic = new Dictionary<MyHash, bool>();\n\n // used to generate random arrays\n Random rand = new Random();\n\n\n\n var now = DateTime.Now;\n\n for (var j = 0; j < 100; j++)\n {\n for (var i = 0; i < 5000; i++)\n {\n // create new array and populate it with random bytes\n byte[] randBytes = new byte[byte.MaxValue];\n rand.NextBytes(randBytes);\n\n MyHash h = new MyHash(randBytes);\n\n if (checkForDuplicatesDic.ContainsKey(h))\n {\n Console.WriteLine(\"Duplicate\");\n }\n else\n {\n checkForDuplicatesDic[h] = true;\n }\n }\n Console.WriteLine(j);\n checkForDuplicatesDic.Clear(); // clear dictionary every 5000 iterations\n }\n\n var elapsed = DateTime.Now - now;\n\n Console.Read();\n public override int GetHashCode() public override int GetHashCode()\n { \n var str = Convert.ToBase64String(Val);\n return str.GetHashCode(); \n }\n public override int GetHashCode()\n {\n // 7.1 seconds\n unchecked\n {\n const int p = 16777619;\n int hash = (int)2166136261;\n\n for (int i = 0; i < Val.Length; i++)\n hash = (hash ^ Val[i]) * p;\n\n hash += hash << 13;\n hash ^= hash >> 7;\n hash += hash << 3;\n hash ^= hash >> 17;\n hash += hash << 5;\n return hash;\n }\n }\n" }, { "answer_id": 25558241, "author": "Varty", "author_id": 2519526, "author_profile": "https://Stackoverflow.com/users/2519526", "pm_score": 0, "selected": false, "text": "private int? hashCode;\n\npublic override int GetHashCode()\n{\n if (!hashCode.HasValue)\n {\n var hash = 0;\n for (var i = 0; i < bytes.Length; i++)\n {\n hash = (hash << 4) + bytes[i];\n }\n hashCode = hash;\n }\n return hashCode.Value;\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948/" ]
16,363
<p>Starting with 2005, VS started this behavior of when starting debugging session it spawns up a webserver for every project in a solution. I have a solution with 15 projects so it takes a while and is a waste of resources. Is there a way to configure it differently besides just using IIS?</p>
[ { "answer_id": 5235353, "author": "EBarr", "author_id": 215068, "author_profile": "https://Stackoverflow.com/users/215068", "pm_score": 2, "selected": false, "text": "Always Start When Debugging" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1940/" ]
16,402
<p>I have a bunch of files that I need to be able to <em>transport</em> and <em>install</em> quickly. My current method for doing so is moving a flash drive with a readme file of where stuff goes whenever I need to move stuff, which is rather inelegant and cumbersome.</p> <p>My idea for a solution would be to write up a quick script to move files around that I could just click on. I've done some <strong><em>bash</em></strong> scripting before but <strong><em>batch</em></strong> scripting is a little odd to me. Does anyone have a good online reference guide I could use?</p> <p>An alternative soulution I could accept would be a program that makes an installer for you, though I'm a bit against that as I would lose a lot of control. However, I'd be alright with it if it was extremely simple,</p>
[ { "answer_id": 16416, "author": "Martin", "author_id": 770, "author_profile": "https://Stackoverflow.com/users/770", "pm_score": 3, "selected": true, "text": "robocopy robocopy" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/652/" ]
16,413
<p>Problem: I have an address field from an Access database which has been converted to SQL Server 2005. This field has everything all in one field. I need to parse out the address's individual sections into their appropriate fields in a normalized table. I need to do this for approximately 4,000 records, and it needs to be repeatable.</p> <p>Assumptions:</p> <ol> <li><p>Assume an address in the US (for now)</p> </li> <li><p>assume that the input string will sometimes contain an addressee (the person being addressed) and/or a second street address (i.e. Suite B)</p> </li> <li><p>states may be abbreviated</p> </li> <li><p>zip code could be standard 5 digits or zip+4</p> </li> <li><p>there are typos in some instances</p> </li> </ol> <p>UPDATE: In response to the questions posed, standards were not universally followed; I need need to store the individual values, not just geocode and errors means typo (corrected above)</p> <p>Sample Data:</p> <ul> <li><p>A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947</p> </li> <li><p>11522 Shawnee Road, Greenwood DE 19950</p> </li> <li><p>144 Kings Highway, S.W. Dover, DE 19901</p> </li> <li><p>Intergrated Const. Services 2 Penns Way Suite 405 New Castle, DE 19720</p> </li> <li><p>Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958</p> </li> <li><p>Nichols Excavation 2742 Pulaski Hwy Newark, DE 19711</p> </li> <li><p>2284 Bryn Zion Road, Smyrna, DE 19904</p> </li> <li><p>VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21</p> </li> <li><p>580 North Dupont Highway Dover, DE 19901</p> </li> <li><p>P.O. Box 778 Dover, DE 19903</p> </li> </ul>
[ { "answer_id": 16819, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 4, "selected": false, "text": "Public Function parseAddress(ByVal input As String) As Collection\n input = input.Replace(\",\", \"\")\n input = input.Replace(\" \", \" \")\n Dim splitString() As String = Split(input)\n Dim streetMarker() As String = New String() {\"street\", \"st\", \"st.\", \"avenue\", \"ave\", \"ave.\", \"blvd\", \"blvd.\", \"highway\", \"hwy\", \"hwy.\", \"box\", \"road\", \"rd\", \"rd.\", \"lane\", \"ln\", \"ln.\", \"circle\", \"circ\", \"circ.\", \"court\", \"ct\", \"ct.\"}\n Dim address1 As String\n Dim address2 As String = \"\"\n Dim city As String\n Dim state As String\n Dim zip As String\n Dim streetMarkerIndex As Integer\n\n zip = splitString(splitString.Length - 1).ToString()\n state = splitString(splitString.Length - 2).ToString()\n streetMarkerIndex = getLastIndexOf(splitString, streetMarker) + 1\n Dim sb As New StringBuilder\n\n For counter As Integer = streetMarkerIndex To splitString.Length - 3\n sb.Append(splitString(counter) + \" \")\n Next counter\n city = RTrim(sb.ToString())\n Dim addressIndex As Integer = 0\n\n For counter As Integer = 0 To streetMarkerIndex\n If IsNumeric(splitString(counter)) _\n Or splitString(counter).ToString.ToLower = \"po\" _\n Or splitString(counter).ToString().ToLower().Replace(\".\", \"\") = \"po\" Then\n addressIndex = counter\n Exit For\n End If\n Next counter\n\n sb = New StringBuilder\n For counter As Integer = addressIndex To streetMarkerIndex - 1\n sb.Append(splitString(counter) + \" \")\n Next counter\n\n address1 = RTrim(sb.ToString())\n\n sb = New StringBuilder\n\n If addressIndex = 0 Then\n If splitString(splitString.Length - 2).ToString() <> splitString(streetMarkerIndex + 1) Then\n For counter As Integer = streetMarkerIndex To splitString.Length - 2\n sb.Append(splitString(counter) + \" \")\n Next counter\n End If\n Else\n For counter As Integer = 0 To addressIndex - 1\n sb.Append(splitString(counter) + \" \")\n Next counter\n End If\n address2 = RTrim(sb.ToString())\n\n Dim output As New Collection\n output.Add(address1, \"Address1\")\n output.Add(address2, \"Address2\")\n output.Add(city, \"City\")\n output.Add(state, \"State\")\n output.Add(zip, \"Zip\")\n Return output\nEnd Function\n\nPrivate Function getLastIndexOf(ByVal sArray As String(), ByVal checkArray As String()) As Integer\n Dim sourceIndex As Integer = 0\n Dim outputIndex As Integer = 0\n For Each item As String In checkArray\n For Each source As String In sArray\n If source.ToLower = item.ToLower Then\n outputIndex = sourceIndex\n If item.ToLower = \"box\" Then\n outputIndex = outputIndex + 1\n End If\n End If\n sourceIndex = sourceIndex + 1\n Next\n sourceIndex = 0\n Next\n Return outputIndex\nEnd Function\n parseAddress 2299 Lewes-Georgetown Hwy\nA. P. Croll & Son \nGeorgetown\nDE\n19947\n" }, { "answer_id": 16887, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 7, "selected": false, "text": "{\n \"name\": \"1600 Amphitheatre Parkway, Mountain View, CA, USA\",\n \"Status\": {\n \"code\": 200,\n \"request\": \"geocode\"\n },\n \"Placemark\": [\n {\n \"address\": \"1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA\",\n \"AddressDetails\": {\n \"Country\": {\n \"CountryNameCode\": \"US\",\n \"AdministrativeArea\": {\n \"AdministrativeAreaName\": \"CA\",\n \"SubAdministrativeArea\": {\n \"SubAdministrativeAreaName\": \"Santa Clara\",\n \"Locality\": {\n \"LocalityName\": \"Mountain View\",\n \"Thoroughfare\": {\n \"ThoroughfareName\": \"1600 Amphitheatre Pkwy\"\n },\n \"PostalCode\": {\n \"PostalCodeNumber\": \"94043\"\n }\n }\n }\n }\n },\n \"Accuracy\": 8\n },\n \"Point\": {\n \"coordinates\": [-122.083739, 37.423021, 0]\n }\n }\n ]\n}\n" }, { "answer_id": 12797231, "author": "komal", "author_id": 1730707, "author_profile": "https://Stackoverflow.com/users/1730707", "pm_score": 2, "selected": false, "text": "$d=str_replace(\" \", \"+\", $address_url);\n$completeurl =\"http://maps.googleapis.com/maps/api/geocode/xml?address=\".$d.\"&sensor=true\"; \n$phpobject = simplexml_load_file($completeurl);\nprint_r($phpobject);\n" }, { "answer_id": 16448034, "author": "Matt", "author_id": 1048862, "author_profile": "https://Stackoverflow.com/users/1048862", "pm_score": 4, "selected": false, "text": "ID,Start,End,Segment,Verified,Candidate,Firm,FirstLine,SecondLine,LastLine,City,State,ZIPCode,County,DpvFootnotes,DeliveryPointBarcode,Active,Vacant,CMRA,MatchCode,Latitude,Longitude,Precision,RDI,RecordType,BuildingDefaultIndicator,CongressionalDistrict,Footnotes\n1,32,79,\"2299 Lewes-Georgetown Hwy, Georgetown, DE 19947\",N,,,,,,,,,,,,,,,,,,,,,,\n2,81,119,\"11522 Shawnee Road, Greenwood DE 19950\",Y,0,,11522 Shawnee Rd,,Greenwood DE 19950-5209,Greenwood,DE,19950,Sussex,AABB,199505209226,Y,N,N,Y,38.82865,-75.54907,Zip9,Residential,S,,AL,N#\n3,121,160,\"144 Kings Highway, S.W. Dover, DE 19901\",Y,0,,144 Kings Hwy,,Dover DE 19901-7308,Dover,DE,19901,Kent,AABB,199017308444,Y,N,N,Y,39.16081,-75.52377,Zip9,Commercial,S,,AL,L#\n4,190,232,\"2 Penns Way Suite 405 New Castle, DE 19720\",Y,0,,2 Penns Way Ste 405,,New Castle DE 19720-2407,New Castle,DE,19720,New Castle,AABB,197202407053,Y,N,N,Y,39.68332,-75.61043,Zip9,Commercial,H,,AL,N#\n5,247,285,\"33 Bridle Ridge Court, Lewes, DE 19958\",Y,0,,33 Bridle Ridge Cir,,Lewes DE 19958-8961,Lewes,DE,19958,Sussex,AABB,199588961338,Y,N,N,Y,38.72749,-75.17055,Zip7,Residential,S,,AL,L#\n6,306,339,\"2742 Pulaski Hwy Newark, DE 19711\",Y,0,,2742 Pulaski Hwy,,Newark DE 19702-3911,Newark,DE,19702,New Castle,AABB,197023911421,Y,N,N,Y,39.60328,-75.75869,Zip9,Commercial,S,,AL,A#\n7,341,378,\"2284 Bryn Zion Road, Smyrna, DE 19904\",Y,0,,2284 Bryn Zion Rd,,Smyrna DE 19977-3895,Smyrna,DE,19977,Kent,AABB,199773895840,Y,N,N,Y,39.23937,-75.64065,Zip7,Residential,S,,AL,A#N#\n8,406,450,\"1500 Serpentine Road, Suite 100 Baltimore MD\",Y,0,,1500 Serpentine Rd Ste 100,,Baltimore MD 21209-2034,Baltimore,MD,21209,Baltimore,AABB,212092034250,Y,N,N,Y,39.38194,-76.65856,Zip9,Commercial,H,,03,N#\n9,455,495,\"580 North Dupont Highway Dover, DE 19901\",Y,0,,580 N DuPont Hwy,,Dover DE 19901-3961,Dover,DE,19901,Kent,AABB,199013961803,Y,N,N,Y,39.17576,-75.5241,Zip9,Commercial,S,,AL,N#\n10,497,525,\"P.O. Box 778 Dover, DE 19903\",Y,0,,PO Box 778,,Dover DE 19903-0778,Dover,DE,19903,Kent,AABB,199030778781,Y,N,N,Y,39.20946,-75.57012,Zip5,Residential,P,,AL,\n" }, { "answer_id": 19735415, "author": "Sachin Prasad", "author_id": 2840147, "author_profile": "https://Stackoverflow.com/users/2840147", "pm_score": 2, "selected": false, "text": "P. O. Box 1410 Durham, NC 27702" }, { "answer_id": 26139807, "author": "Kim Ryan", "author_id": 4098466, "author_profile": "https://Stackoverflow.com/users/4098466", "pm_score": 2, "selected": false, "text": "Non matching part ''\nError '0'\nError descriptions ''\nCase all '2299 Lewes-Georgetown Hwy Georgetown DE 19947'\nCOMPONENTS ''\ncountry ''\npo_box_type ''\npost_box ''\npost_code '19947'\npre_cursor ''\nproperty_identifier '2299'\nproperty_name ''\nroad_box ''\nstreet 'Lewes-Georgetown'\nstreet_direction ''\nstreet_type 'Hwy'\nsub_property_identifier ''\nsubcountry 'DE'\nsuburb 'Georgetown'\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149/" ]
16,432
<p>Let's say that you want to output or concat strings. Which of the following styles do you prefer?</p> <ul> <li><p><code>var p = new { FirstName = "Bill", LastName = "Gates" };</code></p></li> <li><p><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName);</code></p></li> <li><p><code>Console.WriteLine(p.FirstName + " " + p.LastName);</code></p></li> </ul> <p>Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?</p> <p>Do you have any rational arguments to use one and not the other?</p> <p>I'd go for the second one.</p>
[ { "answer_id": 16449, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 3, "selected": false, "text": "Console.Write String.Format String.Format" }, { "answer_id": 16452, "author": "Mike", "author_id": 1573, "author_profile": "https://Stackoverflow.com/users/1573", "pm_score": 3, "selected": false, "text": "Console.WriteLine(\"User {0} accessed {1} on {2}.\", user.Name, fileName, timestamp);\nvs\nConsole.WriteLine(\"User \" + user.Name + \" accessed \" + fileName + \" on \" + timestamp + \".\");\n" }, { "answer_id": 16455, "author": "Nathan", "author_id": 541, "author_profile": "https://Stackoverflow.com/users/541", "pm_score": 3, "selected": false, "text": "string str = \"{0} {1} is my friend. {3}, {2} is my boss.\".FormatWith(prop1,prop2,prop3,prop4);\n string name = String.Format(ApplicationStrings.General.InformalUserNameFormat,this.FirstName,this.LastName);\n" }, { "answer_id": 16471, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": false, "text": " System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();\n\n var p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\n s.Start();\n Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n s.Stop();\n Console.WriteLine(\"Console.WriteLine(\\\"{0} {1}\\\", p.FirstName, p.LastName); took: \" + s.ElapsedMilliseconds + \"ms - \" + s.ElapsedTicks + \" ticks\");\n\n s.Reset();\n s.Start();\n Console.WriteLine(p.FirstName + \" \" + p.LastName);\n s.Stop();\n\n Console.WriteLine(\"Console.WriteLine(p.FirstName + \\\" \\\" + p.LastName); took: \" + s.ElapsedMilliseconds + \"ms - \" + s.ElapsedTicks + \" ticks\");\n Bill Gates\nConsole.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took: 2ms - 7280 ticks\nBill Gates\nConsole.WriteLine(p.FirstName + \" \" + p.LastName); took: 0ms - 67 ticks\n" }, { "answer_id": 16480, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 2, "selected": false, "text": "String.Format String.Format String.Format" }, { "answer_id": 17608, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 1, "selected": false, "text": "Console.WriteLine(String.Concat(p.FirstName,\" \",p.LastName));\n" }, { "answer_id": 17615, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 6, "selected": false, "text": "Bill Gates\nConsole.WriteLine(p.FirstName + \" \" + p.LastName); took: 8ms - 30488 ticks\nBill Gates\nConsole.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took: 0ms - 182 ticks\n Bill Gates\nConsole.WriteLine(FirstName + \" \" + LastName); took: 5ms - 20335 ticks\nBill Gates\nConsole.WriteLine(FirstName + \" \" + LastName); took: 0ms - 156 ticks\nBill Gates\nConsole.WriteLine(FirstName + \" \" + LastName); took: 0ms - 122 ticks\nBill Gates\nConsole.WriteLine(\"{0} {1}\", FirstName, LastName); took: 0ms - 181 ticks\nBill Gates\nConsole.WriteLine(\"{0} {1}\", FirstName, LastName); took: 0ms - 122 ticks\nBill Gates\nString.Concat(FirstName, \" \", LastName); took: 0ms - 142 ticks\nBill Gates\nString.Concat(FirstName, \" \", LastName); took: 0ms - 117 ticks\n" }, { "answer_id": 18300, "author": "Philippe", "author_id": 920, "author_profile": "https://Stackoverflow.com/users/920", "pm_score": 4, "selected": false, "text": "Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName); took (avg): 0ms - 689 ticks\nConsole.WriteLine(p.FirstName + \" \" + p.LastName); took (avg): 0ms - 683 ticks\n Stopwatch s = new Stopwatch();\n\nvar p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\n//First print to remove the initial cost\nConsole.WriteLine(p.FirstName + \" \" + p.LastName);\nConsole.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n\nint n = 100000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;\n\nfor (var i = 0; i < n; i++)\n{\n s.Start();\n Console.WriteLine(p.FirstName + \" \" + p.LastName);\n s.Stop();\n cElapsedMilliseconds += s.ElapsedMilliseconds;\n cElapsedTicks += s.ElapsedTicks;\n s.Reset();\n s.Start();\n Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n s.Stop();\n fElapsedMilliseconds += s.ElapsedMilliseconds;\n fElapsedTicks += s.ElapsedTicks;\n s.Reset();\n}\n\nConsole.Clear();\n\nConsole.WriteLine(\"Console.WriteLine(\\\"{0} {1}\\\", p.FirstName, p.LastName); took (avg): \" + (fElapsedMilliseconds / n) + \"ms - \" + (fElapsedTicks / n) + \" ticks\");\nConsole.WriteLine(\"Console.WriteLine(p.FirstName + \\\" \\\" + p.LastName); took (avg): \" + (cElapsedMilliseconds / n) + \"ms - \" + (cElapsedTicks / n) + \" ticks\");\n" }, { "answer_id": 18342, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 7, "selected": true, "text": "Stopwatch s = new Stopwatch();\n\nvar p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\nint n = 1000000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;\n\nstring result;\ns.Start();\nfor (var i = 0; i < n; i++)\n result = (p.FirstName + \" \" + p.LastName);\ns.Stop();\ncElapsedMilliseconds = s.ElapsedMilliseconds;\ncElapsedTicks = s.ElapsedTicks;\ns.Reset();\ns.Start();\nfor (var i = 0; i < n; i++)\n result = string.Format(\"{0} {1}\", p.FirstName, p.LastName);\ns.Stop();\nfElapsedMilliseconds = s.ElapsedMilliseconds;\nfElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\n\nConsole.Clear();\nConsole.WriteLine(n.ToString()+\" x result = string.Format(\\\"{0} {1}\\\", p.FirstName, p.LastName); took: \" + (fElapsedMilliseconds) + \"ms - \" + (fElapsedTicks) + \" ticks\");\nConsole.WriteLine(n.ToString() + \" x result = (p.FirstName + \\\" \\\" + p.LastName); took: \" + (cElapsedMilliseconds) + \"ms - \" + (cElapsedTicks) + \" ticks\");\nThread.Sleep(4000);\n" }, { "answer_id": 18467, "author": "Philippe", "author_id": 920, "author_profile": "https://Stackoverflow.com/users/920", "pm_score": 2, "selected": false, "text": " s.Start();\n for (var i = 0; i < n; i++)\n result = string.Concat(p.FirstName, \" \", p.LastName);\n s.Stop();\n ceElapsedMilliseconds = s.ElapsedMilliseconds;\n ceElapsedTicks = s.ElapsedTicks;\n s.Reset();\n 1000000 x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: 249ms - 3571621 ticks\n1000000 x result = (p.FirstName + \" \" + p.LastName); took: 65ms - 944948 ticks\n1000000 x result = string.Concat(p.FirstName, \" \", p.LastName); took: 54ms - 780524 ticks\n" }, { "answer_id": 24561, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 7, "selected": false, "text": "String.Format \"Firstname Lastname\" \"Lastname, Firstname.\"" }, { "answer_id": 115305, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 1, "selected": false, "text": "class Program {\n static void Main(string[] args) {\n\n var p = new { FirstName = \"Bill\", LastName = \"Gates\" };\n\n var tests = new[] {\n new { Name = \"Concat\", Action = new Action(delegate() { string x = p.FirstName + \" \" + p.LastName; }) },\n new { Name = \"Format\", Action = new Action(delegate() { string x = string.Format(\"{0} {1}\", p.FirstName, p.LastName); }) },\n new { Name = \"StringBuilder\", Action = new Action(delegate() {\n StringBuilder sb = new StringBuilder();\n sb.Append(p.FirstName);\n sb.Append(\" \");\n sb.Append(p.LastName);\n string x = sb.ToString();\n }) }\n };\n\n var Watch = new Stopwatch();\n foreach (var t in tests) {\n for (int i = 0; i < 5; i++) {\n Watch.Reset();\n long Elapsed = ElapsedTicks(t.Action, Watch, 10000);\n Console.WriteLine(string.Format(\"{0}: {1} ticks\", t.Name, Elapsed.ToString()));\n }\n }\n }\n\n public static long ElapsedTicks(Action ActionDelg, Stopwatch Watch, int Iterations) {\n Watch.Start();\n for (int i = 0; i < Iterations; i++) {\n ActionDelg();\n }\n Watch.Stop();\n return Watch.ElapsedTicks / Iterations;\n }\n}\n" }, { "answer_id": 856794, "author": "DonkeyMaster", "author_id": 5178, "author_profile": "https://Stackoverflow.com/users/5178", "pm_score": 2, "selected": false, "text": "Console.WriteLine(\"User {0} accessed {1} on {2}.\", \n user.Name, fileName, timestamp);\n Console.WriteLine(\"User \" + user.Name + \" accessed \" + fileName + \n \" on \" + timestamp + \".\");\n Console.WriteLine(\"{0} {1}\", p.FirstName, p.LastName);\n Console.WriteLine(p.FirstName + \" \" + p.LastName);\n string Concat() Join()" }, { "answer_id": 1822422, "author": "Jeremy McGee", "author_id": 3546, "author_profile": "https://Stackoverflow.com/users/3546", "pm_score": 5, "selected": false, "text": "string.Format()" }, { "answer_id": 13354257, "author": "Ludington", "author_id": 112794, "author_profile": "https://Stackoverflow.com/users/112794", "pm_score": 5, "selected": false, "text": "Stopwatch s = new Stopwatch();\n\nint n = 1000000;\nlong fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0, sbElapsedMilliseconds = 0, sbElapsedTicks = 0;\n\nRandom random = new Random(DateTime.Now.Millisecond);\n\nstring result;\ns.Start();\nfor (var i = 0; i < n; i++)\n result = (random.Next().ToString() + \" \" + random.Next().ToString());\ns.Stop();\ncElapsedMilliseconds = s.ElapsedMilliseconds;\ncElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\ns.Start();\nfor (var i = 0; i < n; i++)\n result = string.Format(\"{0} {1}\", random.Next().ToString(), random.Next().ToString());\ns.Stop();\nfElapsedMilliseconds = s.ElapsedMilliseconds;\nfElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\nStringBuilder sb = new StringBuilder();\ns.Start();\nfor(var i = 0; i < n; i++){\n sb.Clear();\n sb.Append(random.Next().ToString());\n sb.Append(\" \");\n sb.Append(random.Next().ToString());\n result = sb.ToString();\n}\ns.Stop();\nsbElapsedMilliseconds = s.ElapsedMilliseconds;\nsbElapsedTicks = s.ElapsedTicks;\ns.Reset();\n\nConsole.WriteLine(n.ToString() + \" x result = string.Format(\\\"{0} {1}\\\", p.FirstName, p.LastName); took: \" + (fElapsedMilliseconds) + \"ms - \" + (fElapsedTicks) + \" ticks\");\nConsole.WriteLine(n.ToString() + \" x result = (p.FirstName + \\\" \\\" + p.LastName); took: \" + (cElapsedMilliseconds) + \"ms - \" + (cElapsedTicks) + \" ticks\");\nConsole.WriteLine(n.ToString() + \" x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(\\\" \\\"); sb.Append(random.Next().ToString()); result = sb.ToString(); took: \" + (sbElapsedMilliseconds) + \"ms - \" + (sbElapsedTicks) + \" ticks\");\nConsole.WriteLine(\"****************\");\nConsole.WriteLine(\"Press Enter to Quit\");\nConsole.ReadLine();\n 1000000 x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: 513ms - 1499816 ticks\n1000000 x result = (p.FirstName + \" \" + p.LastName); took: 393ms - 1150148 ticks\n1000000 x sb.Clear();sb.Append(random.Next().ToString()); sb.Append(\" \"); sb.Append(random.Next().ToString()); result = sb.ToString(); took: 405ms - 1185816 ticks\n" }, { "answer_id": 30392913, "author": "atlaste", "author_id": 1031591, "author_profile": "https://Stackoverflow.com/users/1031591", "pm_score": 2, "selected": false, "text": "Console.WriteLine(string format, params object[] pars) string.Format string s = a + \"foo\" + b;\n string tmp1 = a;\nstring tmp2 = \"foo\" \nstring tmp3 = concat(tmp1, tmp2);\nstring tmp4 = b;\nstring s = concat(tmp3, tmp4);\n tmp ldstr concat concat string.Format string.Format string.Format CultureInfo double string.Format CultureInfo StringBuilder string.Format StringBuilder" }, { "answer_id": 31888031, "author": "Saragis", "author_id": 2789100, "author_profile": "https://Stackoverflow.com/users/2789100", "pm_score": 3, "selected": false, "text": "6.0 var name = \"Bill\";\nvar surname = \"Gates\";\nMessageBox.Show($\"Welcome to the show, {name} {surname}!\");\n" }, { "answer_id": 31955456, "author": "von v.", "author_id": 815073, "author_profile": "https://Stackoverflow.com/users/815073", "pm_score": 3, "selected": false, "text": "var p = new { FirstName = \"Bill\", LastName = \"Gates\" };\nvar fullname = $\"{p.FirstName} {p.LastName}\";\n var qs = string.Format(\"q1={0}&q2={1}&q3={2}&q4={3}&q5={4}&q6={5}\", \n someVar, anotherVarWithLongName, var3, var4, var5, var6)\n var qs=$\"q1={someVar}&q2={anotherVarWithLongName}&q3={var3}&q4={var4}&q5={var5}&q6={var6}\";\n" }, { "answer_id": 68137074, "author": "Misha Zaslavsky", "author_id": 2667173, "author_profile": "https://Stackoverflow.com/users/2667173", "pm_score": 1, "selected": false, "text": "6.0 Console.WriteLine($\"{p.FirstName} {p.LastName}\");\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/920/" ]
16,443
<p>Is it possible (in Vb.Net 2005), without manually parsing the dataset table properties, to create the table and add it to the database?</p> <p>We have old versions of our program on some machines, which obviously has our old database, and we are looking for a way to detect if there is a missing table and then generate the table based on the current status of the table in the dataset. We were re-scripting the table every time we released a new version (if new columns were added) but we would like to avoid this step if possible.</p>
[ { "answer_id": 16840, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": false, "text": "SqlCommand.ExecuteNonQuery()" }, { "answer_id": 13625295, "author": "Prahalad Gaggar", "author_id": 1841054, "author_profile": "https://Stackoverflow.com/users/1841054", "pm_score": 2, "selected": false, "text": "SqlConnection con = new SqlConnection(\"Data Source=.;uid=sa;pwd=sa123;database=Example1\");\ncon.Open();\nstring sql = \"Create Table abcd (\";\n\nforeach (DataColumn column in dt.Columns)\n{\n sql += \"[\" + column.ColumnName + \"] \" + \"nvarchar(50)\" + \",\";\n}\n\nsql = sql.TrimEnd(new char[] { ',' }) + \")\";\nSqlCommand cmd = new SqlCommand(sql, con);\nSqlDataAdapter da = new SqlDataAdapter(cmd);\ncmd.ExecuteNonQuery();\n\nusing (var adapter = new SqlDataAdapter(\"SELECT * FROM abcd\", con)) \nusing(var builder = new SqlCommandBuilder(adapter))\n{\n adapter.InsertCommand = builder.GetInsertCommand();\n adapter.Update(dt);\n}\ncon.Close();\n dt adapter.update(dt);\n //if you have a DataSet\nadapter.Update(ds.Tables[0]); \n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936/" ]
16,447
<p>I am trying to generate a report by querying 2 databases (Sybase) in classic ASP.</p> <p>I have created 2 connection strings:<br></p> <blockquote> <p>connA for databaseA<br> connB for databaseB</p> </blockquote> <p>Both databases are present on the same server (don't know if this matters)<br></p> <p>Queries:</p> <p><code>q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz=&quot;A&quot;</code></p> <p><code>q2 = SELECT columnA,columnB,...,columnZ FROM table2 a #temp b WHERE b.column1=a.columnB</code></p> <p>followed by:</p> <pre><code>response.Write(rstsql) &lt;br&gt; set rstSQL = CreateObject(&quot;ADODB.Recordset&quot;)&lt;br&gt; rstSQL.Open q1, connA&lt;br&gt; rstSQL.Open q2, connB </code></pre> <p>When I try to open up this page in a browser, I get error message:</p> <blockquote> <p>Microsoft OLE DB Provider for ODBC Drivers error '80040e37'</p> <p>[DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]#temp not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).</p> </blockquote> <p>Could anyone please help me understand what the problem is and help me fix it?</p> <p>Thanks.</p>
[ { "answer_id": 16474, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "\nSELECT a.columnA, a.columnB,..., a.columnZ\nFROM table2 a\nINNER JOIN (SELECT databaseA..table1.column1 \n FROM databaseA..table1\n WHERE databaseA..table1.xyz = 'A') b\n ON a.columnB = b.column1\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311/" ]
16,451
<p>I need to call a web service written in .NET from Java. The web service implements the WS-Security stack (either WSE 2 or WSE 3, it's not clear from the information I have). </p> <p>The information that I received from the service provider included WSDL, a policyCache.config file, some sample C# code, and a sample application that can successfully call the service.</p> <p>This isn't as useful as it sounds because it's not clear how I'm supposed to use this information to write a Java client. If the web service request isn't signed according to the policy then it is rejected by the service. I'm trying to use Apache Axis2 and I can't find any instructions on how I'm supposed to use the policyCahce.config file and the WSDL to generate a client.</p> <p>There are several examples that I have found on the Web but in all cases the authors of the examples had control of both the service and the client and so were able to make tweaks on both sides in order to get it to work. I'm not in that position.</p> <p>Has anyone done this successfully?</p>
[ { "answer_id": 16979, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 2, "selected": false, "text": "import java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.security.auth.callback.Callback;\nimport javax.security.auth.callback.CallbackHandler;\nimport javax.security.auth.callback.UnsupportedCallbackException;\n\nimport org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;\nimport org.apache.ws.security.WSConstants;\nimport org.apache.ws.security.WSPasswordCallback;\nimport org.apache.ws.security.handler.WSHandlerConstants;\n\npublic class ServiceTest implements CallbackHandler\n{\n\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n // set the password for our message.\n pc.setPassword(\"buddah\");\n }\n\n public static void main(String[] args){\n PatientServiceImplService locator = new PatientServiceImplService();\n PatientService service = locator.getPatientServiceImplPort();\n\n org.apache.cxf.endpoint.Client client = org.apache.cxf.frontend.ClientProxy.getClient(service);\n org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();\n\n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN + \" \" + WSHandlerConstants.TIMESTAMP);\n outProps.put(WSHandlerConstants.USER, \"joe\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n\n // Callback used to retrieve password for given user.\n outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ServiceTest.class.getName());\n\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n cxfEndpoint.getOutInterceptors().add(wssOut);\n\n\n try\n {\n List list = service.getInpatientCensus();\n for(Patient p : list){\n System.out.println(p.getFirstName() + \" \" + p.getLastName());\n }\n\n }\n catch (Exception e)\n {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1958/" ]
16,458
<p>I'm using <code>ColdFusion</code> to return a result set from a SQL database and turn it into a list.</p> <p>I need some way to generate an alphabetical navigation bar for that list. I have ColdFusion and the jQuery library available.</p> <p>I'm looking to generate something like this:</p> <pre><code>A | B | C | ...      - A - A - B - B - B - C - D </code></pre> <p>Where clicking on one of the letters drops you down the page to the first item for that letter. Not all 26 letters of the alphabet are necessarily in use.</p>
[ { "answer_id": 16555, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 3, "selected": false, "text": "<cfoutput>\n<cfloop from=\"#asc('A')#\" to=\"#asc('Z')#\" index=\"i\">\n <a href=\"###chr(i)#\">#chr(i)#</a>\n <cfif asc('Z') neq i>|</cfif>\n</cfloop>\n</cfoutput>\n <cfset currentLetter = \"\">\n<cfoutput query=\"data\">\n<cfif currentLetter neq left(data.name, 1)>\n <h3><a name=\"#ucase(left(data.name, 1))#\">#ucase(left(data.name, 1))#</a></h3>\n</cfif>\n<cfset currentLetter = left(data.name, 1)>\n#name#<br>\n</cfoutput>\n" }, { "answer_id": 67091, "author": "mjb", "author_id": 10064, "author_profile": "https://Stackoverflow.com/users/10064", "pm_score": 2, "selected": false, "text": "<cfquery datasource=\"#application.dsn#\" name=\"qMembers\">\nSELECT firstname,lastname, left(lastname,1) as indexLetter\nFROM member\nORDER BY indexLetter,lastName\n</cfquery>\n\n\n<p id=\"indexLetter\">\n<cfoutput query=\"qMembers\" group=\"indexLetter\">\n <a href=\"###qMembers.indexLetter#\">#UCase(qMembers.indexLetter)#</a>\n</cfoutput>\n</p>\n\n\n\n\n<cfif qMembers.recordCount>\n\n <table>\n\n <cfoutput query=\"qMembers\" group=\"indexLetter\">\n <tr>\n <th colspan=\"99\" style=\"background-color:##324E7C;\">\n <a name=\"#qMembers.indexLetter#\" style=\"float:left;\">#UCase(qMembers.indexLetter)#</a> \n <a href=\"##indexLetter\" style=\"color:##fff;float:right;\">index</a>\n </th>\n </tr>\n\n <cfoutput>\n <tr>\n <td><strong>#qMembers.lastName#</strong> #qMembers.firstName#</td>\n </tr>\n </cfoutput>\n </cfoutput>\n\n </table>\n\n<cfelse>\n <p>No Members were found</p>\n</cfif>\n" }, { "answer_id": 137090, "author": "alexp206", "author_id": 666, "author_profile": "https://Stackoverflow.com/users/666", "pm_score": 1, "selected": true, "text": "<cfquery datasource=\"#application.dsn#\" name=\"qTitles\">\nSELECT title, url, substr(titles,1,1) as indexLetter\nFROM list\nORDER BY indexLetter,title\n</cfquery>\n\n<cfset linkLetter = \"#asc('A')#\">\n<cfoutput query=\"titles\" group=\"indexletter\">\n <cfif chr(linkLetter) eq #qTitles.indexletter#>\n <a href=\"###ucase(qTitles.indexletter)#\">#ucase(qTitles.indexletter)#</a>\n <cfif asc('W') neq linkLetter>|</cfif>\n <cfset linkLetter = ++LinkLetter>\n <cfelse>\n <cfscript>\n while(chr(linkLetter) != qTitles.indexletter)\n {\n WriteOutput(\" \" & chr(linkLetter) & \" \");\n IF(linkLetter != asc('W')){WriteOutput(\"|\");};\n ++LinkLetter;\n }\n </cfscript>\n\n <a href=\"###ucase(qTitles.indexletter)#\">#ucase(qTitles.indexletter)#</a>\n <cfif asc('W') neq linkLetter>|</cfif>\n <cfset linkLetter = ++LinkLetter>\n </cfif>\n</cfoutput>\n\n<ul>\n<cfset currentLetter = \"\">\n<cfoutput query=\"qTitles\" group=\"title\">\n<cfif currentLetter neq #qTitles.indexletter#>\n <li><a name=\"#ucase(qTitles.indexletter)#\">#ucase(qTitles.indexletter)#</a></li>\n</cfif>\n<cfset currentLetter = #qTitles.indexletter#>\n<li><a href=\"#url#\">#title#</a></li>\n</cfoutput>\n</ul>\n" }, { "answer_id": 60471224, "author": "Bryan Elliott", "author_id": 1388588, "author_profile": "https://Stackoverflow.com/users/1388588", "pm_score": 0, "selected": false, "text": "Coldfusion <ul id=\"myList\">\n <li>Eggplant</li>\n <li>Apples</li>\n <li>Carrots</li>\n <li>Blueberries</li> \n</ul>\n <head> <link rel=\"stylesheet\" href=\"alphaListNav.css\">\n<!-- note: you can edit/overide the css to customize how you want it to look -->\n </body> <script src=\"alphaListNav.js\"></script>\n <script>\n new AlphaListNav('myList');\n</script>\n <script>\n new AlphaListNav('myList', {\n initLetter: 'A',\n includeAll: false,\n includeNums: false,\n removeDisabled: true,\n //and many other options available..\n });\n</script>\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666/" ]
16,460
<p>I was writing some <strong>ASP.NET</strong> control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.</p> <p>The <code>RemoveAll</code> method of the generic <code>List</code> class does a good job, but removes <em>all</em> items that match the condition, specified by the predicate.</p> <p>What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?</p>
[ { "answer_id": 16466, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 1, "selected": false, "text": "list.RemoveAll(item => ShouldIRemoveThis(item));\n" }, { "answer_id": 16493, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 0, "selected": false, "text": "List<int> myList = new List<int>;\nfor (int i = 0; i < 20; i++) myList.add(i);\n\nint total = 0;\nint limit = 5;\nmyList.RemoveAll(delegate(int i) { if (i % 2 == 0 && total < limit) { total++; return true; } return false; });\n\nmyList.ForEach(i => Console.Write(i + \" \"));\n" }, { "answer_id": 16496, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 3, "selected": false, "text": "list.RemoveAll(item => ShouldIRemoveThis(item));\n list.RemoveAll(ShouldIRemoveThis);\n" }, { "answer_id": 16500, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 4, "selected": true, "text": "int limit = 30; // Suppose you want to remove 30 items at most\nlist.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801/" ]
16,473
<p>Say we have the following method:</p> <pre><code>private MyObject foo = new MyObject(); // and later in the class public void PotentialMemoryLeaker(){ int firedCount = 0; foo.AnEvent += (o,e) =&gt; { firedCount++;Console.Write(firedCount);}; foo.MethodThatFiresAnEvent(); } </code></pre> <p>If the class with this method is instantiated and the <code>PotentialMemoryLeaker</code> method is called multiple times, do we leak memory?</p> <p>Is there any way to unhook that lambda event handler after we're done calling <code>MethodThatFiresAnEvent</code>? </p>
[ { "answer_id": 16484, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": true, "text": "DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); };\nfoo.AnEvent += evt;\nfoo.MethodThatFiresAnEvent();\nfoo.AnEvent -= evt;\n" }, { "answer_id": 16486, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "someobject.SomeEvent += () => ...;\nsomeobject.SomeEvent += delegate () {\n ...\n};\n\n// unhook\nAction del = () => ...;\nsomeobject.SomeEvent += del;\nsomeobject.SomeEvent -= del;\n" }, { "answer_id": 16498, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "foreach (var handler in AnEvent.GetInvocationList()) AnEvent -= handler;\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
16,487
<p>I am using SourceForge for some Open Source projects and I want to automate the deployment of releases to the SourceForge File Release System. I use Maven for my builds and the standard SFTP deployment mechanism doesn't seem to work unless you do some manual preparation work. I have come across some old postings on other forums suggesting that the only approach is to write a Wagon specifically for SourceForge.</p> <p>Has anybody had any recent experience with this?</p>
[ { "answer_id": 1449595, "author": "Rich Seller", "author_id": 123582, "author_profile": "https://Stackoverflow.com/users/123582", "pm_score": 4, "selected": true, "text": "SourceForge username: foo\nSourceForge user password: secret\nSourceForge project name: bar\nPath: /home/frs/project/P/PR/PROJECT_UNIX_NAME/ \n - Substitute your project UNIX name data for /P/PR/PROJECT_UNIX_NAME \n <server>\n <id>sourceforge</id>\n <username>foo,bar</username>\n <password>secret</password>\n</server>\n <!-- Enabling the use of FTP -->\n<distributionManagement>\n <repository>\n <id>ssh-repository</id>\n <url>\nscpexe://frs.sourceforge.net:/home/frs/project/P/PR/PROJECT_UNIX_NAME</url>\n </repository>\n</distributionManagement>\n <build>\n <extensions>\n <extension>\n <groupId>org.apache.maven.wagon</groupId>\n <artifactId>wagon-ssh-external</artifactId>\n <version>1.0-alpha-5</version>\n </extension>\n </extensions>\n</build>\n ssh -t <username>,<project name>@shell.sf.net create\n <url>scp://shell.sourceforge.net/home/frs/project/P/PR/PROJECT_UNIX_NAME/</url>\n" }, { "answer_id": 2187533, "author": "Gray", "author_id": 179850, "author_profile": "https://Stackoverflow.com/users/179850", "pm_score": 1, "selected": false, "text": "<server>\n <id>sourceforge</id>\n <password>secret</password>\n <filePermissions>775</filePermissions>\n <directoryPermissions>775</directoryPermissions>\n</server>\n <distributionManagement>\n <repository>\n <id>sourceforge</id>\n <name>SourceForge</name>\n <url>sftp://user,[email protected]:/home/frs/project/o/or/ormlite/releases\n </url>\n </repository>\n <snapshotRepository>\n <id>sourceforge</id>\n <name>SourceForge</name>\n <url>sftp://user,[email protected]:/home/frs/project/o/or/ormlite/snapshots\n </url>\n </snapshotRepository>\n</distributionManagement>\n" }, { "answer_id": 2330852, "author": "TimP", "author_id": 60160, "author_profile": "https://Stackoverflow.com/users/60160", "pm_score": 1, "selected": false, "text": "scp://timp,[email protected]:/home/groups/w/we/webmacro/htdocs/maven2/\n sftp://timp,[email protected]:/home/groups/w/we/webmacro/htdocs/maven2\n sftp://timp,[email protected]:/home/frs/project/w/we/webmacro/releases\n ssh -t timp,[email protected] create\n" }, { "answer_id": 2337482, "author": "Huluvu424242", "author_id": 373498, "author_profile": "https://Stackoverflow.com/users/373498", "pm_score": 2, "selected": false, "text": "<distributionManagement>\n <!-- use the following if you're not using a snapshot version. -->\n <repository>\n <id>sourceforge-sf-mvn-plugins</id>\n <name>FRS Area</name>\n <uniqueVersion>false</uniqueVersion>\n <url>sftp://web.sourceforge.net/home/frs/project/s/sf/sf-mvn-plugins/m2-repo</url>\n </repository>\n <site>\n <id>sourceforge-sf-mvn-plugins</id>\n <name>Web Area</name>\n <url>\n sftp://web.sourceforge.net/home/groups/s/sf/sf-mvn-plugins/htdocs/${artifactId}\n </url>\n </site>\n</distributionManagement>\n <server>\n <id>sourceforge-sf-mvn-plugins-svn</id>\n <username>tmichel,sf-mvn-plugins</username>\n <password>secret</password>\n </server>\n\n <server>\n <id>sourceforge-sf-mvn-plugins</id>\n <username>user,project</username>\n <password>secret</password>\n </server>\n <repositories>\n <repository>\n <id>sourceforge-svn</id>\n <name>SF Maven Plugin SVN Repository</name>\n <url>http://sf-mvn-plugins.svn.sourceforge.net/svnroot/sf-mvn-plugins/_m2-repo/trunk</url>\n </repository>\n </repositories>\n\n\n <pluginRepositories>\n <pluginRepository>\n <id>sourceforge-frs</id>\n <name>SF Maven Plugin Repository</name>\n <url>http://sourceforge.net/projects/sf-mvn-plugins/files/m2-repo</url>\n </pluginRepository>\n </pluginRepositories>\n\n <build>\n <extensions>\n <extension>\n <groupId>net.sf.maven.plugins</groupId>\n <artifactId>wagon-http-sourceforge</artifactId>\n <version>0.4</version>\n </extension>\n </extensions>\n :\n </build>\n" }, { "answer_id": 4110138, "author": "simbo1905", "author_id": 329496, "author_profile": "https://Stackoverflow.com/users/329496", "pm_score": 1, "selected": false, "text": "ssh -t user,[email protected] create\n /home/groups/c/ch/chex4j/\n mkdir /home/groups/c/ch/chex4j/htdocs/maven2\n <settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0\n http://maven.apache.org/xsd/settings-1.0.0.xsd/\"> \n <servers>\n <server>\n <id>chex4j.sf.net</id>\n <username>me,myproject</username>\n <password>password</password>\n <filePermissions>775</filePermissions>\n <directoryPermissions>775</directoryPermissions>\n </server>\n </servers>\n</settings>\n <distributionManagement>\n <site>\n <id>chex4j.sf.net</id>\n <url>scp://shell.sourceforge.net/home/groups/c/ch/chex4j/htdocs/\n </url>\n </site>\n <repository>\n <id>chex4j.sf.net</id>\n <name>SourceForge shell repo</name>\n <url>scp://shell.sourceforge.net/home/groups/c/ch/chex4j/htdocs/maven2</url>\n </repository>\n</distributionManagement>\n mvn deploy\n Options +Indexes\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969/" ]
16,491
<p>How do you restore a database backup using SQL Server 2005 over the network? I recall doing this before but there was something odd about the way you had to do it.</p>
[ { "answer_id": 10236311, "author": "RSOLY777", "author_id": 1345056, "author_profile": "https://Stackoverflow.com/users/1345056", "pm_score": 3, "selected": false, "text": "SQL services \"Services.msc\" \"Domain User\"" }, { "answer_id": 14894743, "author": "coussej", "author_id": 1682515, "author_profile": "https://Stackoverflow.com/users/1682515", "pm_score": 3, "selected": false, "text": "EXEC xp_cmdshell 'NET USE Z: SERVERLOCATION PASSWORD /USER:DOMAIN\\USERNAME'\n" }, { "answer_id": 20465401, "author": "TPAKTOPA", "author_id": 3081808, "author_profile": "https://Stackoverflow.com/users/3081808", "pm_score": 6, "selected": false, "text": "-- allow changes to advanced options \nEXEC sp_configure 'show advanced options', 1\nGO\n-- Update currently configured values for advanced options.\nRECONFIGURE\nGO\n-- To enable xp_cmdshell\nEXEC sp_configure 'xp_cmdshell', 1\nGO\n-- Update currently configured values for advanced options.\nRECONFIGURE\nGO\nEXEC xp_cmdshell 'NET USE Z: \\\\Srv\\Path password1 /USER:Domain\\UserName'\n RESTORE DATABASE DataBaseNameHere FROM DISK = 'Z:\\BackNameHere.BAK'\nGO\n" }, { "answer_id": 54476762, "author": "Muhammad Adil Jamil", "author_id": 2384589, "author_profile": "https://Stackoverflow.com/users/2384589", "pm_score": -1, "selected": false, "text": "EXEC sp_configure 'show advanced options', 1\nGO\n RECONFIGURE\nGO\n-- To enable xp_cmdshell\nEXEC sp_configure 'xp_cmdshell', 1\nGO\n RECONFIGURE\nGO\n NET USE Z: \\\\172.100.1.100\\Shared Password /USER:administrator /Persistent:no\n EXEC xp_cmdshell 'NET USE Z: \\\\172.100.1.100\\Shared Password /USER:administrator /Persistent:no'\n RESTORE DATABASE DB FROM DISK = 'Z:\\DB.BAK'\nWITH REPLACE\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1545/" ]
16,501
<p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>
[ { "answer_id": 16504, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": false, "text": "λ : λ → λ (lambda (x y) (* x y)) \n ((lambda (x y) (* x y)) 5 10)\n" }, { "answer_id": 16509, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 11, "selected": true, "text": "def adder(x):\n return lambda y: x + y\nadd5 = adder(5)\nadd5(1)\n6\n sub adder {\n my ($x) = @_;\n return sub {\n my ($y) = @_;\n $x + $y\n }\n}\n\nmy $add5 = adder(5);\nprint &$add5(1) == 6 ? \"ok\\n\" : \"not ok\\n\";\n var adder = function (x) {\n return function (y) {\n return x + y;\n };\n};\nadd5 = adder(5);\nadd5(1) == 6\n const adder = x => y => x + y;\nadd5 = adder(5);\nadd5(1) == 6\n (define adder\n (lambda (x)\n (lambda (y)\n (+ x y))))\n(define add5\n (adder 5))\n(add5 1)\n6\n Func<int, Func<int, int>> adder = \n (int x) => (int y) => x + y; // `int` declarations optional\nFunc<int, int> add5 = adder(5);\nvar add6 = adder(6); // Using implicit typing\nDebug.Assert(add5(1) == 6);\nDebug.Assert(add6(-1) == 5);\n\n// Closure example\nint yEnclosed = 1;\nFunc<int, int> addWithClosure = \n (x) => x + yEnclosed;\nDebug.Assert(addWithClosure(2) == 3);\n func adder(x: Int) -> (Int) -> Int{\n return { y in x + y }\n}\nlet add5 = adder(5)\nadd5(1)\n6\n $a = 1;\n$b = 2;\n\n$lambda = fn () => $a + $b;\n\necho $lambda();\n (\\x y -> x + y) \n // The following is an example of Predicate : \n// a functional interface that takes an argument \n// and returns a boolean primitive type.\n\nPredicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.\nboolean result = pred.test(4); // true\n adder = function(x)\n return function(y)\n return x + y\n end\nend\nadd5 = adder(5)\nadd5(1) == 6 -- true\n val pred = { x: Int -> x % 2 == 0 }\nval result = pred(4) // true\n def adder(x)\n lambda { |y| x + y }\nend\nadd5 = adder(5)\nadd5[1] == 6\n adder def adder(x)\n -> y { x + y }\nend\n adder <- function(x) {\n function(y) x + y\n}\nadd5 <- adder(5)\nadd5(1)\n#> [1] 6\n" }, { "answer_id": 16510, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 7, "selected": false, "text": "public Int32 Add(Int32 a, Int32 b)\n{\n return a + b;\n}\n\npublic Int32 Sub(Int32 a, Int32 b)\n{\n return a - b;\n}\n\npublic delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n Console.WriteLine(\"Calculator: op(\" + a + \", \" + b + \") = \" + op(a, b));\n}\n\npublic void Test()\n{\n Calculator(10, 23, Add);\n Calculator(10, 23, Sub);\n}\n public delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n Console.WriteLine(\"Calculator: op(\" + a + \", \" + b + \") = \" + op(a, b));\n}\n\npublic void Test()\n{\n Calculator(10, 23, delegate(Int32 a, Int32 b)\n {\n return a + b;\n });\n Calculator(10, 23, delegate(Int32 a, Int32 b)\n {\n return a - b;\n });\n}\n public delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n Console.WriteLine(\"Calculator: op(\" + a + \", \" + b + \") = \" + op(a, b));\n}\n\npublic void Test()\n{\n Calculator(10, 23, (a, b) => a + b);\n Calculator(10, 23, (a, b) => a - b);\n}\n" }, { "answer_id": 16511, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "numberCollection.GetMatchingItems<int>(number => number > 5);\n number => number > 5\n" }, { "answer_id": 16514, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "LinqToSqlContext.Where( \n row => row.FieldName > 15 );\n select ... from [tablename] \nwhere [FieldName] > 15 --this line was 'read' from the lambda function\n LinqToSqlContext.Where( \n row => SomeComplexCheck( row.FieldName ) );\n SomeComplexCheck LinqToSqlContext.Where( \n delegate ( DataRow row ) { \n return row.FieldName > 15; \n } );\n" }, { "answer_id": 16578, "author": "CodingWithoutComments", "author_id": 25, "author_profile": "https://Stackoverflow.com/users/25", "pm_score": 3, "selected": false, "text": "hello = lambda do\n puts('Hello')\n puts('I am inside a proc')\nend\n\nhello.call\n Hello\nI am inside a proc\n" }, { "answer_id": 16680, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "string[] GetCustomerNames(IEnumerable<Customer> customers)\n { return customers.Select(c=>c.Name);\n }\n getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});\n" }, { "answer_id": 23046, "author": "SarekOfVulcan", "author_id": 2531, "author_profile": "https://Stackoverflow.com/users/2531", "pm_score": 2, "selected": false, "text": "? Calculator(10, 23, \"a + b\")\n? Calculator(10, 23, \"a - b\");\n\nFUNCTION Calculator(a, b, op)\nRETURN Evaluate(op)\n" }, { "answer_id": 34969, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 6, "selected": false, "text": "args.foreach(arg => println(arg))\n foreach void printThat(Object that) {\n println(that)\n}\n...\nargs.foreach(printThat)\n int tempVar = 2 * a + b\n...\nprintln(tempVar)\n println(2 * a + b)\n" }, { "answer_id": 1254843, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "int string float bool var x = new Object;\nx.thingy = new Array();\nx.thingy[0] = function(){ return function(){ return function(){ alert('index 0 pressed'); }; }; }\nx.thingy[1] = function(){ return function(){ return function(){ alert('index 1 pressed'); }; }; }\nx.thingy[2] = function(){ return function(){ return function(){ alert('index 2 pressed'); }; }; }\n\nfor(var i=0 ;i<3; i++)\n x.thingy[i]()()();\n" }, { "answer_id": 10807110, "author": "learnvst", "author_id": 276193, "author_profile": "https://Stackoverflow.com/users/276193", "pm_score": 3, "selected": false, "text": "template<typename F>\n\nvoid Eval( const F& f ) {\n    f();\n}\nvoid foo() {\n    Eval( []{ printf(\"Hello, Lambdas\\n\"); } );\n}\n void bar() {\n    auto f = []{ printf(\"Hello, Lambdas\\n\"); };\n    f();\n}\n" }, { "answer_id": 18222531, "author": "isomorphismes", "author_id": 563329, "author_profile": "https://Stackoverflow.com/users/563329", "pm_score": 6, "selected": false, "text": "x+y=5 x−y=1 y = x−1 λ y = x−1 x−1 y λ y y λ y int square(int x)\n{\n return x * x;\n}\n (define square\n (lambda (x) \n (* x x)))\n" }, { "answer_id": 47355087, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 3, "selected": false, "text": "lambdas In [1]: x = 1\n ...: y = 'value'\nIn [2]: x\nOut[2]: 1\nIn [3]: y\nOut[3]: 'value'\n In [4]: m = n**2 + 2*n + 1\nNameError: name 'n' is not defined\n In [8]: n = 3.14\nIn [9]: m = n**2 + 2*n + 1\nIn [10]: m\nOut[10]: 17.1396\n lambda In [13]: j = lambda i: i**2 + 2*i + 1\nIn [14]: j\nOut[14]: <function __main__.<lambda>>\n lambda = In [15]: x = print('This is a x')\nThis is a x\nIn [16]: x\nIn [17]: x = input('Enter a x: ')\nEnter a x: x\n In [18]: m = n**2 + 2*n + 1 if n > 0\nSyntaxError: invalid syntax\n#or\nIn [19]: m = n**2 + 2*n + 1, if n > 0\nSyntaxError: invalid syntax\n def In [23]: def m(n):\n ...: if n > 0:\n ...: return n**2 + 2*n + 1\n ...:\nIn [24]: m(2)\nOut[24]: 9\n : lambda In [28]: m = m(3)\nIn [29]: m\nOut[29]: 16\n m In [27]: m = def m(n):\n ...: if n > 0:\n ...: return n**2 + 2*n + 1\n SyntaxError: invalid syntax\n m = lambda n:n**2 + 2*n + 1\n lambda lambda" }, { "answer_id": 50459728, "author": "madeinQuant", "author_id": 5329711, "author_profile": "https://Stackoverflow.com/users/5329711", "pm_score": 1, "selected": false, "text": "let f = |x: f32| -> f32 { x * x - 2.0 };\nlet df = |x: f32| -> f32 { 2.0 * x };\n println!(\"f={:.6} df={:.6}\", f(10.0), df(10.0))\n\nf=98.000000 df=20.000000\n" }, { "answer_id": 52646171, "author": "akinov", "author_id": 6565365, "author_profile": "https://Stackoverflow.com/users/6565365", "pm_score": 1, "selected": false, "text": "// ES5 \nvar food = function withBike(kebap, coke) {\nreturn (kebap + coke); \n};\n // ES6 \nconst food = (kebap, coke) => { return kebap + coke };\n" }, { "answer_id": 54168332, "author": "Andy Jazz", "author_id": 6599590, "author_profile": "https://Stackoverflow.com/users/6599590", "pm_score": 3, "selected": false, "text": "Lambda Function Small Anonymous Function Lambda Closure Block let coffee: [String] = [\"Cappuccino\", \"Espresso\", \"Latte\", \"Ristretto\"]\n func backward(_ n1: String, _ n2: String) -> Bool {\n return n1 > n2\n}\nvar reverseOrder = coffee.sorted(by: backward)\n\n\n// RESULT: [\"Ristretto\", \"Latte\", \"Espresso\", \"Cappuccino\"]\n reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in \n return n1 > n2\n})\n reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in \n return n1 > n2 \n})\n reverseOrder = coffee.sorted(by: { n1, n2 in return n1 > n2 } )\n reverseOrder = coffee.sorted(by: { n1, n2 in n1 > n2 } )\n reverseOrder = coffee.sorted(by: { $0 > $1 } )\n\n// $0 and $1 are closure’s first and second String arguments.\n reverseOrder = coffee.sorted(by: >)\n\n// RESULT: [\"Ristretto\", \"Latte\", \"Espresso\", \"Cappuccino\"]\n" }, { "answer_id": 62742314, "author": "Thingamabobs", "author_id": 13629335, "author_profile": "https://Stackoverflow.com/users/13629335", "pm_score": 3, "selected": false, "text": "def name_of_func():\n #command/instruction\n print('hello')\n\nprint(type(name_of_func)) #the name of the function is a reference\n #the reference contains a function Object with command/instruction\n <class 'function'>\n def print_my_argument(x):\n print(x)\n\n\nprint_my_argument('Hello')\n Hello\n def name_of_func():\n print('Hello')\n\n\n\nlambda: print('Hello')\n def delete_last_char(arg1=None):\n print(arg1[:-1])\n\nstring = 'Hello World'\ndelete_last_char(string)\n\nf = lambda arg1=None: print(arg1[:-1])\nf(string)\n Hello Worl\nHello Worl\n string = 'Hello World'\nf = lambda arg1=string: print(arg1[:-1])\nf()\nprint(type(f))\n Hello Worl\n<class 'function'>\n def delete_last_char(arg1):\n print(arg1[:-1])\n\nstring = 'Hello World'\nx = delete_last_char(string)\n\nf = lambda arg1=string: print(arg1[:-1])\nx2 = f()\n\nprint(x)\nprint(x2)\n Hello Worl\nHello Worl\nNone\nNone\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344/" ]
16,529
<p>I've been developing a "Form Builder" in Javascript, and coming up to the part where I'll be sending the spec for the form back to the server to be stored. The builder maintains an internal data structure that represents the fields, label, options (for select/checkbox/radio), mandatory status, and the general sorting order of the fields.</p> <p>When I want to send this structure back to the server, which format should I communicate it with?</p> <p>Also, when restoring a server-saved form back into my Javascript builder, should I load in the data in the same format it sent it with, or should I rebuild the fields using the builder's <code>createField()</code> functions?</p>
[ { "answer_id": 16535, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 0, "selected": false, "text": "text serialization" }, { "answer_id": 16547, "author": "t3rse", "author_id": 64, "author_profile": "https://Stackoverflow.com/users/64", "pm_score": 2, "selected": false, "text": "JSON" }, { "answer_id": 16551, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "JSON XML XML XML JavaScript form submit JavaScript JSON/XML" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1951/" ]
16,550
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/476163">NAnt or MSBuild, which one to choose and when?</a> </p> </blockquote> <p>What is the best build tool for <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a>?</p> <p>I currently use <a href="http://en.wikipedia.org/wiki/NAnt" rel="nofollow noreferrer">NAnt</a> but only because I have experience with <a href="http://en.wikipedia.org/wiki/Apache_Ant" rel="nofollow noreferrer">Ant</a>. Is <a href="http://en.wikipedia.org/wiki/MSBuild" rel="nofollow noreferrer">MSBuild</a> preferred?</p>
[ { "answer_id": 17316, "author": "Lee", "author_id": 1954, "author_profile": "https://Stackoverflow.com/users/1954", "pm_score": 3, "selected": false, "text": "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" DefaultTargets=\"Build\">\n <UsingTask AssemblyFile=\"$(MSBuildProjectDirectory)\\bin\\xUnit\\xunitext.runner.msbuild.dll\" TaskName=\"XunitExt.Runner.MSBuild.xunit\"/>\n <PropertyGroup>\n <Configuration Condition=\"'$(Configuration)'==''\">Debug</Configuration>\n <DeployDir>$(MSBuildProjectDirectory)\\Build\\$(Configuration)</DeployDir>\n <ProjectMask>$(MSBuildProjectDirectory)\\**\\*.csproj</ProjectMask>\n <ProjectExcludeMask></ProjectExcludeMask>\n <TestAssembliesIncludeMask>$(DeployDir)\\*.Test.dll</TestAssembliesIncludeMask>\n </PropertyGroup>\n\n <ItemGroup>\n <ProjectFiles Include=\"$(ProjectMask)\" Exclude=\"$(ProjectExcludeMask)\"/>\n </ItemGroup>\n\n <Target Name=\"Build\" DependsOnTargets=\"__Compile;__Deploy;__Test\"/>\n\n <Target Name=\"Clean\">\n <MSBuild Projects=\"@(ProjectFiles)\" Targets=\"Clean\"/>\n <RemoveDir Directories=\"$(DeployDir)\"/>\n </Target>\n\n <Target Name=\"Rebuild\" DependsOnTargets=\"Clean;Build\"/>\n\n <!--\n ===== Targets that are meant for use only by MSBuild =====\n -->\n <Target Name=\"__Compile\">\n <MSBuild Projects=\"@(ProjectFiles)\" Targets=\"Build\">\n <Output TaskParameter=\"TargetOutputs\" ItemName=\"AssembliesBuilt\"/>\n </MSBuild>\n <CreateItem Include=\"@(AssembliesBuilt -> '%(RootDir)%(Directory)*')\">\n <Output TaskParameter=\"Include\" ItemName=\"DeployFiles\"/>\n </CreateItem>\n </Target>\n\n <Target Name=\"__Deploy\">\n <MakeDir Directories=\"$(DeployDir)\"/>\n <Copy SourceFiles=\"@(DeployFiles)\" DestinationFolder=\"$(DeployDir)\"/>\n <CreateItem Include=\"$(TestAssembliesIncludeMask)\">\n <Output TaskParameter=\"Include\" ItemName=\"TestAssemblies\"/>\n </CreateItem>\n </Target>\n\n <Target Name=\"__Test\">\n <xunit Assembly=\"@(TestAssemblies)\"/>\n </Target>\n</Project>\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1464/" ]
16,557
<p>I have always thought that the .equals() method in java should be overridden to be made specific to the class you have created. In other words to look for equivalence of two different instances rather than two references to the same instance. However I have encountered other programmers who seem to think that the default object behavior should be left alone and a new method created for testing equivalence of two objects of the same class. </p> <p>What are the argument for and against overriding the equals method?</p>
[ { "answer_id": 16574, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 0, "selected": false, "text": "equals() SortedSet hashCode()" }, { "answer_id": 16922, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "compare_to" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1104/" ]
16,563
<p>So I'm working on a project that will allow users to enter <strong>poker hand histories</strong> from sites like PokerStars and then display the hand to them.</p> <p>It seems that regex would be a great tool for this, however I rank my regex knowledge at "slim to none".</p> <p>So I'm using PHP and looping through this block of text line by line and on lines like this:</p> <pre><code>Seat 1: fabulous29 (835 in chips) Seat 2: Nioreh_21 (6465 in chips) Seat 3: Big Loads (3465 in chips) Seat 4: Sauchie (2060 in chips) </code></pre> <p>I want to extract seat <code>number, name, &amp; chip count</code> so the format is</p> <pre><code>Seat [number]: [letters&amp;numbers&amp;characters] ([number] in chips) </code></pre> <p>I have NO IDEA where to start or what commands I should even be using to optimize this.</p> <p>Any advice is greatly appreciated - even if it is just a link to a tutorial on PHP regex or the name of the command(s) I should be using.</p>
[ { "answer_id": 16583, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 2, "selected": false, "text": "/Seat (\\d+): ([^ ]+) \\((\\d+)/\n _ _" }, { "answer_id": 16592, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": -1, "selected": false, "text": "Seat [number]: [letters&numbers&characters] ([number] in chips)\n Seat (\\d+): ([a-zA-Z0-9]+) \\((\\d+) in chips\\)\n" }, { "answer_id": 16593, "author": "Roy Rico", "author_id": 1580, "author_profile": "https://Stackoverflow.com/users/1580", "pm_score": -1, "selected": false, "text": "$seat = 0;\n$name = 1;\n$chips = 2;\n\nforeach( $string in $file ) {\n if (preg_match(\"Seat ([1-0]): ([A-Za-z_0-9]*) \\(([1-0]*) in chips\\)\", $string, $matches)) {\n echo \"Seat: \" . $matches[$seat] . \"<br>\";\n echo \"Name: \" . $matches[$name] . \"<br>\";\n echo \"Chips: \" . $matches[$chips] . \"<br>\";\n }\n}\n" }, { "answer_id": 16598, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 0, "selected": false, "text": "preg_match(\"/(Seat \\d+: [A-Za-z0-9 _-]+) \\((\\d+) in chips\\)/\",$line)\n" }, { "answer_id": 16603, "author": "Joel Meador", "author_id": 1976, "author_profile": "https://Stackoverflow.com/users/1976", "pm_score": 1, "selected": false, "text": "<?php\n$str = 'Seat 1: fabulous29 (835 in chips)';\npreg_match('/Seat (?<seatNo>\\d+): (?<name>\\w+) \\((?<chipCnt>\\d+) in chips\\)/', $str, $matches);\nprint_r($matches);\n?>\n" }, { "answer_id": 16643, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "/Seat (\\d+): ([^\\(]+) \\((\\d+)in chips\\)/\n \\t \\\\t ([^\\(]+)\n ([A-Za-z0-9-_]+)\n ([A-Za-z0-9-_\\s]+)\n" }, { "answer_id": 17522, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 0, "selected": false, "text": "preg_match_all() preg_match_all('/Seat (\\d+): \\w+ \\((\\d+) in chips\\)/', $preg_match_all, $matches);\n array\n 0 => \n array\n 0 => string 'Seat 1: fabulous29 (835 in chips)' (length=33)\n 1 => string 'Seat 2: Nioreh_21 (6465 in chips)' (length=33)\n 2 => string 'Seat 4: Sauchie (2060 in chips)' (length=31)\n 1 => \n array\n 0 => string '1' (length=1)\n 1 => string '2' (length=1)\n 2 => string '4' (length=1)\n 2 => \n array\n 0 => string '835' (length=3)\n 1 => string '6465' (length=4)\n 2 => string '2060' (length=4)\n" }, { "answer_id": 19360596, "author": "A. Zalonis", "author_id": 2455661, "author_profile": "https://Stackoverflow.com/users/2455661", "pm_score": 0, "selected": false, "text": "$string1 = \"Seat 1: fabulous29 (835 in chips)\";\n$string2 = \"Seat 2: Nioreh_21 (6465 in chips)\";\n$string3 = \"Seat 3: Big Loads (3465 in chips)\";\n$string4 = \"Seat 4: Sauchie (2060 in chips)\";\n $lines = array($string1,$string2,$string3,$string4);\nforeach($lines as $line )\n{\n $seatArray = explode(\":\", $line);\n $seat = explode(\" \",$seatArray[0]);\n $seatNumber = $seat[1];\n\n $usernameArray = explode(\"(\",$seatArray[1]);\n $username = trim($usernameArray[0]);\n\n $chipArray = explode(\" \",$usernameArray[1]);\n $chipNumber = $chipArray[0]; \n\n echo \"<br>\".\"Seat [\".$seatNumber.\"]: [\". $username.\"] ([\".$chipNumber.\"] in chips)\";\n}\n" }, { "answer_id": 26624125, "author": "Suganthan Madhavan Pillai", "author_id": 2534236, "author_profile": "https://Stackoverflow.com/users/2534236", "pm_score": 1, "selected": false, "text": "Seat\\s(\\d):\\s([\\w\\s]+)\\s\\((\\d+).*\\)\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
16,568
<p>I'm interested in learning some (ideally) database agnostic ways of selecting the <em>n</em>th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases: </p> <ul> <li>SQL Server</li> <li>MySQL</li> <li>PostgreSQL</li> <li>SQLite</li> <li>Oracle</li> </ul> <p>I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches:</p> <pre><code>WITH Ordered AS ( SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate FROM Orders) SELECT * FROM Ordered WHERE RowNumber = 1000000 </code></pre> <p>Credit for the above SQL: <a href="https://web.archive.org/web/20101103031717/http://weblogs.asp.net/Firoz/archive/2005/06/12/411949.aspx" rel="noreferrer">Firoz Ansari's Weblog</a></p> <p><strong>Update:</strong> See <a href="https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765">Troels Arvin's answer</a> regarding the SQL standard. <em>Troels, have you got any links we can cite?</em></p>
[ { "answer_id": 16570, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 2, "selected": false, "text": "LIMIT n,1\n" }, { "answer_id": 16584, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 2, "selected": false, "text": "-- p_LowerBound = first row # in the returned set; if second page of 10 rows,\n-- this would be 11 (-1 for unbounded/not set)\n-- p_UpperBound = last row # in the returned set; if second page of 10 rows,\n-- this would be 20 (-1 for unbounded/not set)\n\nOPEN o_Cursor FOR\nSELECT * FROM (\nSELECT\n Column1,\n Column2\n rownum AS rn\nFROM\n(\n SELECT\n tbl.Column1,\n tbl.column2\n FROM MyTable tbl\n WHERE\n tbl.Column1 = p_PKParam OR\n tbl.Column1 = -1\n ORDER BY\n DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 1, Column1, 'X'),'X'),\n DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 1, Column1, 'X'),'X') DESC,\n DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate),\n DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate) DESC\n))\nWHERE\n (rn >= p_lowerBound OR p_lowerBound = -1) AND\n (rn <= p_upperBound OR p_upperBound = -1);\n" }, { "answer_id": 16587, "author": "Ellen Teapot", "author_id": 1914, "author_profile": "https://Stackoverflow.com/users/1914", "pm_score": 5, "selected": false, "text": "SELECT * \nFROM the_table \nORDER BY added DESC \nLIMIT 1,15\n" }, { "answer_id": 16602, "author": "Tim", "author_id": 1970, "author_profile": "https://Stackoverflow.com/users/1970", "pm_score": 4, "selected": false, "text": "select top 1 field\nfrom table\nwhere field in (select top 5 field from table order by field asc)\norder by field desc\n" }, { "answer_id": 16606, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 7, "selected": false, "text": "LIMIT OFFSET SELECT\n *\nFROM\n mytable\nORDER BY\n somefield\nLIMIT 1 OFFSET 20;\n OFFSET 20 ORDER BY" }, { "answer_id": 16608, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 3, "selected": false, "text": "DECLARE @InnerPageSize int\nDECLARE @OuterPageSize int\nDECLARE @Count int\n\nSELECT @Count = COUNT(<column>) FROM <TABLE>\nSET @InnerPageSize = @PageNum * @PageSize\nSET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize)\n\nIF (@OuterPageSize < 0)\n SET @OuterPageSize = 0\nELSE IF (@OuterPageSize > @PageSize)\n SET @OuterPageSize = @PageSize\n\nDECLARE @sql NVARCHAR(8000)\n\nSET @sql = 'SELECT * FROM\n(\n SELECT TOP ' + CAST(@OuterPageSize AS nvarchar(5)) + ' * FROM\n (\n SELECT TOP ' + CAST(@InnerPageSize AS nvarchar(5)) + ' * FROM <TABLE> ORDER BY <column> ASC\n ) AS t1 ORDER BY <column> DESC\n) AS t2 ORDER BY <column> ASC'\n\nPRINT @sql\nEXECUTE sp_executesql @sql\n" }, { "answer_id": 16735, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "select * from (select foo from bar order by foo) where ROWNUM = x\n" }, { "answer_id": 16753, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "SELECT TOP 1 START AT n * from table ORDER BY whatever\n" }, { "answer_id": 16777, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 10, "selected": true, "text": "SELECT...\nLIMIT y OFFSET x \n SELECT * FROM (\n SELECT\n ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,\n columns\n FROM tablename\n) AS foo\nWHERE rownumber <= n\n" }, { "answer_id": 16780, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 4, "selected": false, "text": "select *\nfrom thetable\nlimit n-1, 1\n" }, { "answer_id": 42765, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 4, "selected": false, "text": "\n OFFSET skip ROWS\n FETCH FIRST n ROWS ONLY" }, { "answer_id": 618857, "author": "jrEving", "author_id": 72739, "author_profile": "https://Stackoverflow.com/users/72739", "pm_score": 0, "selected": false, "text": "WITH sentence AS\n(SELECT \n stuff,\n row = ROW_NUMBER() OVER (ORDER BY Id)\nFROM \n SentenceType\n )\nSELECT\n sen.stuff\nFROM sentence sen\nWHERE sen.row = (ABS(CHECKSUM(NEWID())) % 100) + 1\n" }, { "answer_id": 965955, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SELECT * FROM emp a\nWHERE n = ( \n SELECT COUNT( _rowid)\n FROM emp b\n WHERE a. _rowid >= b. _rowid\n);\n" }, { "answer_id": 1028336, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "SET ROWCOUNT @row --@row = the row number you wish to work on.\n set rowcount 20 --sets row to 20th row\n\nselect meat, cheese from dbo.sandwich --select columns from table at 20th row\n\nset rowcount 0 --sets rowcount back to all rows\n" }, { "answer_id": 1104447, "author": "monibius", "author_id": 135569, "author_profile": "https://Stackoverflow.com/users/135569", "pm_score": 5, "selected": false, "text": "SELECT\n *\nFROM\n (\n SELECT\n ROW_NUMBER () OVER (ORDER BY MyColumnToOrderBy) AS RowNum,\n *\n FROM\n Table_1\n ) sub\nWHERE\n RowNum = 23\n" }, { "answer_id": 4228433, "author": "Sangeeth Krishna", "author_id": 513879, "author_profile": "https://Stackoverflow.com/users/513879", "pm_score": 1, "selected": false, "text": "select * from\n (select row_number() over (order by Rand() desc) as Rno,* from TableName) T where T.Rno = RecordNumber\n\nWhere RecordNumber --> Record Number to Select\n TableName --> To be Replaced with your Table Name\n select * from\n (select row_number() over (order by Rand() desc) as Rno,* from Employee) T where T.Rno = 5\n" }, { "answer_id": 8677680, "author": "E-A", "author_id": 584508, "author_profile": "https://Stackoverflow.com/users/584508", "pm_score": 2, "selected": false, "text": "SELECT * FROM (\n SELECT\n ROW_NUMBER() OVER (ORDER BY ColumnName1 ASC) AS rownumber, ColumnName1, ColumnName2\n FROM TableName\n) AS foo\nWHERE rownumber % 10 = 0\n" }, { "answer_id": 10633023, "author": "Amit Shah", "author_id": 1240318, "author_profile": "https://Stackoverflow.com/users/1240318", "pm_score": 3, "selected": false, "text": "SELECT * FROM table ORDER BY `id` DESC LIMIT N, 1\n SELECT DISTINCT (`amount`) \nFROM cart \nORDER BY CAST( `amount` AS SIGNED ) DESC \nLIMIT 4 , 1\n" }, { "answer_id": 21870925, "author": "Aditya", "author_id": 2819400, "author_profile": "https://Stackoverflow.com/users/2819400", "pm_score": 3, "selected": false, "text": "SELECT * FROM (\nSELECT \nID, NAME, ROW_NUMBER() OVER(ORDER BY ID) AS ROW\nFROM TABLE \n) AS TMP \nWHERE ROW = n\n SELECT * FROM (\nSELECT \nID, NAME, ROW_NUMBER() OVER(ORDER BY ID DESC) AS ROW\nFROM TABLE \n) AS TMP \nWHERE ROW = n\n" }, { "answer_id": 26402677, "author": "Rameshwar Pawale", "author_id": 1794528, "author_profile": "https://Stackoverflow.com/users/1794528", "pm_score": 4, "selected": false, "text": "Select top 10 * From emp \nEXCEPT\nSelect top 9 * From emp\n" }, { "answer_id": 28210751, "author": "Arjun Chiddarwar", "author_id": 2149459, "author_profile": "https://Stackoverflow.com/users/2149459", "pm_score": 1, "selected": false, "text": "SELECT\n top 1 *\nFROM\n table_name\nWHERE\n column_name IN (\n SELECT\n top N column_name\n FROM\n TABLE\n ORDER BY\n column_name\n )\nORDER BY\n column_name DESC\n SELECT\n top 1 *\nFROM\n Employee\nWHERE\n emp_id IN (\n SELECT\n top 7 emp_id\n FROM\n Employee\n ORDER BY\n emp_id\n )\nORDER BY\n emp_id DESC\n" }, { "answer_id": 32888597, "author": "THE JOATMON", "author_id": 736893, "author_profile": "https://Stackoverflow.com/users/736893", "pm_score": 2, "selected": false, "text": "SELECT TOP 1 * FROM (\n SELECT TOP n * FROM <table>\n ORDER BY ID Desc\n)\nORDER BY ID ASC\n" }, { "answer_id": 40680413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT * FROM ( \n SELECT RRN(FOO) AS RRN, FOO.*\n FROM FOO \n ORDER BY RRN(FOO)) BAR \nWHERE BAR.RRN = recordnumber\n" }, { "answer_id": 44336943, "author": "Dwipam Katariya", "author_id": 7530100, "author_profile": "https://Stackoverflow.com/users/7530100", "pm_score": 0, "selected": false, "text": "select * from \n(select * from ordered order by order_id limit 100) x order by \nx.order_id desc limit 1;\n" }, { "answer_id": 45137397, "author": "John Deighan", "author_id": 1738579, "author_profile": "https://Stackoverflow.com/users/1738579", "pm_score": 0, "selected": false, "text": "select * \nfrom Table \nlimit abs(random()) % (select count(*) from Words), 1;\n" }, { "answer_id": 48622884, "author": "Kaushik Nayak", "author_id": 7998591, "author_profile": "https://Stackoverflow.com/users/7998591", "pm_score": 3, "selected": false, "text": "OFFSET..FETCH..ROWS ORDER BY SELECT * \nFROM sometable\nORDER BY column_name\nOFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY;\n" }, { "answer_id": 50954231, "author": "nPcomp", "author_id": 5074973, "author_profile": "https://Stackoverflow.com/users/5074973", "pm_score": 2, "selected": false, "text": "declare @rowNumber int = 1;\n select TOP(@rowNumber) * from [dbo].[someTable];\nEXCEPT\n select TOP(@rowNumber - 1) * from [dbo].[someTable];\n WHILE @constVar > 0\nBEGIN\n declare @rowNumber int = @consVar;\n select TOP(@rowNumber) * from [dbo].[someTable];\n EXCEPT\n select TOP(@rowNumber - 1) * from [dbo].[someTable]; \n\n SET @constVar = @constVar - 1; \nEND;\n" }, { "answer_id": 59001597, "author": "Mashood Murtaza", "author_id": 11537677, "author_profile": "https://Stackoverflow.com/users/11537677", "pm_score": 0, "selected": false, "text": "WITH myTableWithRows AS (\n SELECT (ROW_NUMBER() OVER (ORDER BY myTable.SomeField)) as row,*\n FROM myTable)\nSELECT * FROM myTableWithRows WHERE row = 3\n" }, { "answer_id": 59179791, "author": "FoxArc", "author_id": 3866382, "author_profile": "https://Stackoverflow.com/users/3866382", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT dept_id\n , NTH_VALUE(salary,2) OVER (PARTITION BY dept_id ORDER BY salary DESC\n RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) \n AS \"SECOND HIGHEST\"\n , NTH_VALUE(salary,3) OVER (PARTITION BY dept_id ORDER BY salary DESC\n RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)\n AS \"THIRD HIGHEST\"\n FROM employees\n WHERE dept_id in (10,20)\n ORDER \n BY dept_id;\n" }, { "answer_id": 64932564, "author": "3rdRockSoftware", "author_id": 12927325, "author_profile": "https://Stackoverflow.com/users/12927325", "pm_score": 1, "selected": false, "text": "WHERE x IN (...)\n SELECT TOP 1\n--select the value needed from t1\n[col2]\nFROM\n(\n SELECT TOP 2 --the Nth row, alter this to taste\n UE2.[col1],\n UE2.[col2],\n UE2.[date],\n UE2.[time],\n UE2.[UID]\n FROM\n [table1] AS UE2\n WHERE\n UE2.[col1] = ID --this is a subquery \n AND\n UE2.[col2] IS NOT NULL\n ORDER BY\n UE2.[date] DESC, UE2.[time] DESC --sorting by date and time newest first\n) AS t1\nORDER BY t1.[date] ASC, t1.[time] ASC --this reverses the order of the sort in t1\n" }, { "answer_id": 64995930, "author": "vinaych", "author_id": 3802476, "author_profile": "https://Stackoverflow.com/users/3802476", "pm_score": 0, "selected": false, "text": "WITH r AS (\n SELECT TOP 1000 * FROM emp\n)\nSELECT * FROM r\nEXCEPT\nSELECT TOP 999 FROM r\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
16,610
<p>Every now and then in a high volume .NET application, you might see this exception when you try to execute a query:</p> <blockquote> <p>System.Data.SqlClient.SqlException: A transport-level error has occurred when sending the request to the server.</p> </blockquote> <p>According to my research, this is something that "just happens" and not much can be done to prevent it. It does not happen as a result of a bad query, and generally cannot be duplicated. It just crops up maybe once every few days in a busy OLTP system when the TCP connection to the database goes bad for some reason.</p> <p>I am forced to detect this error by parsing the exception message, and then retrying the entire operation from scratch, to include using a new connection. None of that is pretty.</p> <p>Anybody have any alternate solutions?</p>
[ { "answer_id": 156388, "author": "Daniel Fortunov", "author_id": 5975, "author_profile": "https://Stackoverflow.com/users/5975", "pm_score": 2, "selected": false, "text": "Number SqlException SqlError Errors" }, { "answer_id": 22389658, "author": "Phillip Deneka", "author_id": 1721229, "author_profile": "https://Stackoverflow.com/users/1721229", "pm_score": 0, "selected": false, "text": " BULK INSERT #t1 FROM 'C:\\123\\Import123.csv' WITH \n ( FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0d0x0a' )\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
16,615
<p>I'm new to windows programming and I'm trying to get notified of all changes to the file system (similar to the information that FileMon from SysInternals displays, but via an API). Is a FindFirstChangeNotification for each (non-network, non-substed) drive my best bet or are there other more suitable C/C++ APIs?</p>
[ { "answer_id": 22910, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 6, "selected": true, "text": "FindFirstChangeNotification ReadDirectoryChangesW." } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849/" ]
16,616
<p>In .NET, is it more appropriate to throw an argument null exception for an Integer if the value is Integer.MinValue or Integer = 0 (assuming that 0 is not a valid value)?</p>
[ { "answer_id": 16627, "author": "bradtgmurray", "author_id": 1546, "author_profile": "https://Stackoverflow.com/users/1546", "pm_score": 0, "selected": false, "text": "ArgumentNullException ArgumentException ArgumentOutOfRangeException" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1989/" ]
16,634
<p>We used the "undocumented" xp_fileexist stored procedure for years in SQL Server 2000 and had no trouble with it. In 2005, it seems that they modified the behavior slightly to always return a 0 if the executing user account is not a sysadmin. It also seems to return a zero if the SQL Server service is running under the LocalSystem account and you are trying to check a file on the network. </p> <p>I'd like to get away from xp_fileexist. Does anyone have a better way to check for the existence of a file at a network location from inside of a stored procedure?</p>
[ { "answer_id": 18000, "author": "Paul G", "author_id": 162, "author_profile": "https://Stackoverflow.com/users/162", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Security.Principal;\n\npublic partial class StoredProcedures\n{\n [Microsoft.SqlServer.Server.SqlProcedure]\n public static void FileExists(SqlString fileName, out SqlInt32 returnValue)\n {\n WindowsImpersonationContext originalContext = null;\n\n try\n {\n WindowsIdentity callerIdentity = SqlContext.WindowsIdentity;\n originalContext = callerIdentity.Impersonate();\n\n if (System.IO.File.Exists(Convert.ToString(fileName)))\n {\n returnValue = 1;\n }\n else\n {\n returnValue = 0;\n }\n }\n catch (Exception)\n {\n returnValue = -1;\n }\n finally\n {\n if (originalContext != null)\n {\n originalContext.Undo();\n }\n }\n }\n}\n USE master\nGO\nCREATE ASYMMETRIC KEY FileUtilitiesKey FROM EXECUTABLE FILE = 'J:\\FileUtilities.dll' \nCREATE LOGIN CLRLogin FROM ASYMMETRIC KEY FileUtilitiesKey \nGRANT EXTERNAL ACCESS ASSEMBLY TO CLRLogin \nALTER DATABASE database SET TRUSTWORTHY ON;\n DECLARE @i INT\n--EXEC FileExists '\\\\\\\\server\\\\share\\\\folder\\\\file.dat', @i OUT\nEXEC FileExists 'j:\\\\file.dat', @i OUT\nSELECT @i\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162/" ]
16,638
<p>I am having some trouble with the <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps API</a>. I have an array which holds a ojbect I created to store points.</p> <p>My array and class:</p> <pre><code>var tPoints = []; function tPoint(name) { var id = name; var points = []; var pointsCount = 0; ... this.getHeadPoint = function() { return points[pointsCount-1]; } } </code></pre> <p>tPoint holds an array of <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLng" rel="nofollow noreferrer">GLatLng</a> points. I want to write a function to return a <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> object which is extended from the current map bounds to show all the HeadPoints.</p> <p>Heres what I have so far..</p> <pre><code>function getBounds() { var mBound = map.getBounds(); for (var i = 0; i &lt; tPoints.length; i++) { alert(mBound.getSouthWest().lat() + "," + mBound.getSouthWest().lng()); alert(mBound.getNorthEast().lat() + "," + mBound.getNorthEast().lng()); currPoint = trackMarkers[i].getHeadPoint(); if (!mBound.containsLatLng(currPoint)) { mBound.extend(currPoint); } } return mBound; } </code></pre> <p>Which returns these values for the alert. (Generally over the US)<br /></p> <blockquote> <p>"19.64258,NaN"<br /> "52.69636,NaN"<br /> "i=0"<br /> "19.64258,NaN"<br /> "52.69636,-117.20701"<br /> "i=1"<br /></p> </blockquote> <p>I don't know why I am getting NaN back. When I use the bounds to get a zoom level I think the NaN value is causing the map.getBoundsZoomLevel(bounds) to return 0 which is incorrect. Am I using <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> incorrectly?</p>
[ { "answer_id": 18000, "author": "Paul G", "author_id": 162, "author_profile": "https://Stackoverflow.com/users/162", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Security.Principal;\n\npublic partial class StoredProcedures\n{\n [Microsoft.SqlServer.Server.SqlProcedure]\n public static void FileExists(SqlString fileName, out SqlInt32 returnValue)\n {\n WindowsImpersonationContext originalContext = null;\n\n try\n {\n WindowsIdentity callerIdentity = SqlContext.WindowsIdentity;\n originalContext = callerIdentity.Impersonate();\n\n if (System.IO.File.Exists(Convert.ToString(fileName)))\n {\n returnValue = 1;\n }\n else\n {\n returnValue = 0;\n }\n }\n catch (Exception)\n {\n returnValue = -1;\n }\n finally\n {\n if (originalContext != null)\n {\n originalContext.Undo();\n }\n }\n }\n}\n USE master\nGO\nCREATE ASYMMETRIC KEY FileUtilitiesKey FROM EXECUTABLE FILE = 'J:\\FileUtilities.dll' \nCREATE LOGIN CLRLogin FROM ASYMMETRIC KEY FileUtilitiesKey \nGRANT EXTERNAL ACCESS ASSEMBLY TO CLRLogin \nALTER DATABASE database SET TRUSTWORTHY ON;\n DECLARE @i INT\n--EXEC FileExists '\\\\\\\\server\\\\share\\\\folder\\\\file.dat', @i OUT\nEXEC FileExists 'j:\\\\file.dat', @i OUT\nSELECT @i\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1992/" ]
16,656
<p>I am working on a program that needs to create a multiple temporary folders for the application. These will not be seen by the user. The app is written in VB.net. I can think of a few ways to do it such as incremental folder name or random numbered folder names, but I was wondering, how other people solve this problem?</p>
[ { "answer_id": 16672, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 4, "selected": false, "text": "System.IO.Path.GetTempFileName() System.IO.Path.GetDirectoryName(System.IO.Path.GetTempFileName())" }, { "answer_id": 16685, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "using System.IO;\n\nstring path = Path.GetTempPath() + Path.GetRandomFileName();\nwhile (Directory.Exists(path))\n path = Path.GetTempPath() + Path.GetRandomFileName();\n\nDirectory.CreateDirectory(path);\n" }, { "answer_id": 16701, "author": "Brian G Swanson", "author_id": 1795, "author_profile": "https://Stackoverflow.com/users/1795", "pm_score": 1, "selected": false, "text": "\nusing System.IO;\n\nstring path = Path.GetTempPath() + Path.GetRandomFileName();\n\nwhile (Directory.Exists(path)) \n path = Path.GetTempPath() + Path.GetRandomFileName();\n\nFile.Delete(path);\nDirectory.CreateDirectory(path);\n" }, { "answer_id": 16787, "author": "Rick", "author_id": 1752, "author_profile": "https://Stackoverflow.com/users/1752", "pm_score": 6, "selected": true, "text": "Private Function GetTempFolder() As String\n Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n Do While Directory.Exists(folder) or File.Exists(folder)\n folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n Loop\n\n Return folder\nEnd Function\n Private Function GetTempFolderGuid() As String\n Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)\n Do While Directory.Exists(folder) or File.Exists(folder)\n folder = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)\n Loop\n\n Return folder\nEnd Function\n" }, { "answer_id": 20710, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 3, "selected": false, "text": "System.IO.Path.GetTempPath()\n System.IO.Path.GetTempFileName()\n System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempFileName())\n" }, { "answer_id": 217198, "author": "Jonathan Wright", "author_id": 28840, "author_profile": "https://Stackoverflow.com/users/28840", "pm_score": 3, "selected": false, "text": "GetTempFileName() GetRandomFileName() Guid.NewGuid.ToString GetTempFileName() CreateDirectory() GetRandomFileName() CreateDirectory()" }, { "answer_id": 8750974, "author": "Daniel Trebbien", "author_id": 196844, "author_profile": "https://Stackoverflow.com/users/196844", "pm_score": 3, "selected": false, "text": "GetTempFileName() GetRandomFileName() Guid.NewGuid.ToString CreateDirectoryTransacted() CreateFileTransacted() // using System.ComponentModel;\n// using System.Runtime.InteropServices;\n// using System.Transactions;\n\n[ComImport]\n[Guid(\"79427a2b-f895-40e0-be79-b57dc82ed231\")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IKernelTransaction\n{\n void GetHandle(out IntPtr pHandle);\n}\n\n// 2.2 Win32 Error Codes <http://msdn.microsoft.com/en-us/library/cc231199.aspx>\npublic const int ERROR_PATH_NOT_FOUND = 0x3;\npublic const int ERROR_ALREADY_EXISTS = 0xb7;\npublic const int ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION = 0x1aaf;\n\n[DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\npublic static extern bool CreateDirectoryTransacted(string lpTemplateDirectory, string lpNewDirectory, IntPtr lpSecurityAttributes, IntPtr hTransaction);\n\n/// <summary>\n/// Creates a uniquely-named directory in the directory named by <paramref name=\"tempPath\"/> and returns the path to it.\n/// </summary>\n/// <param name=\"tempPath\">Path of a directory in which the temporary directory will be created.</param>\n/// <returns>The path of the newly-created temporary directory within <paramref name=\"tempPath\"/>.</returns>\npublic static string GetTempDirectoryName(string tempPath)\n{\n string retPath;\n\n using (TransactionScope transactionScope = new TransactionScope())\n {\n IKernelTransaction kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);\n IntPtr hTransaction;\n kernelTransaction.GetHandle(out hTransaction);\n\n while (!CreateDirectoryTransacted(null, retPath = Path.Combine(tempPath, Path.GetRandomFileName()), IntPtr.Zero, hTransaction))\n {\n int lastWin32Error = Marshal.GetLastWin32Error();\n switch (lastWin32Error)\n {\n case ERROR_ALREADY_EXISTS:\n break;\n default:\n throw new Win32Exception(lastWin32Error);\n }\n }\n\n transactionScope.Complete();\n }\n return retPath;\n}\n\n/// <summary>\n/// Equivalent to <c>GetTempDirectoryName(Path.GetTempPath())</c>.\n/// </summary>\n/// <seealso cref=\"GetTempDirectoryName(string)\"/>\npublic static string GetTempDirectoryName()\n{\n return GetTempDirectoryName(Path.GetTempPath());\n}\n" }, { "answer_id": 18579763, "author": "jri", "author_id": 1655724, "author_profile": "https://Stackoverflow.com/users/1655724", "pm_score": 0, "selected": false, "text": "Dim NewFolder = System.IO.Directory.CreateDirectory(IO.Path.Combine(IO.Path.GetTempPath, Guid.NewGuid.ToString))\n" }, { "answer_id": 39467623, "author": "Wilco BT", "author_id": 4153333, "author_profile": "https://Stackoverflow.com/users/4153333", "pm_score": 0, "selected": false, "text": "Private Function GetTempFolder() As String\n Dim folder As String\n Dim succes as Boolean = false\n Do While not succes\n folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n success = c_api_create_directory(folder)\n Loop\n Return folder\nEnd Function\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
16,727
<p>In GWT I have to specify what locales are supported in my application. The code get compiled in various files, one for each locale (beside other versions), but I have to give my clients one only URL. This URL is supposed to be a page that should be displayed according to the locale preferred by the browser. I dont't want to have an HTTP parameter for the locale since I want to forse the locale preferred by the browser. How can this be coded in GWT?</p> <p>Should I try to to this using apache rewrite rules? I thied it, but I think I cannot access such parameter easely in a rewrite rule.</p> <p>Thanks a lot, Giuseppe</p>
[ { "answer_id": 40521, "author": "Lloyd Meinholz", "author_id": 4229, "author_profile": "https://Stackoverflow.com/users/4229", "pm_score": 3, "selected": false, "text": "<inherits name=\"com.google.gwt.i18n.I18N\"/>\n errorMessage=Invalid Entry!\n import com.google.gwt.i18n.client.Constants;\n\npublic interface myConstants extends Constants {\n String errorMessage();\n}\n public class MyApplication implements EntryPoint {\n private static final MyConstants constants = (MyConstants)GWT.create(MyConstants.class);\n\n public void onModuleLoad() {\n final Label errorMessage = new Label(constants.errorMessage);\n }\n}\n" }, { "answer_id": 1343216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "com.google.gwt.i18n.client.LocaleInfo#getCurrentLocale()" }, { "answer_id": 15151797, "author": "Pavel", "author_id": 1282532, "author_profile": "https://Stackoverflow.com/users/1282532", "pm_score": 2, "selected": false, "text": "<inherits name=\"com.google.gwt.i18n.I18N\"/>\n\n<!-- Use browser-specified locale for i18n -->\n<set-configuration-property name=\"locale.useragent\" value=\"Y\"/>\n\n<!-- Specify locales your application support -->\n<extend-property name=\"locale\" values=\"en\"/>\n<extend-property name=\"locale\" values=\"de_DE\"/>\n<extend-property name=\"locale\" values=\"ru_RU\"/>\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
16,747
<p>I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.</p>
[ { "answer_id": 25606, "author": "Daniel Pollard", "author_id": 2758, "author_profile": "https://Stackoverflow.com/users/2758", "pm_score": 6, "selected": true, "text": "public JsonResult CheckUserName(string username)\n{\n return Json(CheckValidUsername(username));\n}\n" }, { "answer_id": 256975, "author": "Emad", "author_id": 18132, "author_profile": "https://Stackoverflow.com/users/18132", "pm_score": 1, "selected": false, "text": "\n\nclass User {\n\n [Required]\n public string Name{get;set;}\n\n [Email][Required]\n public string Email {get;set;}\n}\n\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549/" ]
16,762
<p>I have a couple CSS files with overlapping CSS selectors that I'd like to programmatically merge (as in not just appending one file to the end of the other). Is there any tool to do this online? or a Firefox extension perhaps?</p>
[ { "answer_id": 11005246, "author": "Ben23", "author_id": 1452316, "author_profile": "https://Stackoverflow.com/users/1452316", "pm_score": 1, "selected": false, "text": "font font-size font-weight a a a:hover a.extlink a#mylink .foo a #bar a p a pre > a a + p a img a #a .a" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2007/" ]
16,770
<p>I'm trying to fully understand all of Haskell's concepts.</p> <p>In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway? </p> <p>I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.</p>
[ { "answer_id": 16810, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 6, "selected": true, "text": " data List a = Cons a (List a) | Nil\n class List<a> {\n class Cons : List<a> {\n a head;\n List<a> tail;\n }\n class Nil : List<a> {}\n }\n" }, { "answer_id": 16825, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 0, "selected": false, "text": "data Tree = Empty \n | Leaf Int \n | Node Tree Tree\n" }, { "answer_id": 648959, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 4, "selected": false, "text": "data Bool = False | True\n data Pair a b = Pair a b\n type 'a 'b pair = Pair of 'a * 'b\n" }, { "answer_id": 5917133, "author": "Don Stewart", "author_id": 83805, "author_profile": "https://Stackoverflow.com/users/83805", "pm_score": 7, "selected": false, "text": "+ Either • X data X a = X a 1 () μ X² X•X 1 X + • data () = () 1 data Maybe a = Nothing | Just a 1 + X data [a] = [] | a : [a] L = 1+X•L data BTree a = Empty | Node a (BTree a) (BTree a) B = 1 + X•B² L = 1 + X + X² + X³ + ... ◦ F G F ◦ G R = X • (L ◦ R) L 1′ = 0 X′ = 1 (F + G)′ = F' + G′ (F • G)′ = F • G′ + F′ • G (F ◦ G)′ = (F′ ◦ G) • G′" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
16,792
<p>Came across this error today. Wondering if anyone can tell me what it means:</p> <blockquote> <blockquote> <p>Cannot sort a row of size 9522, which is greater than the allowable maximum of 8094.</p> </blockquote> </blockquote> <p>Is that 8094 bytes? Characters? Fields? Is this a problem joining multiple tables that are exceeding some limit?</p>
[ { "answer_id": 2547872, "author": "Kevin Albrecht", "author_id": 10475, "author_profile": "https://Stackoverflow.com/users/10475", "pm_score": 2, "selected": false, "text": "DBCC CLEANTABLE (0,[dbo.TableName])\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975282/" ]
16,795
<p>PHP has a great function called <a href="http://us2.php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer">htmlspecialcharacters()</a> where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's <em>almost</em> a one stop shop for sanitizing input. Very nice right?</p> <p>Well is there an equivalent in any of the .NET libraries?</p> <p>If not, can anyone link to any code samples or libraries that do this well?</p>
[ { "answer_id": 16802, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 5, "selected": true, "text": "var encodedHtml = HttpContext.Current.Server.HtmlEncode(...);\n" }, { "answer_id": 16807, "author": "Jason Shoulders", "author_id": 1953, "author_profile": "https://Stackoverflow.com/users/1953", "pm_score": 2, "selected": false, "text": "HtmlUtility.HtmlEncode HtmlUtility.UrlEncode RegularExpressionValidator RangeValidator System.Text.RegularExpression.Regex" }, { "answer_id": 1261065, "author": "michalstanko", "author_id": 154440, "author_profile": "https://Stackoverflow.com/users/154440", "pm_score": 2, "selected": false, "text": "HttpUtility.HtmlAttributeEncode()\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
16,804
<p>What options are there in the industry for enterprise reporting? I'm currently using SSRS 2005, and know that there is another version coming out with the new release of MSSQL.</p> <p>But, it seems like it might also be a good time to investigate the market to see what else is out there.</p> <p>What have you encountered? Do you like it/dislike it? Why?</p> <p>Thank you.</p>
[ { "answer_id": 144531, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 5, "selected": false, "text": "SELECT COUNT(*) FROM sometable WHERE 1=0\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733/" ]
16,815
<p>I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in <code>$_SESSION</code>) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the <code>?destroy=1</code> parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.</p> <p>I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.</p> <p>I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...</p> <p>See code here:</p> <pre><code>&lt;?php if ($_POST['destroy']) { session_destroy(); } else { session_start(); } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Session test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php if (isset($_POST['destroy'])) { echo "Destroy set"; } $_SESSION['counter']++; echo "You have visited this page " . $_SESSION['counter'] . " times" . "&lt;BR&gt;"; echo "I am tracking you using the session id " . session_id() . "&lt;BR&gt;"; echo "Click &lt;a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\"&gt;here&lt;/a&gt; to destroy the session."; ?&gt; </code></pre>
[ { "answer_id": 16818, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 4, "selected": true, "text": "$_POST['destroy']\n $_GET['destroy']\n" }, { "answer_id": 16826, "author": "ftdysa", "author_id": 2016, "author_profile": "https://Stackoverflow.com/users/2016", "pm_score": 1, "selected": false, "text": "if( $_GET['destroy'] == 1 )\n if( isset($_GET['destroy']) )\n" }, { "answer_id": 17141, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 2, "selected": false, "text": "session_start();\n$_SESSION = array();\nif (isset($_COOKIE[session_name()])) {\n setcookie(session_name(), '', time()-42000, '/');\n}\nsession_destroy();\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
16,828
<p>It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work</p> <pre><code>/something to search for/i </code></pre>
[ { "answer_id": 16837, "author": "Juha Syrjälä", "author_id": 1431, "author_profile": "https://Stackoverflow.com/users/1431", "pm_score": 10, "selected": true, "text": "-I" }, { "answer_id": 26069, "author": "sanmiguel", "author_id": 24, "author_profile": "https://Stackoverflow.com/users/24", "pm_score": 7, "selected": false, "text": "LESS LESS=-Ri grep +F tail -f <file>" }, { "answer_id": 13205810, "author": "Antony Thomas", "author_id": 984378, "author_profile": "https://Stackoverflow.com/users/984378", "pm_score": 5, "selected": false, "text": "-i :set smartcase -i" }, { "answer_id": 21956109, "author": "slm", "author_id": 33204, "author_profile": "https://Stackoverflow.com/users/33204", "pm_score": 4, "selected": false, "text": "less prompt> /search string/-i\n less h less prompt> h\n...\n -i ........ --ignore-case\n Ignore case in searches that do not contain uppercase.\n -I ........ --IGNORE-CASE\n Ignore case in all searches.\n...\n less less brew $ brew install less\n$ less --version\nless 530 (POSIX regular expressions)\nCopyright (C) 1984-2017 Mark Nudelman\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
16,829
<p>I know there are at least 10 different ways to structure project in version control. I'm curious what some methods being used are and which ones work for you. I've worked with SVN, TFS, and currently/unfortunately VSS. I've seen version control implemented very poorly and just OK, but never great.</p> <p>Just to get the ball rolling, here is a review of things I've seen.</p> <p>This example is SVN-based, but applies to most VCS's (not so much to distributed version control).</p> <ol> <li><p>branch the individual projects that are part of site /division/web/projectName/vb/src/[trunk|branches|tags]</p></li> <li><p>branch the whole site, in the case I've seen, the whole site except for core components was branched. /division/[trunk|branches|tags]/web/projectName/vb/src/</p></li> <li><p>Use main-line a default, only branch when necessary for <strong>huge</strong> changes.</p></li> </ol>
[ { "answer_id": 16915, "author": "Boris Terzic", "author_id": 1996, "author_profile": "https://Stackoverflow.com/users/1996", "pm_score": 3, "selected": false, "text": "svnrepo/\n trunk/\n modules/\n m1/ --> will result in jar file\n m2/\n ...\n assemblies/\n a1/\n ...\n tags/\n modules/\n m1/\n 1.0.0/\n 1.0.1/\n 1.1.0/\n m2/\n ...\n assemblies/\n a1/\n iteration-55/\n ...\n branches/\n m1/\n 1.0/\n ...\n" }, { "answer_id": 17363, "author": "Monroecheeseman", "author_id": 1351, "author_profile": "https://Stackoverflow.com/users/1351", "pm_score": 0, "selected": false, "text": "+ devroot\n +--Dept1\n +--Dept1Proj1\n +--Dept2Proj2\n +--Dept2\n +--Dept2Proj1\n +--Tools\n +--Purchase3rdPartyTools\n +--NLog\n +--CustomBuiltLibrary\n" }, { "answer_id": 8929709, "author": "altern", "author_id": 50962, "author_profile": "https://Stackoverflow.com/users/50962", "pm_score": 2, "selected": false, "text": "/project\n /trunk\n /tags\n /builds\n /PA\n /A\n /B\n /releases\n /AR\n /BR\n /RC\n /ST\n /branches\n /experimental\n /maintenance\n /versions\n /platforms\n /releases\n PA A B AR BR RC ST N.x.K N K 1.x.0 5.x.1 10.x.33 N.M.K N M K 1.0.0 5.3.1 10.22.33" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
16,832
<p>I am looking for a lightweight source control system for use on "hobby" projects with only one person (myself) working on the project. Does anyone have any suggestions? Ideally it should interface with Visual Studio either naively or through another plug-in, outside of that, anything that works would be nice to be replace Gmail as source control.</p>
[ { "answer_id": 16835, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 3, "selected": false, "text": "Svn1ClickSetup-1.3.3.exe" }, { "answer_id": 16844, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "git init\ngit add .\ngit commit -m \"my first commit!\"\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
16,833
<p>I need to periodically download, extract and save the contents of <a href="http://data.dot.state.mn.us/dds/det_sample.xml.gz" rel="noreferrer">http://data.dot.state.mn.us/dds/det_sample.xml.gz</a> to disk. Anyone have experience downloading gzipped files with C#?</p>
[ { "answer_id": 16852, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": false, "text": "WebClient Client = new WebClient ();\nClient.DownloadFile(\"http://data.dot.state.mn.us/dds/det_sample.xml.gz\", \" C:\\mygzipfile.gz\");\n" }, { "answer_id": 16853, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": false, "text": "using ICSharpCode.SharpZipLib.Zip;\n\nFastZip fz = new FastZip(); \nfz.ExtractZip(zipFile, targetDirectory,\"\");\n" }, { "answer_id": 16856, "author": "JeremiahClark", "author_id": 581, "author_profile": "https://Stackoverflow.com/users/581", "pm_score": 6, "selected": true, "text": "using (FileStream fStream = new FileStream(@\"C:\\test.docx.gzip\", \nFileMode.Create, FileAccess.Write)) {\n using (GZipStream zipStream = new GZipStream(fStream, \n CompressionMode.Compress)) {\n byte[] inputfile = File.ReadAllBytes(@\"c:\\test.docx\");\n zipStream.Write(inputfile, 0, inputfile.Length);\n }\n}\n using (FileStream fInStream = new FileStream(@\"c:\\test.docx.gz\", \nFileMode.Open, FileAccess.Read)) {\n using (GZipStream zipStream = new GZipStream(fInStream, CompressionMode.Decompress)) { \n using (FileStream fOutStream = new FileStream(@\"c:\\test1.docx\", \n FileMode.Create, FileAccess.Write)) {\n byte[] tempBytes = new byte[4096];\n int i;\n while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0) {\n fOutStream.Write(tempBytes, 0, i);\n }\n }\n }\n}\n" }, { "answer_id": 70603695, "author": "Ajai Rajendran", "author_id": 17847889, "author_profile": "https://Stackoverflow.com/users/17847889", "pm_score": 0, "selected": false, "text": "HttpContext DataTable StringBuilder inputString byte[] buffer = Encoding.ASCII.GetBytes(inputString.ToString());\nHttpContext.Current.Response.Clear();\nHttpContext.Current.Response.Buffer = true;\nHttpContext.Current.Response.ContentType = \"application/zip\";\nHttpContext.Current.Response.AddHeader(\"Content-Disposition\", string.Format(\"attachment;filename={0}.csv.gz\", fileName));\nHttpContext.Current.Response.Filter = new GZipStream(HttpContext.Current.Response.Filter, CompressionMode.Compress);\nHttpContext.Current.Response.AppendHeader(\"Content-Encoding\", \"gzip\");\nusing (GZipStream zipStream = new GZipStream(HttpContext.Current.Response.OutputStream, CompressionMode.Compress))\n{\n zipStream.Write(buffer, 0, buffer.Length);\n}\nHttpContext.Current.Response.End();\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
16,861
<p>What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="noreferrer">XSS</a> or SQL injection attack?</p>
[ { "answer_id": 25136, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 5, "selected": false, "text": "onclick href=\"javascript:...\" <a href=\"ja&#x09;vascript:alert('hi')\"> <a href=\"ja vascript:alert('hi')\"> import re\nfrom urlparse import urljoin\nfrom BeautifulSoup import BeautifulSoup, Comment\n\ndef sanitizeHtml(value, base_url=None):\n rjs = r'[\\s]*(&#x.{1,7})?'.join(list('javascript:'))\n rvb = r'[\\s]*(&#x.{1,7})?'.join(list('vbscript:'))\n re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)\n validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()\n validAttrs = 'href src width height'.split()\n urlAttrs = 'href src'.split() # Attributes which should have a URL\n soup = BeautifulSoup(value)\n for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):\n # Get rid of comments\n comment.extract()\n for tag in soup.findAll(True):\n if tag.name not in validTags:\n tag.hidden = True\n attrs = tag.attrs\n tag.attrs = []\n for attr, val in attrs:\n if attr in validAttrs:\n val = re_scripts.sub('', val) # Remove scripts (vbs & js)\n if attr in urlAttrs:\n val = urljoin(base_url, val) # Calculate the absolute url\n tag.attrs.append((attr, val))\n\n return soup.renderContents().decode('utf8')\n" }, { "answer_id": 248933, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "html5lib style sanitize_html" }, { "answer_id": 1503641, "author": "Mr. Napik", "author_id": 170918, "author_profile": "https://Stackoverflow.com/users/170918", "pm_score": 0, "selected": false, "text": "datasetName = datasetName.replace(\"'\",\"\").replace('\"',\"\")\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019/" ]
16,891
<p>As you may know, in <code>VS 2008</code> <kbd>ctrl</kbd>+<kbd>tab</kbd> brings up a nifty navigator window with a thumbnail of each file. I love it, but there is one tiny thing that is annoying to me about this feature: <em>the window stays around after releasing the <kbd>ctrl</kbd> key</em>. When doing an <kbd>alt</kbd>+<kbd>tab</kbd> in windows, you can hit tab to get to the item you want (while still holding down the <kbd>alt</kbd> key), and then when you find what you want, <em>lifting up</em> on the <kbd>alt</kbd> key selects that item.</p> <p>I wish <code>VS 2008</code> would do the same. For me, when I lift off of <kbd>ctrl</kbd>, the window is still there. I have to hit <kbd>enter</kbd> to actually select the item. I find this annoying.</p> <p>Does anyone know how to make <code>VS 2008</code> dismiss the window on the <em>release</em> of the <kbd>ctrl</kbd> key?</p>
[ { "answer_id": 6413653, "author": "SliverNinja - MSFT", "author_id": 175679, "author_profile": "https://Stackoverflow.com/users/175679", "pm_score": 2, "selected": false, "text": "Window.NextDocumentWindow Window.NextDocumentWindowNav" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1789/" ]
16,926
<p>My HTML is all marked up, ready to make it rain CSS. The problem is that I have to go back and find out what all my id and class names are so I can get started. What I need is a tool that parses my HTML and spits out a stylesheet with all the possible elements ready to be styled (maybe even with some defaults). Does such a tool exist?</p>
[ { "answer_id": 16989, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\n $(document).ready(function() {\n\n $('*[@id]').each(function() {\n console.log('#' + this.id + ' {}');\n });\n $('*[@class]').each(function() {\n $.each($(this).attr('class').split(\" \"), function() {\n console.log('.' + this + ' {}');\n });\n });\n });\n</script>\n #spinner {}\n#log {}\n#area {}\n.cards {}\n.dialog {}\n.controller {}\n <script type=\"text/javascript\">\n $(document).ready(function() {\n $('*').each(function() {\n if($(this).is('[@id]')) {\n console.log('#' + this.id + ' {}');\n }\n if($(this).is('[@class]')) {\n $.each($(this).attr('class').split(\" \"), function() {\n console.log('.' + this + ' {}');\n });\n }\n });\n });\n</script>\n" }, { "answer_id": 330652, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 2, "selected": false, "text": "<div id=\"nav\">\n <ul id=\"nav_list\">\n <li class=\"nav_list_item\">\n <a class=\"navlist_item_link\" href=\"foo\">foo</a>\n </li>\n <li class=\"nav_list_item\">\n <a class=\"navlist_item_link\" href=\"bar\">bar</a>\n </li>\n <li class=\"nav_list_item\">\n <a class=\"navlist_item_link\" href=\"baz\">baz</a>\n </li>\n </ul>\n</div>\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/744/" ]
16,935
<p>I'm trying to compile over 100 java classes from different packages from a clean directory (no incremental compiles) using the following ant tasks:</p> <pre><code>&lt;target name="-main-src-depend"&gt; &lt;depend srcdir="${src.dir}" destdir="${bin.dir}" cache="${cache.dir}" closure="true"/&gt; &lt;/target&gt; &lt;target name="compile" depends="-main-src-depend" description="Compiles the project."&gt; &lt;echo&gt;Compiling&lt;/echo&gt; &lt;javac target="${javac.target}" source="${javac.source}" debug="${javac.debug}" srcdir="${src.dir}" destdir="${bin.dir}"&gt; &lt;classpath&gt; &lt;path refid="runtime.classpath"/&gt; &lt;path refid="compile.classpath"/&gt; &lt;/classpath&gt; &lt;/javac&gt; &lt;/target&gt; </code></pre> <p>However, the first time I run the compile task I always get a StackOverflowException. If I run the task again the compiler does an incremental build and everything works fine. This is undesirable since we are using <a href="http://cruisecontrol.sourceforge.net/" rel="noreferrer">CruiseControl</a> to do an automatic daily build and this is causing false build failures.</p> <p>As a quick-and-dirty solution I have created 2 separate tasks, compiling portions of the project in each. I really don't think this solution will hold as more classes are added in the future, and I don't want to be adding new compile tasks every time we hit the "compile limit".</p>
[ { "answer_id": 16955, "author": "jmanning2k", "author_id": 1480, "author_profile": "https://Stackoverflow.com/users/1480", "pm_score": 1, "selected": false, "text": "javac memoryinitialsize=\"256M\" memorymaximumsize=\"1024M\"\n fork=\"true\" javac fork=\"true\"" }, { "answer_id": 16982, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 0, "selected": false, "text": "javac -Xss ant fork=\"true\" <compilerarg> <javac> fork=\"true\"" }, { "answer_id": 18086, "author": "Elliot Vargas", "author_id": 2024, "author_profile": "https://Stackoverflow.com/users/2024", "pm_score": 0, "selected": false, "text": "fork=\"true\" memoryinitialsize=\"256m\" memorymaximumsize=\"1024m\" (this.A == null && other.getA() == null) || (this.A != null && this.A.equals(other.getA()))\n" }, { "answer_id": 19782, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "$ javac -version\njavac 1.6.0_05\n javac -help\njavac -X\njavac -J-X\n javac -J-Xss10M Foo.java\n <javac srcdir=\"gen\" destdir=\"gen-bin\" debug=\"on\" fork=\"true\">\n <compilerarg value=\"-J-Xss10M\" />\n</javac>\n" }, { "answer_id": 1042236, "author": "npellow", "author_id": 2767300, "author_profile": "https://Stackoverflow.com/users/2767300", "pm_score": 2, "selected": false, "text": " <javac srcdir=\"gen\" destdir=\"gen-bin\" debug=\"on\" fork=\"true\">\n <compilerarg value=\"-J-Xss10M\" />\n </javac>\n <javac srcdir=\"gen\" destdir=\"gen-bin\" debug=\"on\" fork=\"true\">\n <compilerarg value=\"-J -Xss10M\" />\n</javac>\n [javac] \n[javac] The ' characters around the executable and arguments are\n[javac] not part of the command.\n[javac] Files to be compiled:\n" }, { "answer_id": 66958359, "author": "l k", "author_id": 6292018, "author_profile": "https://Stackoverflow.com/users/6292018", "pm_score": 0, "selected": false, "text": "fork=\"true\" ANT_OPTS ANT_OPTS=-Xss10M ant\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024/" ]
16,939
<p>I am reading a binary file into a parsing program. I will need to iterate through the file and look for certain markers so I can split the file up and pass those parts into their respective object’s constructors.</p> <p>Is there an advantage to holding the file as a stream, either MemoryStream or FileStream, or should it be converted into a byte[] array?</p> <p>Keith</p>
[ { "answer_id": 16967, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 6, "selected": true, "text": "byte[] MemoryStream MemoryStream FileStream BinaryReader BinaryWriter" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
16,945
<p>I would like to rename files and folders recursively by applying a string replacement operation.</p> <p>E.g. The word "shark" in files and folders should be replaced by the word "orca".</p> <p><code>C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe</code> </p> <p>should be moved to:</p> <p><code>C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe</code></p> <p>The same operation should be of course applied to each child object in each folder level as well.</p> <p>I was experimenting with some of the members of the <code>System.IO.FileInfo</code> and <code>System.IO.DirectoryInfo</code> classes but didn't find an easy way to do it.</p> <pre><code>fi.MoveTo(fi.FullName.Replace("shark", "orca")); </code></pre> <p>Doesn't do the trick.</p> <p>I was hoping there is some kind of "genius" way to perform this kind of operation. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17028, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "function Move-Stuff($folder)\n{\n foreach($sub in [System.IO.Directory]::GetDirectories($folder))\n {\n Move-Stuff $sub\n }\n $new = $folder.Replace(\"Shark\", \"Orca\")\n if(!(Test-Path($new)))\n {\n new-item -path $new -type directory\n }\n foreach($file in [System.IO.Directory]::GetFiles($folder))\n {\n $new = $file.Replace(\"Shark\", \"Orca\")\n move-item $file $new\n }\n}\n\nMove-Stuff \"C:\\Temp\\Test\"\n" }, { "answer_id": 17052, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "string oldPath = \"\\\\shark.exe\"\nstring newPath = oldPath.Replace(\"shark\", \"orca\");\n\nSystem.IO.File.Move(oldPath, newPath);\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
16,963
<p>Curious if others feel the same as me. To me, controls such as datagrid/gridview/formview/etc. are great for presentations or demo's only. To take the time and tweak this controls, override their default behavior (hooking into their silly events etc.) is a big headache. The only control that I use is the repeater, since it offers me the most flexibility over the others.</p> <p><strong>In short, they are pretty much bloatware.</strong></p> <p>I'd rather weave my own html/css, use my own custom paging queries. </p> <p>Again, if you need to throw up a quick page these controls are great (especially if you are trying to woo people into the ease of <code>.NET</code> development).</p> <p>I must be in the minority, otherwise MS wouldn't dedicated so much development time on these types of controls... ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 16978, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<asp:GridView ...>\n <Columns>\n <my:AutoField HeaderText=\"Type\" \n DataField=\"TypeId\"\n ListDataSourceID=\"TypesDataSource\"\n ListDataTextField=\"TypeName\" /> \n </Columns>\n\n <EmptyDataTemplate>\n <my:AutoEmptyData runat=\"server\" />\n </EmptyDataTemplate>\n\n</asp:GridView>\n" }, { "answer_id": 256118, "author": "p.campbell", "author_id": 23199, "author_profile": "https://Stackoverflow.com/users/23199", "pm_score": 2, "selected": false, "text": "asp:HyperlinkField List ArrayList Hashtable SqlDataReader SqlDataSource SqlDataSource ObjectDataSource" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
16,964
<p>I'm trying to implement something like this:</p> <pre><code>&lt;div&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Port name&lt;/td&gt; &lt;td&gt;Current port version&lt;/td&gt; &lt;td&gt;New port version&lt;/td&gt; &lt;td&gt;Update&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;% foreach (var ip in Ports) { %&gt; &lt;tr&gt; &lt;td&gt; &lt;%= ip.PortName %&gt; &lt;/td&gt; &lt;td&gt; &lt;%= ip.CurrentVersion %&gt; &lt;/td&gt; &lt;td&gt; &lt;%= ip.NewVersion %&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="&lt;% ip.PortName %&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>The button's <code>CommandArgument</code> property is where my code complains about not being able to resolve symbol <code>ip</code>. Is there any way to do what I'm trying to do? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 594544, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 1, "selected": false, "text": "HtmlHelper ViewPage <% using(Html.BeginForm(\"Update\", \"Ip\", new {portName = ip.PortName} )) { %>\n\n ....\n <input name=\"action\" type=\"submit\" value=\"Update\">\n\n<% } %>\n <%= Html.ActionLink(\"Update IP\", \"Update\", \"Ip\", \n new { \n portName = ip.PortName \n }) \n%>\n public ActionResult Update(string portName) {\n // ...\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614/" ]
16,971
<p>I would like to have a nice template for doing this in development. How do I reset an increment identity's starting value in SQL Server?</p>
[ { "answer_id": 16977, "author": "Ryan Sampson", "author_id": 1375, "author_profile": "https://Stackoverflow.com/users/1375", "pm_score": 8, "selected": true, "text": "DBCC CHECKIDENT('TableName', RESEED, 0)\n" }, { "answer_id": 16983, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "DBCC CHECKIDENT (MyTable, RESEED, 100)\n" }, { "answer_id": 17016, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 5, "selected": false, "text": "DBCC CHECKIDENT (MyTable, RESEED, 0)" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1976/" ]
16,991
<p>I've been using Eclipse with RDT (not RadRails) a lot lately, and I'm quite happy with it, but I'm wondering if you guys know any decent alternatives. I know NetBeans also supports Ruby these days, but I'm not sure what it has to offer over Eclipse.</p> <p>Please, list any features you think are brilliant or useful when suggesting an IDE, makes it easier to compare.</p> <p>Also, I said Ruby, not Rails. While Rails support is a plus, I prefer things to be none Rails-centric. It should also be available on Linux and optionally Solaris.</p>
[ { "answer_id": 4040692, "author": "so_mv", "author_id": 186858, "author_profile": "https://Stackoverflow.com/users/186858", "pm_score": 3, "selected": false, "text": "code completion debugging code navigation Relying on code completion and code navigation is anti-ruby/rails" }, { "answer_id": 5790859, "author": "Michael De Silva", "author_id": 449342, "author_profile": "https://Stackoverflow.com/users/449342", "pm_score": 2, "selected": false, "text": "cd 'your-shiny-ruby-project'\nmate .\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018/" ]
16,998
<p>I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse:</p> <pre><code>// response is an HttpWebResponse StreamReader reader = new StreamReader(response.GetResponseStream()); string output = reader.ReadToEnd(); // throws exception... </code></pre> <p>When the <code>reader.ReadToEnd()</code> method is called I'm getting the following System.IO.IOException: <strong>Unable to read data from the transport connection: The connection was closed.</strong></p> <p>The above code works just fine when server returns a "non-chunked" response.</p> <p>The only way I've been able to get it to work is to use HTTP/1.0 for the initial request (instead of HTTP/1.1, the default) but this seems like a lame work-around.</p> <p>Any ideas?</p> <hr> <p>@Chuck</p> <p>Your solution works pretty good. It still throws the same IOExeception on the last Read(). But after inspecting the contents of the StringBuilder it looks like all the data has been received. So perhaps I just need to wrap the Read() in a try-catch and swallow the "error".</p>
[ { "answer_id": 17236, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "StringBuilder sb = new StringBuilder();\nByte[] buf = new byte[8192];\nStream resStream = response.GetResponseStream();\nstring tmpString = null;\nint count = 0;\ndo\n{\n count = resStream.Read(buf, 0, buf.Length);\n if(count != 0)\n {\n tmpString = Encoding.ASCII.GetString(buf, 0, count);\n sb.Append(tmpString);\n }\n}while (count > 0);\n" }, { "answer_id": 352440, "author": "Liam Corner", "author_id": 44565, "author_profile": "https://Stackoverflow.com/users/44565", "pm_score": -1, "selected": false, "text": "using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))\n{\n StringBuilder sb = new StringBuilder();\n\n try\n {\n while (!sr.EndOfStream)\n {\n sb.Append((char)sr.Read());\n }\n }\n catch (System.IO.IOException)\n { }\n\n string content = sb.ToString();\n}\n" }, { "answer_id": 57149944, "author": "Steven Craft", "author_id": 312000, "author_profile": "https://Stackoverflow.com/users/312000", "pm_score": 0, "selected": false, "text": "byte[] data;\nvar responseStream = response.GetResponseStream();\nvar reader = new StreamReader(responseStream, Encoding.UTF8);\ndata = Encoding.UTF8.GetBytes(reader.ReadToEnd());\nreturn Encoding.Default.GetString(data.ToArray());\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/16998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2047/" ]
17,017
<p>How do I convert a DateTime structure to its equivalent <a href="http://www.ietf.org/rfc/rfc3339.txt" rel="noreferrer">RFC 3339</a> formatted string representation and/or parse this string representation back to a <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> structure? The RFC-3339 date-time format is used in a number of specifications such as the <a href="http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs" rel="noreferrer">Atom Syndication Format</a>.</p>
[ { "answer_id": 17021, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Globalization;\n\nnamespace DateTimeConsoleApplication\n{\n /// <summary>\n /// Provides methods for converting <see cref=\"DateTime\"/> structures to and from the equivalent RFC 3339 string representation.\n /// </summary>\n public static class Rfc3339DateTime\n {\n //============================================================\n // Private members\n //============================================================\n #region Private Members\n /// <summary>\n /// Private member to hold array of formats that RFC 3339 date-time representations conform to.\n /// </summary>\n private static string[] formats = new string[0];\n /// <summary>\n /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format.\n /// </summary>\n private const string format = \"yyyy-MM-dd'T'HH:mm:ss.fffK\";\n #endregion\n\n //============================================================\n // Public Properties\n //============================================================\n #region Rfc3339DateTimeFormat\n /// <summary>\n /// Gets the custom format specifier that may be used to represent a <see cref=\"DateTime\"/> in the RFC 3339 format.\n /// </summary>\n /// <value>A <i>DateTime format string</i> that may be used to represent a <see cref=\"DateTime\"/> in the RFC 3339 format.</value>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of a <see cref=\"DateTime\"/> that \n /// is precise to the three most significant digits of the seconds fraction; that is, it represents \n /// the milliseconds in a date and time value. The <see cref=\"Rfc3339DateTimeFormat\"/> is a valid \n /// date-time format string for use in the <see cref=\"DateTime.ToString(String, IFormatProvider)\"/> method.\n /// </para>\n /// </remarks>\n public static string Rfc3339DateTimeFormat\n {\n get\n {\n return format;\n }\n }\n #endregion\n\n #region Rfc3339DateTimePatterns\n /// <summary>\n /// Gets an array of the expected formats for RFC 3339 date-time string representations.\n /// </summary>\n /// <value>\n /// An array of the expected formats for RFC 3339 date-time string representations \n /// that may used in the <see cref=\"DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)\"/> method.\n /// </value>\n public static string[] Rfc3339DateTimePatterns\n {\n get\n {\n if (formats.Length > 0)\n {\n return formats;\n }\n else\n {\n formats = new string[11];\n\n // Rfc3339DateTimePatterns\n formats[0] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\";\n formats[1] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK\";\n formats[2] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK\";\n formats[3] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK\";\n formats[4] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK\";\n formats[5] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK\";\n formats[6] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK\";\n formats[7] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ssK\";\n\n // Fall back patterns\n formats[8] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\"; // RoundtripDateTimePattern\n formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n return formats;\n }\n }\n }\n #endregion\n\n //============================================================\n // Public Methods\n //============================================================\n #region Parse(string s)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <returns>A <see cref=\"DateTime\"/> equivalent to the date and time contained in <paramref name=\"s\"/>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"FormatException\"><paramref name=\"s\"/> does not contain a valid RFC 3339 string representation of a date and time.</exception>\n public static DateTime Parse(string s)\n {\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n if(s == null)\n {\n throw new ArgumentNullException(\"s\");\n }\n\n DateTime result;\n if (Rfc3339DateTime.TryParse(s, out result))\n {\n return result;\n }\n else\n {\n throw new FormatException(String.Format(null, \"{0} is not a valid RFC 3339 string representation of a date and time.\", s));\n }\n }\n #endregion\n\n #region ToString(DateTime utcDateTime)\n /// <summary>\n /// Converts the value of the specified <see cref=\"DateTime\"/> object to its equivalent string representation.\n /// </summary>\n /// <param name=\"utcDateTime\">The Coordinated Universal Time (UTC) <see cref=\"DateTime\"/> to convert.</param>\n /// <returns>A RFC 3339 string representation of the value of the <paramref name=\"utcDateTime\"/>.</returns>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of the <paramref name=\"utcDateTime\"/> that \n /// is precise to the three most significant digits of the seconds fraction; that is, it represents \n /// the milliseconds in a date and time value.\n /// </para>\n /// <para>\n /// While it is possible to display higher precision fractions of a second component of a time value, \n /// that value may not be meaningful. The precision of date and time values depends on the resolution \n /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's \n /// resolution is approximately 10-15 milliseconds.\n /// </para>\n /// </remarks>\n /// <exception cref=\"ArgumentException\">The specified <paramref name=\"utcDateTime\"/> object does not represent a <see cref=\"DateTimeKind.Utc\">Coordinated Universal Time (UTC)</see> value.</exception>\n public static string ToString(DateTime utcDateTime)\n {\n if (utcDateTime.Kind != DateTimeKind.Utc)\n {\n throw new ArgumentException(\"utcDateTime\");\n }\n\n return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n }\n #endregion\n\n #region TryParse(string s, out DateTime result)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <param name=\"result\">\n /// When this method returns, contains the <see cref=\"DateTime\"/> value equivalent to the date and time \n /// contained in <paramref name=\"s\"/>, if the conversion succeeded, \n /// or <see cref=\"DateTime.MinValue\">MinValue</see> if the conversion failed. \n /// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic), \n /// or does not contain a valid string representation of a date and time. \n /// This parameter is passed uninitialized.\n /// </param>\n /// <returns><b>true</b> if the <paramref name=\"s\"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n public static bool TryParse(string s, out DateTime result)\n {\n //------------------------------------------------------------\n // Attempt to convert string representation\n //------------------------------------------------------------\n bool wasConverted = false;\n result = DateTime.MinValue;\n\n if (!String.IsNullOrEmpty(s))\n {\n DateTime parseResult;\n if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n {\n result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n wasConverted = true;\n }\n }\n\n return wasConverted;\n }\n #endregion\n }\n}\n" }, { "answer_id": 17025, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": -1, "selected": false, "text": " datetime.ToString(\"YYYY-MM-DD'T'HH:mm:ssZ\")\n DateTime.Parse() DateTime" }, { "answer_id": 91146, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 6, "selected": false, "text": "XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)\n XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)\n" }, { "answer_id": 43358041, "author": "user1560963", "author_id": 1560963, "author_profile": "https://Stackoverflow.com/users/1560963", "pm_score": -1, "selected": false, "text": "rfcFormat = DateDiff(\"s\", \"1/1/1970\", Now())\n" }, { "answer_id": 59933089, "author": "rothschild86", "author_id": 955459, "author_profile": "https://Stackoverflow.com/users/955459", "pm_score": -1, "selected": false, "text": "JsonConvert.SerializeObject(DateTime.Now);\n" }, { "answer_id": 69047714, "author": "Felipe Maricato Moura", "author_id": 1837537, "author_profile": "https://Stackoverflow.com/users/1837537", "pm_score": -1, "selected": false, "text": "<input asp-for=\"StartDate\" class=\"form-control\" value=\"@DateTime.Now.ToString(\"yyyy-MM-ddThh:mm:ss\")\" />\n" }, { "answer_id": 69941381, "author": "Andrey Stukalin", "author_id": 467851, "author_profile": "https://Stackoverflow.com/users/467851", "pm_score": 0, "selected": false, "text": "System.Text.Json JsonSerializer.Serialize(DateTime.Now)\n" }, { "answer_id": 74110087, "author": "Pedro Coelho", "author_id": 9513617, "author_profile": "https://Stackoverflow.com/users/9513617", "pm_score": 0, "selected": false, "text": "public static class DateTimeExtensions\n{\n public static string ToRFC3339(this DateTime date)\n {\n return date.ToUniversalTime().ToString(\"yyyy-MM-dd'T'HH:mm:ss.fffK\");\n }\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2029/" ]
17,020
<p>I have a new 1 TB drive coming in tomorrow. What is the best way to divide this space for a development workstation?</p> <p>The biggest problem I think I'm going to have is that some partitions (probably /usr) will become to small after a bit of use. Other partitions are probably to huge. The swap drive for example is currently 2GB (2x 1GB RAM), but it is almost never used (only once that I know of).</p>
[ { "answer_id": 30415, "author": "palm3D", "author_id": 2686, "author_profile": "https://Stackoverflow.com/users/2686", "pm_score": 2, "selected": false, "text": "quota" }, { "answer_id": 30419, "author": "palm3D", "author_id": 2686, "author_profile": "https://Stackoverflow.com/users/2686", "pm_score": 1, "selected": false, "text": "fsck" }, { "answer_id": 731111, "author": "Zifre", "author_id": 83871, "author_profile": "https://Stackoverflow.com/users/83871", "pm_score": 1, "selected": false, "text": "/ /home /boot" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1633/" ]
17,032
<p><a href="http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html" rel="noreferrer">Resharper</a> certainly thinks so, and out of the box it will nag you to convert</p> <pre><code>Dooberry dooberry = new Dooberry(); </code></pre> <p>to</p> <pre><code>var dooberry = new Dooberry(); </code></pre> <p>Is that really considered the best style?</p>
[ { "answer_id": 17042, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 6, "selected": true, "text": "var result = GetUserID();\n" }, { "answer_id": 17044, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "Generic<OtherGeneric< T,U,V>, Dictionary< X, Y>>>" }, { "answer_id": 17100, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "var myvariable = DateTime.Now\nDateTime myvariable = DateTime.Now;\n var myvariable = ResultFromMethod();\n" }, { "answer_id": 17347, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 4, "selected": false, "text": "XmlNodeList itemList = rssNode.SelectNodes(\"item\");\nvar rssItems = new RssItem[itemList.Count];\n var itemList = rssNode.SelectNodes(\"item\");\nvar rssItems = new RssItem[itemList.Count];\n" }, { "answer_id": 68091505, "author": "Misha Zaslavsky", "author_id": 2667173, "author_profile": "https://Stackoverflow.com/users/2667173", "pm_score": 1, "selected": false, "text": "C# 9.0 Dooberry dooberry = new();\n var Dooberry dooberry = GetDooberry();\n var now = DateTime.Now;\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ]
17,054
<p>How do you use network sockets in Pascal? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17062, "author": "Mickey", "author_id": 1494, "author_profile": "https://Stackoverflow.com/users/1494", "pm_score": 4, "selected": true, "text": "program daytime;\n\n{ Simple client program }\n\nuses\n sockets, inetaux, myerror;\n\nconst\n RemotePort : Word = 13;\n\nvar\n Sock : LongInt;\n sAddr : TInetSockAddr;\n sin, sout : Text;\n Line : String;\n\nbegin\n if ParamCount = 0 then GenError('Supply IP address as parameter.');\n\n with sAddr do\n begin\n Family := af_inet;\n Port := htons(RemotePort);\n Addr := StrToAddr(ParamStr(1));\n if Addr = 0 then GenError('Not a valid IP address.');\n end;\n\n Sock := Socket(af_inet, sock_stream, 0);\n if Sock = -1 then SockError('Socket: ');\n\n if not Connect(Sock, sAddr, sizeof(sAddr)) then SockError('Connect: ');\n Sock2Text(Sock, sin, sout);\n Reset(sin);\n Rewrite(sout);\n\n while not eof(sin) do \n begin\n Readln(sin, Line);\n Writeln(Line);\n end;\n\n Close(sin);\n Close(sout);\n Shutdown(Sock, 2);\nend.\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868/" ]
17,056
<p>I'm currently working on an application where we have a SQL-Server database and I need to get a full text search working that allows us to search people's names.</p> <p>Currently the user can enter a into a name field that searches 3 different varchar cols. First, Last, Middle names</p> <p>So say I have 3 rows with the following info.</p> <p>1 - Phillip - J - Fry</p> <p>2 - Amy - NULL - Wong</p> <p>3 - Leo - NULL - Wong</p> <p>If the user enters a name such as 'Fry' it will return row 1. However if they enter Phillip Fry, or Fr, or Phil they get nothing.. and I don't understand why its doing this. If they search for Wong they get rows 2 and 3 if they search for Amy Wong they again get nothing.</p> <p>Currently the query is using CONTAINSTABLE but I have switched that with FREETEXTTABLE, CONTAINS, and FREETEXT without any noticeable differences in the results. The table methods are be preferred because they return the same results but with ranking.</p> <p>Here is the query.</p> <pre><code>.... @Name nvarchar(100), .... --""s added to prevent crash if searching on more then one word. DECLARE @SearchString varchar(100) SET @SearchString = '"'+@Name+'"' SELECT Per.Lastname, Per.Firstname, Per.MiddleName FROM Person as Per INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) AS KEYTBL ON Per.Person_ID = KEYTBL.[KEY] WHERE KEY_TBL.RANK &gt; 2 ORDER BY KEYTBL.RANK DESC; .... </code></pre> <p>Any Ideas...? Why this full text search is not working correctly ?</p>
[ { "answer_id": 18072, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "INNER JOIN FREETEXTTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) \n" }, { "answer_id": 18226, "author": "corymathews", "author_id": 1925, "author_profile": "https://Stackoverflow.com/users/1925", "pm_score": 3, "selected": true, "text": "....\n@Name nvarchar(100),\n....\n--\"\"s added to prevent crash if searching on more then one word.\nDECLARE @SearchString varchar(100)\n\n--Added this line\nSET @SearchString = REPLACE(@Name, ' ', '*\" OR \"*')\nSET @SearchString = '\"*'+@SearchString+'*\"'\n\nSELECT Per.Lastname, Per.Firstname, Per.MiddleName\nFROM Person as Per\nINNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) \nAS KEYTBL\nON Per.Person_ID = KEYTBL.[KEY]\nWHERE KEY_TBL.RANK > 2\nORDER BY KEYTBL.RANK DESC; \n....\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925/" ]
17,085
<p>I have a simple CAML query like</p> <pre><code>&lt;Where&gt;&lt;Eq&gt;&lt;Field="FieldName"&gt;&lt;Value Type="Text"&gt;Value text&lt;/Value&gt;&lt;/Field&gt;&lt;/Eq&gt;&lt;/Where&gt; </code></pre> <p>And I have a variable to substitute for <code>Value text</code>. What's the best way to validate/escape the text that is substituted here in the .NET framework? I've done a quick web search on this problem but all what I found was <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.aspx" rel="nofollow noreferrer"><code>System.Xml.Convert</code></a> class but this seems to be not quite what I need here.</p> <p>I know I could have gone with an <code>XmlWriter</code> here, but it seems like a lot of code for such a simple task where I just need to make sure that the <code>Value text</code> part is formatted well.</p>
[ { "answer_id": 17093, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "System.Xml.Linq.XElement SetValue" }, { "answer_id": 17137, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 0, "selected": false, "text": "public class Example\n{\n private const string CAMLQUERY = \"<Where><Eq><Field=\\\"FieldName\\\"><Value Type=\\\"Text\\\">{0}</Value></Field></Eq></Where>\";\n\n public string PrepareCamlQuery(string textValue)\n {\n return String.Format(CAMLQUERY, textValue);\n }\n}\n" }, { "answer_id": 22293, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "XmlDocument doc = new XmlDocument();\n\n// Create the Where Node\nXmlNode whereNode = doc.CreateNode(XmlNodeType.Element, \"Where\", string.Empty);\nXmlNode eqNode = doc.CreateNode(XmlNodeType.Element, \"Eq\", string.Empty);\nXmlNode fieldNode = doc.CreateNode(XmlNodeType.Element, \"Field\", string.Empty);\n\nXmlAttribute newAttribute = doc.CreateAttribute(\"FieldName\");\nnewAttribute.InnerText = \"Name\";\nfieldNode.Attributes.Append(newAttribute);\n\nXmlNode valueNode = doc.CreateNode(XmlNodeType.Element, \"Value\", string.Empty);\n\nXmlAttribute valueAtt = doc.CreateAttribute(\"Type\");\nvalueAtt.InnerText = \"Text\";\nvalueNode.Attributes.Append(valueAtt);\n\n// Can set the text of the Node to anything.\nvalueNode.InnerText = \"Value Text\";\n\n// Or you can use\n//valueNode.InnerXml = \"<aValid>SomeStuff</aValid>\";\n\n// Create the document\nfieldNode.AppendChild(valueNode);\neqNode.AppendChild(fieldNode);\nwhereNode.AppendChild(eqNode);\n\ndoc.AppendChild(whereNode);\n\n// Or you can use XQuery to Find the node and then change it\n\n// Find the Where Node\nXmlNode foundWhereNode = doc.SelectSingleNode(\"Where/Eq/Field/Value\");\n\nif (foundWhereNode != null)\n{\n // Now you can set the Value\n foundWhereNode.InnerText = \"Some Value Text\";\n}\n" }, { "answer_id": 26202, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 1, "selected": false, "text": "XmlDocument doc = new XmlDocument();\ndoc.InnerXml = @\"<Where><Eq><Field Name=\"\"FieldName\"\"><Value Type=\"\"Text\"\">/Value></Field></Eq></Where>\";\nXmlNode valueNode = doc.SelectSingleNode(\"Where/Eq/Field/Value\");\nvalueNode.InnerText = @\"Text <>!$% value>\";\n" }, { "answer_id": 1466268, "author": "jedigo", "author_id": 94345, "author_profile": "https://Stackoverflow.com/users/94345", "pm_score": 1, "selected": false, "text": "System.Security.SecurityElement.Escape(\"<unescaped text>\");\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
17,106
<p>We are developing an application that involves a substantial amount of XML transformations. We do not have any proper input test data per se, only DTD or XSD files. We'd like to generate our test data ourselves from these files. Is there an easy/free way to do that?</p> <p><strong>Edit</strong></p> <p>There are apparently no free tools for this, and I agree that OxygenXML is one of the best tools for this.</p>
[ { "answer_id": 374256, "author": "falko", "author_id": 47010, "author_profile": "https://Stackoverflow.com/users/47010", "pm_score": 3, "selected": false, "text": "xmlgen.zip java -jar xmlgen.jar -help" }, { "answer_id": 6209865, "author": "Michal Rames", "author_id": 780439, "author_profile": "https://Stackoverflow.com/users/780439", "pm_score": 3, "selected": false, "text": "InputStream in = new FileInputStream(PATH_TO_XSD);\nDynamicJAXBContext jaxbContext = \n DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);\nDynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);\nDynamicEntity root = rootType.newDynamicEntity();\ntraverseProps(jaxbContext, root, rootType, 0);\n private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{\n if (t!=null) {\n logger.info(indent(level) + \"type [\" + t.getName() + \"] of class [\" + t.getClassName() + \"] has \" + t.getNumberOfProperties() + \" props\");\n for (String pName:t.getPropertiesNames()){\n Class<?> clazz = t.getPropertyType(pName);\n logger.info(indent(level) + \"prop [\" + pName + \"] in type: \" + clazz);\n //logger.info(\"prop [\" + pName + \"] in entity: \" + e.get(pName));\n\n if (clazz==null){\n // need to create an instance of object\n String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);\n logger.info(indent(level) + \"Creating new type instance for \" + pName + \" using following class name: \" + updatedClassName );\n DynamicType child = c.getDynamicType(\"generated.\" + updatedClassName);\n DynamicEntity childEntity = child.newDynamicEntity();\n e.set(pName, childEntity);\n traverseProps(c, childEntity, child, level+1);\n } else {\n // just set empty value\n e.set(pName, clazz.newInstance());\n }\n }\n } else {\n logger.warn(\"type is null\");\n }\n }\n Marshaller marshaller = jaxbContext.createMarshaller();\nmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\nmarshaller.marshal(root, System.out);\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
17,117
<p>Is Boost the only way for VS2005 users experience TR2? Also is there a idiot proof way of downloading only the TR2 related packages?</p> <p>I was looking at the boost installer provided by BoostPro Consulting. If I select the options for all the threading options with all the packages for MSVC8 it requires 1.1GB. While I am not short of space, it seems ridiculous that a <strong>library</strong> needs over a gigabyte of space and it takes BPC a long time to catch up with the current release.</p> <p>What packages do I need? I'm really only interested in those that comprise std::tr2 and can find that out by comparing those on offer to those in from the TR2 report and selecting those from the list but even then it isn't clear what is needed and the fact that it is a version behind annoys me. </p> <p>I know from previous encounters with Boost (1.33.1) that self compiling is a miserable experience: A lot of time wasted to get it started and then a hoard of errors passes across your screen faster than you can read, so what you are left with is an uneasy feeling that something is broken but you don't quite know what. </p> <p>I've never had these problems with any Apache library but that is another rant...</p>
[ { "answer_id": 38226, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "bjam --help bjam --build-type=complete --toolset=msvc --build-dir=c:\\boost\\build install\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
17,125
<p>I know what <code>yield</code> does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?</p> <p>(Ideally some problem that cannot be solved some other way)</p>
[ { "answer_id": 17133, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 3, "selected": false, "text": "public override IEnumerator<T> GetEnumerator()\n{\n // goes through the collection and only returns the ones that are visible for the current user\n // this is done at this level instead of the display level so that ideas do not bleed through\n // on services\n foreach (T idea in InternalCollection)\n if (idea.IsViewingAuthorized)\n yield return idea;\n}\n" }, { "answer_id": 17200, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "public delegate T SomeDelegate(K obj);\n\npublic IEnumerable<T> DoActionOnList(IEnumerable<K> list, SomeDelegate action)\n{\n foreach (var i in list)\n yield return action(i);\n}\n" }, { "answer_id": 1692705, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 5, "selected": true, "text": "Ideally some problem that cannot be solved some other way\n" }, { "answer_id": 20363364, "author": "Terry Lewis", "author_id": 1013549, "author_profile": "https://Stackoverflow.com/users/1013549", "pm_score": 0, "selected": false, "text": "yield return void Main()\n{\n var StartDate = DateTime.Parse(\"01/01/2013\");\n var EndDate = DateTime.Parse(\"06/30/2013\");\n foreach (var d in GetPayrollDates(StartDate, EndDate)) {\n Console.WriteLine(d);\n }\n}\n\n// Calculate payroll dates in the given range.\n// Assumes the first date given is a payroll date.\nIEnumerable<DateTime> GetPayrollDates(DateTime startDate, DateTime endDate, int daysInPeriod = 14) {\n var thisDate = startDate;\n while (thisDate < endDate) {\n yield return thisDate;\n thisDate = thisDate.AddDays(daysInPeriod);\n }\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
17,140
<p>How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.</p>
[ { "answer_id": 17148, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "#include <stdlib.h>\n\nint main()\n{\n system(\"echo HAI\");\n\n return 0;\n}\n" }, { "answer_id": 17150, "author": "Rippy", "author_id": 1791, "author_profile": "https://Stackoverflow.com/users/1791", "pm_score": 2, "selected": false, "text": "int system(const char *string);\n" }, { "answer_id": 17226, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 2, "selected": false, "text": " QString program = \"./yourspawnedprogram\";\n QProcess * spawnedProcess = new QProcess(parent);\n spawnedProcess->start(program);\n // or spawnedProcess->startDetached(program);\n" }, { "answer_id": 17311, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n int entry = 1;\n char line[200];\n FILE* output = popen(\"/usr/bin/ls -1 /usr/man\", \"r\");\n while ( fgets(line, 199, output) )\n {\n printf(\"%5d: %s\", entry++, line);\n }\n}\n 1: cat1\n2: cat1b\n3: cat1c\n4: cat1f\n5: cat1m\n6: cat1s\n...\n" }, { "answer_id": 20752, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 5, "selected": false, "text": "fork() #include <unistd.h>\n#include <stdio.h>\n\nint main()\n{\n printf( \"hi 2 u\\n\" );\n int mypid = fork();\n\n if( 0 == mypid )\n printf( \"lol child\\n\" );\n else\n printf( \"lol parent\\n\" );\n\n return( 0 );\n}\n fork() execve() fork(). execve() execve() fork() execve() waitpid() fork() execve() waitpid()" }, { "answer_id": 389352, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "fork execvp system()" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
17,170
<p>I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?</p>
[ { "answer_id": 17177, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "Person Group Group Group IList<Person> List public class Group {\n private IList<Person> people;\n\n public Group() {\n this.people = new List<Person>();\n }\n}\n IList IEnumerable" }, { "answer_id": 17179, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 1, "selected": false, "text": "void ProcessArrayData(IList almostAnyTypeOfArray)\n{\n // Do some stuff with the IList array\n}\n" }, { "answer_id": 85441, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 6, "selected": false, "text": "public interface IMyApi\n{\n IList<int> GetReadOnlyValues();\n}\n\npublic class MyApiImplementation : IMyApi\n{\n public IList<int> GetReadOnlyValues()\n {\n List<int> myList = new List<int>();\n ... populate list\n return myList.AsReadOnly();\n }\n}\npublic class MyMockApiImplementationForUnitTests : IMyApi\n{\n public IList<int> GetReadOnlyValues()\n {\n IList<int> testValues = new int[] { 1, 2, 3 };\n return testValues;\n }\n}\n" }, { "answer_id": 85491, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 2, "selected": false, "text": "ArrayList.Adapter(list).Sort()\n" }, { "answer_id": 17761596, "author": "rajesh", "author_id": 2602088, "author_profile": "https://Stackoverflow.com/users/2602088", "pm_score": 5, "selected": false, "text": "IEnumerable IList IEnumerable IList IEnumerable IList List IList" }, { "answer_id": 18306587, "author": "Javid", "author_id": 1701894, "author_profile": "https://Stackoverflow.com/users/1701894", "pm_score": 1, "selected": false, "text": "List List IList List BookList IList IList List IList<string> list1 = new IList<string>(); // this is wrong, and won't compile\n\nIList<string> list2 = new List<string>(); // this will compile\nList<string> list3 = new List<string>(); // this will compile\n" }, { "answer_id": 19684049, "author": "Matthew Watson", "author_id": 106159, "author_profile": "https://Stackoverflow.com/users/106159", "pm_score": 5, "selected": false, "text": "IList<T> IList.Add() Unhandled Exception: System.NotSupportedException: Collection was of a fixed size. private void test(IList<int> list)\n{\n list.Add(1);\n}\n int[] array = new int[0];\ntest(array);\n IList<T> IList<T>.Add() List<T> IList<T>" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560/" ]
17,172
<p>I've tried to do this several times with no luck. After reading <a href="https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477">this post</a>, it made me interested in doing this again. So can anyone tell me why the following doesn't work?</p> <pre><code>&lt;?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user == ($editor | $admin) ) { echo "Test"; } ?&gt; </code></pre>
[ { "answer_id": 17173, "author": "Espen Herseth Halvorsen", "author_id": 1542, "author_profile": "https://Stackoverflow.com/users/1542", "pm_score": 2, "selected": false, "text": "<?php\n\n $guest = 1;\n $editor = 2;\n $admin = 4;\n\n $user = $editor;\n\n if( ($user == $editor) || ($user == $admin) ) {\n echo \"Test\"; \n }\n\n?>\n" }, { "answer_id": 17178, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": true, "text": "<?php\n\n $guest = 1;\n $editor = 2;\n $admin = 4;\n\n $user = $editor;\n\n if( $user & ($editor | $admin) ) {\n echo \"Test\"; \n }\n\n?>\n" }, { "answer_id": 17196, "author": "conmulligan", "author_id": 1467, "author_profile": "https://Stackoverflow.com/users/1467", "pm_score": 1, "selected": false, "text": "$guest = 1;\n$editor = 2;\n$admin = 4;\n\n$user = $editor;\n\nif (user == $editor || $user == $admin) {\n echo \"Test\";\n}\n" }, { "answer_id": 17214, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": " ($editor | $admin)\n if ($user & $database_row['permissions']) {\n // display content\n } else {\n // display permissions error\n }\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
17,175
<p>I'll take away the obvious one here: mic and webcam support. Other than that, if you ran the Silverlight team, what would your highest priority be for Silverlight v.Next?</p> <p>Disclaimer: If we get some good responses, I'll pass them along to folks I know on the Silverlight team.</p> <p><strong>UPDATE</strong>: The best place to report Silverlight feature requests now is the UserVoice site: <a href="http://silverlight.uservoice.com/pages/4325-feature-suggestions" rel="nofollow noreferrer">http://silverlight.uservoice.com/</a></p>
[ { "answer_id": 33962, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "*" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
17,181
<p>In my most C++ project I heavily used ASSERTION statement as following:</p> <pre><code>int doWonderfulThings(const int* fantasticData) { ASSERT(fantasticData); if(!fantasticData) return -1; // ,,, return WOW_VALUE; } </code></pre> <p>But TDD community seems like to enjoy doing something like this:</p> <pre><code>int doMoreWonderfulThings(const int* fantasticData) { if(!fantasticData) return ERROR_VALUE; // ... return AHA_VALUE; } TEST(TDD_Enjoy) { ASSERT_EQ(ERROR_VALUE, doMoreWonderfulThings(0L)); ASSERT_EQ(AHA_VALUE, doMoreWonderfulThings("Foo")); } </code></pre> <p>Just with my experiences first approaches let me remove so many subtle bugs. But TDD approaches are very smart idea to handle legacy codes.</p> <p>"Google" - they compare "FIRST METHOD" to "Walk the shore with life-vest, swim ocean without any safe guard".</p> <p>Which one is better? Which one makes software robust?</p>
[ { "answer_id": 17229, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 2, "selected": false, "text": "int doWonderfulThings(const int* fantasticData)\n{\n ASSERT(fantasticData);\n ASSERTNOTEQUAL(0, fantasticData)\n\n return WOW_VALUE / fantasticData;\n}\n int doMoreWonderfulThings(const int fantasticNumber)\n{\n int count = 100;\n for(int i = 0; i < fantasticNumber; ++i) {\n count += 10 * fantasticNumber;\n }\n return count;\n}\n\nTEST(TDD_Enjoy)\n{\n // Test lower edge\n ASSERT_EQ(0, doMoreWonderfulThings(-1));\n ASSERT_EQ(0, doMoreWonderfulThings(0));\n ASSERT_EQ(110, doMoreWonderfulThings(1));\n\n //Test some random values\n ASSERT_EQ(350, doMoreWonderfulThings(5));\n ASSERT_EQ(2350, doMoreWonderfulThings(15));\n ASSERT_EQ(225100, doMoreWonderfulThings(150));\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
17,194
<p>I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:</p> <pre><code>Category | Revenue | Yearh | Month Bikes 10 000 2008 1 Bikes 12 000 2008 2 Bikes 12 000 2008 3 Bikes 15 000 2008 1 Bikes 11 000 2007 2 Bikes 11 500 2007 3 Bikes 15 400 2007 4 </code></pre> <p><br/> ... And so forth</p> <p>The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this:</p> <pre><code>Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 </code></pre> <p><br/> The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up.</p> <p>Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.</p> <p>The query I got looks something like this:</p> <pre><code>SELECT SP1.Program, SP1.Year, SP1.Month, SP1.TotalRevenue, IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue FROM PVMonthlyStatusReport AS SP1 LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON SP1.Program = SP2.Program AND SP2.Year = SP1.Year - 1 AND SP1.Month = SP2.Month WHERE SP1.Program = 'Bikes' AND SP1.Category = @Category AND (SP1.Year &gt;= @FinancialYear AND SP1.Year &lt;= @FinancialYear + 1) AND ((SP1.Year = @FinancialYear AND SP1.Month &gt; 6) OR (SP1.Year = @FinancialYear + 1 AND SP1.Month &lt;= 6)) ORDER BY SP1.Year, SP1.Month </code></pre> <p>The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007.</p> <p>This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated!</p> <p>Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.</p>
[ { "answer_id": 17277, "author": "Jonas Follesø", "author_id": 1199387, "author_profile": "https://Stackoverflow.com/users/1199387", "pm_score": 1, "selected": false, "text": "SELECT \n SP1.Program,\n SP1.Year,\n SP1.Month,\n SP1.TotalRevenue AS ThisYearRevenue,\n SP2.TotalRevenue AS LastYearRevenue\nFROM GetFinancialYear(@Category, 'First Look', 2008) AS SP1 \n RIGHT JOIN GetFinancialYear(@Category, 'First Look', 2007) AS SP2 ON \n SP1.Program = SP2.Program AND \n SP1.Month = SP2.Month\n" }, { "answer_id": 17290, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 4, "selected": true, "text": "select\n Category\n ,month\n ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year\n ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year\n\nfrom\n sales\n\nwhere\n year in (2008,2007)\n\ngroup by\n Category\n ,month\n Category | Month | Rev. This Year | Rev. Last Year\nBikes 1 10 000 0\nBikes 2 12 000 11 000\nBikes 3 12 000 11 500\nBikes 4 0 15 400\n select\n fill.Category\n ,fill.month\n ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year\n ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year\n\nfrom\n sales\n Right join (select distinct --try out left, right and cross joins to test results.\n product\n ,year\n ,month\n from\n sales --this ideally would be from a products table\n cross join tm\n where\n year in (2008,2007)) fill\n\n\nwhere\n fill.year in (2008,2007)\n\ngroup by\n fill.Category\n ,fill.month\n Category | Month | Rev. This Year | Rev. Last Year\nBikes 1 10 000 0\nBikes 2 12 000 11 000\nBikes 3 12 000 11 500\nBikes 4 0 15 400\nBikes 5 0 0\nBikes 6 0 0\nBikes 7 0 0\nBikes 8 0 0\n" }, { "answer_id": 25600, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "SELECT \n Program,\n Month,\n ThisYearTotalRevenue,\n PriorYearTotalRevenue\nFROM (\n SELECT \n ISNULL(ThisYear.Program, PriorYear.Program) as Program,\n ISNULL(ThisYear.Month, PriorYear.Month),\n ISNULL(ThisYear.TotalRevenue, 0) as ThisYearTotalRevenue,\n ISNULL(PriorYear.TotalRevenue, 0) as PriorYearTotalRevenue\n FROM (\n SELECT Program, Month, SUM(TotalRevenue) as TotalRevenue \n FROM PVMonthlyStatusReport \n WHERE Year = @FinancialYear \n GROUP BY Program, Month\n ) as ThisYear \n FULL OUTER JOIN (\n SELECT Program, Month, SUM(TotalRevenue) as TotalRevenue \n FROM PVMonthlyStatusReport \n WHERE Year = (@FinancialYear - 1) \n GROUP BY Program, Month\n ) as PriorYear ON\n ThisYear.Program = PriorYear.Program\n AND ThisYear.Month = PriorYear.Month\n) as Revenue\nWHERE \n Program = 'Bikes'\nORDER BY \n Month\n" }, { "answer_id": 44827376, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SET NOCOUNT ON\nIF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL\nDROP TABLE #TEMP\n\n;With cte(Category , Revenue , Yearh , [Month])\nAS\n(\nSELECT 'Bikes', 10000, 2008,1 UNION ALL\nSELECT 'Bikes', 12000, 2008,2 UNION ALL\nSELECT 'Bikes', 12000, 2008,3 UNION ALL\nSELECT 'Bikes', 15000, 2008,1 UNION ALL\nSELECT 'Bikes', 11000, 2007,2 UNION ALL\nSELECT 'Bikes', 11500, 2007,3 UNION ALL\nSELECT 'Bikes', 15400, 2007,4\n)\nSELECT * INTO #Temp FROM cte\n\nDeclare @Column nvarchar(max),\n @Column2 nvarchar(max),\n @Sql nvarchar(max)\n\n\nSELECT @Column=STUFF((SELECT DISTINCT ','+ 'ISNULL('+QUOTENAME(CAST(Yearh AS VArchar(10)))+','+'''0'''+')'+ 'AS '+ QUOTENAME(CAST(Yearh AS VArchar(10)))\nFROM #Temp order by 1 desc FOR XML PATH ('')),1,1,'')\n\nSELECT @Column2=STUFF((SELECT DISTINCT ','+ QUOTENAME(CAST(Yearh AS VArchar(10)))\nFROM #Temp FOR XML PATH ('')),1,1,'')\n\nSET @Sql= N'SELECT Category,[Month],'+ @Column +'FRom #Temp\n PIVOT\n (MIN(Revenue) FOR yearh IN ('+@Column2+')\n ) AS Pvt\n\n '\nEXEC(@Sql)\nPrint @Sql\n Category Month 2008 2007\n----------------------------------\nBikes 1 10000 0\nBikes 2 12000 11000\nBikes 3 12000 11500\nBikes 4 0 15400\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199387/" ]
17,225
<p>In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it. </p> <p>Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the <code>.bat</code> equivalent of "@echo on".</p>
[ { "answer_id": 17245, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 3, "selected": false, "text": "open(LS,\"|ls\");\nprint LS;\n" }, { "answer_id": 17293, "author": "Daniel Fone", "author_id": 1848, "author_profile": "https://Stackoverflow.com/users/1848", "pm_score": 4, "selected": true, "text": "[daniel@tux /]$ perl -e '$ls = system(\"ls\"); print \"Result: $ls\\n\"'\nbin dev home lost+found misc net proc sbin srv System tools var\nboot etc lib media mnt opt root selinux sys tmp usr\nResult: 0\n [daniel@tux /]$ perl -e '$ls = `ls`; print \"Result: $ls\\n\"'\nResult: bin\nboot\ndev\netc\nhome\nlib\n system() sub execute {\n my $cmd = shift;\n print \"$cmd\\n\";\n system($cmd);\n}\n\nmy $cmd = $ARGV[0];\nexecute($cmd);\n" }, { "answer_id": 17304, "author": "Rudd Zwolinski", "author_id": 219, "author_profile": "https://Stackoverflow.com/users/219", "pm_score": 4, "selected": false, "text": "sub execute {\n my $cmd = shift;\n print \"$cmd\\n\";\n system($cmd);\n}\n\nmy $cmd = $ARGV[0];\nexecute($cmd);\n pbook:~/foo rudd$ perl foo.pl ls\nls\nfile1 file2 foo.pl\n" }, { "answer_id": 17331, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "if ($DEBUG) {\n *{\"CORE::GLOBAL::system\"} = \\&{\"main::execute\"};\n}\n # importing into either the calling or global namespace _must_ be\n # done from import(). Doing it elsewhere will not have desired results.\n delete($opts{handle_system});\n if ($do_system) {\n if ($do_system eq 'local') {\n *{\"$callpkg\\::system\"} = \\&{\"$_package\\::system\"};\n } else {\n *{\"CORE::GLOBAL::system\"} = \\&{\"$_package\\::system\"};\n }\n }\n" }, { "answer_id": 17468, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "tee open(F, \"ls | tee /dev/tty |\");\nwhile (<F>) {\n print length($_), \"\\n\";\n}\nclose(F);\n tee /dev/tty" }, { "answer_id": 18328, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 3, "selected": false, "text": "sub execute {\n my $cmd = shift;\n print \"$cmd\\n\";\n my $ret = `$cmd`;\n print $ret;\n return $ret;\n}\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
17,228
<p>I develop C++ applications in a Linux environment. The tools I use every day include Eclipse with the CDT plugin, gdb and valgrind.<br> What tools do other people use? Is there anything out there for Linux that rivals the slickness of Microsoft Visual Studio?</p>
[ { "answer_id": 563490, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 6, "selected": false, "text": "strace time(0) poll() read() read() objdump -d __builtin_prefetch" }, { "answer_id": 1955392, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "aptitude install build-essential\n" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1449/" ]
17,231
<p>I was looking at <a href="http://tldp.org/LDP/abs/html/why-shell.html" rel="nofollow noreferrer">http://tldp.org/LDP/abs/html/why-shell.html</a> and was struck by:</p> <blockquote> <p>When not to use shell scripts</p> <p>...</p> <ul> <li>Mission-critical applications upon which you are betting the future of the company</li> </ul> </blockquote> <p>Why not?</p>
[ { "answer_id": 92305, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "critical-business-logic.sh" } ]
2008/08/19
[ "https://Stackoverflow.com/questions/17231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
17,250
<p>I am creating an ZIP file with <code>ZipFile</code> in Python 2.5, it works OK so far:</p> <pre><code>import zipfile, os locfile = &quot;test.txt&quot; loczip = os.path.splitext (locfile)[0] + &quot;.zip&quot; zip = zipfile.ZipFile (loczip, &quot;w&quot;) zip.write (locfile) zip.close() </code></pre> <p>But I couldn't find how to encrypt the files in the ZIP file. I could use system and call <code>PKZIP -s</code>, but I suppose there must be a more &quot;Pythonic&quot; way. I'm looking for an open source solution.</p>
[ { "answer_id": 17287, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": -1, "selected": false, "text": "import chilkat\n\n# Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip\nzip = chilkat.CkZip()\nzip.UnlockComponent(\"anything for 30-day trial\")\n\nzip.NewZip(\"strongEncrypted.zip\")\n\n# Set the Encryption property = 4, which indicates WinZip compatible AES encryption.\nzip.put_Encryption(4)\n# The key length can be 128, 192, or 256.\nzip.put_EncryptKeyLength(128)\nzip.SetPassword(\"secret\")\n\nzip.AppendFiles(\"exampleData/*\",True)\nzip.WriteZip()\n" }, { "answer_id": 16050005, "author": "Shin Aoyama", "author_id": 2288743, "author_profile": "https://Stackoverflow.com/users/2288743", "pm_score": 5, "selected": false, "text": "import pyminizip\n\ncompression_level = 5 # 1-9\npyminizip.compress(\"src.txt\", \"dst.zip\", \"password\", compression_level)\n" }, { "answer_id": 27443681, "author": "tripleee", "author_id": 874188, "author_profile": "https://Stackoverflow.com/users/874188", "pm_score": 3, "selected": false, "text": "7z zip 'myarchive.zip' 7-Zip rc = subprocess.call(['7z', 'a', '-mem=AES256', '-pP4$$W0rd', '-y', 'myarchive.zip'] + \n ['first_file.txt', 'second.file'])\n $ sudo apt-get install p7zip-full\n $ unzip myarchive.zip\n P4$$W0rd >>> zipfile.ZipFile('myarchive.zip').extractall(pwd='P4$$W0rd')\n" }, { "answer_id": 40164739, "author": "zqcolor", "author_id": 5087657, "author_profile": "https://Stackoverflow.com/users/5087657", "pm_score": 0, "selected": false, "text": "rc = subprocess.call(['7z', 'a', output_filename + '.zip', '-mx9', '-pSecret^)'] + [src_folder + '/'])\n -mx9 -pSecret^) Secret^) ^ ) ^ ^ -mhe" }, { "answer_id": 57405348, "author": "Smack Alpha", "author_id": 11090395, "author_profile": "https://Stackoverflow.com/users/11090395", "pm_score": 2, "selected": false, "text": "pyminizip import pyminizip\ncompression_level = 5 # 1-9\npyminizip.compress(\"src.txt\",'src', \"dst.zip\", \"password\", compression_level)\n from zipfile import ZipFile\n\nwith ZipFile('/home/paulsteven/dst.zip') as zf:\n zf.extractall(pwd=b'password')\n" }, { "answer_id": 66158678, "author": "edif", "author_id": 4779475, "author_profile": "https://Stackoverflow.com/users/4779475", "pm_score": 3, "selected": false, "text": "subprocess" }, { "answer_id": 70389456, "author": "Try2Code", "author_id": 17393518, "author_profile": "https://Stackoverflow.com/users/17393518", "pm_score": 1, "selected": false, "text": "pip install pyzipper import pyzipper\n\ndef encrypt_():\n\n secret_password = b'your password'\n\n with pyzipper.AESZipFile('new_test.zip',\n 'w',\n compression=pyzipper.ZIP_LZMA,\n encryption=pyzipper.WZ_AES) as zf:\n zf.setpassword(secret_password)\n zf.writestr('test.txt', \"What ever you do, don't tell anyone!\")\n\n with pyzipper.AESZipFile('new_test.zip') as zf:\n zf.setpassword(secret_password)\n my_secrets = zf.read('test.txt')\n def encrypt_():\n \n secret_password = b'your password'\n\n with pyzipper.AESZipFile('new_test.zip',\n 'w',\n compression=pyzipper.ZIP_LZMA) as zf:\n zf.setpassword(secret_password)\n zf.setencryption(pyzipper.WZ_AES, nbits=128)\n zf.writestr('test.txt', \"What ever you do, don't tell anyone!\")\n\n with pyzipper.AESZipFile('new_test.zip') as zf:\n zf.setpassword(secret_password)\n my_secrets = zf.read('test.txt')\n" }, { "answer_id": 72744952, "author": "Alex Deft", "author_id": 10870968, "author_profile": "https://Stackoverflow.com/users/10870968", "pm_score": 0, "selected": false, "text": "from crocodile.toolbox import Path\n\nfile = Path(r'my_string_path')\nresult_file = file.zip(pwd=\"lol\", use_7z=True)\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
17,274
<p>Although I've done programming, I'm not a programmer. I've recently agreed to coordinate getting a Website up for a club. The resources are--me, who has done Web content maintenance (putting content into HTML and ColdFusion templates via a gatekeeper to the site itself; doing simple HTML and XML coding); a serious Web developer who does database programming, ColdFusion, etc., and talks way over the heads of the rest of us; two designers who use Dreamweaver; the guy who created the original (and now badly broken) site in Front Page and wants to use Expression Web; and assorted other club members who are even less technically inclined.</p> <p>What we need up first is some text and graphics (a gorgeous design has been created in Dreamweaver), some links (including to existing PDF newsletters for download), and maybe hooking up an existing Blogspot blog. Later (or earlier if it's not hard), we may add mouseover menus to the links, a gallery, a calendar, a few Mapquest hotlinks, and so on.</p> <p>My question--First, is there any real problem with sticking with HTML and jpegs for the initial site? Second, for the "later" part of the site development, what's the simplest we can go with? Third, are there costs in doing this the simple way that will make us regret it down the road? Also, is there a good site/resource where I can learn more about this from a newbie perspective? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 18385, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 1, "selected": false, "text": "<!--#include virtual=\"navigation.html\" -->\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1110/" ]
17,299
<p>I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:</p> <pre><code>void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for(i = 1; (i &lt;= ArrayLength) &amp;&amp; flag; i++) { flag = 0; for (j = 0; j &lt; (ArrayLength -1); j++) { if (*pArray[j+1] &gt; *pArray[j]) // ascending order simply changes to &lt; { temp = &amp;pArray[j]; // swap elements pArray[j] = &amp;pArray[j+1]; pArray[j+1] = &amp;temp; flag = 1; // indicates that a swap occurred. } } } } </code></pre>
[ { "answer_id": 17312, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 4, "selected": true, "text": "void SortArray( int ** pArray, int ArrayLength )\n{\n int i, j, flag = 1; // set flag to 1 to begin initial pass\n int * temp; // holding variable orig with no *\n for(i = ArrayLength - 1; i > 0 && flag; i--)\n {\n flag = 0;\n for (j = 0; j < i; j++)\n {\n if (*pArray[j] > *pArray[j+1]) // ascending order simply changes to <\n { \n temp = pArray[j]; // swap elements\n pArray[j] = pArray[j+1];\n pArray[j+1] = temp;\n flag = 1; // indicates that a swap occurred.\n }\n }\n }\n}\n" }, { "answer_id": 17335, "author": "Adam", "author_id": 1366, "author_profile": "https://Stackoverflow.com/users/1366", "pm_score": 2, "selected": false, "text": "std::swap() swap( obj1, obj2 );\n std::swap( obj1, obj2 );\n using namespace std;\n using std::swap;\n" }, { "answer_id": 18042, "author": "Brian Ensink", "author_id": 1254, "author_profile": "https://Stackoverflow.com/users/1254", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n vector<int>; vec;\n vec.push_back(7);\n vec.push_back(5);\n vec.push_back(13);\n sort(vec.begin(), vec.end());\n\n for (vector<int>::size_type i = 0; i < vec.size(); ++i)\n {\n cout << vec[i] << endl;\n }\n}\n" }, { "answer_id": 112530, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nvoid printArray(const std::vector<int *> & p_aInt)\n{\n for(std::vector<int *>::size_type i = 0, iMax = p_aInt.size(); i < iMax; ++i)\n {\n std::cout << \"i[\" << static_cast<int>(i) << \"] = \" << reinterpret_cast<unsigned int>(p_aInt[i]) << std::endl ;\n }\n\n std::cout << std::endl ;\n}\n\n\nint main(int argc, char **argv)\n{\n int a = 1 ;\n int b = 2 ;\n int c = 3 ;\n int d = 4 ;\n int e = 5 ;\n\n std::vector<int *> aInt ;\n\n // We fill the vector with variables in an unordered way\n aInt.push_back(&c) ;\n aInt.push_back(&b) ;\n aInt.push_back(&e) ;\n aInt.push_back(&d) ;\n aInt.push_back(&a) ;\n\n printArray(aInt) ; // We see the addresses are NOT ordered\n std::sort(aInt.begin(), aInt.end()) ; // DO THE SORTING\n printArray(aInt) ; // We see the addresses are ORDERED\n\n return EXIT_SUCCESS;\n}\n i[0] = 3216087168\ni[1] = 3216087172\ni[2] = 3216087160\ni[3] = 3216087164\ni[4] = 3216087176\n\ni[0] = 3216087160\ni[1] = 3216087164\ni[2] = 3216087168\ni[3] = 3216087172\ni[4] = 3216087176\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ]
17,333
<p>What would be the most efficient way to compare two <code>double</code> or two <code>float</code> values?</p> <p>Simply doing this is not correct:</p> <pre><code>bool CompareDoubles1 (double A, double B) { return A == B; } </code></pre> <p>But something like:</p> <pre><code>bool CompareDoubles2 (double A, double B) { diff = A - B; return (diff &lt; EPSILON) &amp;&amp; (-diff &lt; EPSILON); } </code></pre> <p>Seems to waste processing.</p> <p>Does anyone know a smarter float comparer?</p>
[ { "answer_id": 17341, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 8, "selected": false, "text": "bool AreSame(double a, double b)\n{\n return fabs(a - b) < EPSILON;\n}\n" }, { "answer_id": 17412, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 4, "selected": false, "text": "return (diff < EPSILON) && (-diff > EPSILON);\n return (diff < EPSILON) && (diff > -EPSILON);\n" }, { "answer_id": 17467, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 6, "selected": false, "text": "// Usable AlmostEqual function \nbool AlmostEqual2sComplement(float A, float B, int maxUlps) \n{ \n // Make sure maxUlps is non-negative and small enough that the \n // default NAN won't compare as equal to anything. \n assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024); \n int aInt = *(int*)&A; \n // Make aInt lexicographically ordered as a twos-complement int \n if (aInt < 0) \n aInt = 0x80000000 - aInt; \n // Make bInt lexicographically ordered as a twos-complement int \n int bInt = *(int*)&B; \n if (bInt < 0) \n bInt = 0x80000000 - bInt; \n int intDiff = abs(aInt - bInt); \n if (intDiff <= maxUlps) \n return true; \n return false; \n}\n" }, { "answer_id": 18289, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": -1, "selected": false, "text": "diff= a - b; return fabs(diff)<EPSILON;\n fabs" }, { "answer_id": 37589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "return a==b;\n #define VERYSMALL (1.0E-150)\n#define EPSILON (1.0E-8)\nbool AreSame(double a, double b)\n{\n double absDiff = fabs(a - b);\n if (absDiff < VERYSMALL)\n {\n return true;\n }\n\n double maxAbs = max(fabs(a) - fabs(b));\n return (absDiff/maxAbs) < EPSILON;\n}\n fabs(a-b) < EPSILON" }, { "answer_id": 37686, "author": "Chris de Vries", "author_id": 3836, "author_profile": "https://Stackoverflow.com/users/3836", "pm_score": 5, "selected": false, "text": "#include <limits>\nstd::numeric_limits<double>::epsilon()\n #include <cmath>\n#include <limits>\n\nbool AreSame(double a, double b) {\n return std::fabs(a - b) < std::numeric_limits<double>::epsilon();\n}\n" }, { "answer_id": 77735, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 9, "selected": false, "text": "a==b |a-b|<epsilon a==b b==c a==c a==b 1000a!=1000b AlmostEqual2sComplement == a b std::numeric_limits<double>::epsilon() 1.0 int doubles 4.0/2.0 1.0+1.0 4.0/3.0" }, { "answer_id": 253874, "author": "mch", "author_id": 32515, "author_profile": "https://Stackoverflow.com/users/32515", "pm_score": 7, "selected": false, "text": "bool approximatelyEqual(float a, float b, float epsilon)\n{\n return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool essentiallyEqual(float a, float b, float epsilon)\n{\n return fabs(a - b) <= ( (fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyGreaterThan(float a, float b, float epsilon)\n{\n return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyLessThan(float a, float b, float epsilon)\n{\n return (b - a) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n" }, { "answer_id": 3423299, "author": "skrebbel", "author_id": 103395, "author_profile": "https://Stackoverflow.com/users/103395", "pm_score": 7, "selected": false, "text": "double left = // something\ndouble right = // something\nconst FloatingPoint<double> lhs(left), rhs(right);\n\nif (lhs.AlmostEquals(rhs)) {\n //they're equal!\n}\n // Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Authors: [email protected] (Zhanyong Wan), [email protected] (Sean Mcafee)\n//\n// The Google C++ Testing Framework (Google Test)\n\n\n// This template class serves as a compile-time function from size to\n// type. It maps a size in bytes to a primitive type with that\n// size. e.g.\n//\n// TypeWithSize<4>::UInt\n//\n// is typedef-ed to be unsigned int (unsigned integer made up of 4\n// bytes).\n//\n// Such functionality should belong to STL, but I cannot find it\n// there.\n//\n// Google Test uses this class in the implementation of floating-point\n// comparison.\n//\n// For now it only handles UInt (unsigned int) as that's all Google Test\n// needs. Other types can be easily added in the future if need\n// arises.\ntemplate <size_t size>\nclass TypeWithSize {\n public:\n // This prevents the user from using TypeWithSize<N> with incorrect\n // values of N.\n typedef void UInt;\n};\n\n// The specialization for size 4.\ntemplate <>\nclass TypeWithSize<4> {\n public:\n // unsigned int has size 4 in both gcc and MSVC.\n //\n // As base/basictypes.h doesn't compile on Windows, we cannot use\n // uint32, uint64, and etc here.\n typedef int Int;\n typedef unsigned int UInt;\n};\n\n// The specialization for size 8.\ntemplate <>\nclass TypeWithSize<8> {\n public:\n#if GTEST_OS_WINDOWS\n typedef __int64 Int;\n typedef unsigned __int64 UInt;\n#else\n typedef long long Int; // NOLINT\n typedef unsigned long long UInt; // NOLINT\n#endif // GTEST_OS_WINDOWS\n};\n\n\n// This template class represents an IEEE floating-point number\n// (either single-precision or double-precision, depending on the\n// template parameters).\n//\n// The purpose of this class is to do more sophisticated number\n// comparison. (Due to round-off error, etc, it's very unlikely that\n// two floating-points will be equal exactly. Hence a naive\n// comparison by the == operation often doesn't work.)\n//\n// Format of IEEE floating-point:\n//\n// The most-significant bit being the leftmost, an IEEE\n// floating-point looks like\n//\n// sign_bit exponent_bits fraction_bits\n//\n// Here, sign_bit is a single bit that designates the sign of the\n// number.\n//\n// For float, there are 8 exponent bits and 23 fraction bits.\n//\n// For double, there are 11 exponent bits and 52 fraction bits.\n//\n// More details can be found at\n// http://en.wikipedia.org/wiki/IEEE_floating-point_standard.\n//\n// Template parameter:\n//\n// RawType: the raw floating-point type (either float or double)\ntemplate <typename RawType>\nclass FloatingPoint {\n public:\n // Defines the unsigned integer type that has the same size as the\n // floating point number.\n typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;\n\n // Constants.\n\n // # of bits in a number.\n static const size_t kBitCount = 8*sizeof(RawType);\n\n // # of fraction bits in a number.\n static const size_t kFractionBitCount =\n std::numeric_limits<RawType>::digits - 1;\n\n // # of exponent bits in a number.\n static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;\n\n // The mask for the sign bit.\n static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);\n\n // The mask for the fraction bits.\n static const Bits kFractionBitMask =\n ~static_cast<Bits>(0) >> (kExponentBitCount + 1);\n\n // The mask for the exponent bits.\n static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);\n\n // How many ULP's (Units in the Last Place) we want to tolerate when\n // comparing two numbers. The larger the value, the more error we\n // allow. A 0 value means that two numbers must be exactly the same\n // to be considered equal.\n //\n // The maximum error of a single floating-point operation is 0.5\n // units in the last place. On Intel CPU's, all floating-point\n // calculations are done with 80-bit precision, while double has 64\n // bits. Therefore, 4 should be enough for ordinary use.\n //\n // See the following article for more details on ULP:\n // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.\n static const size_t kMaxUlps = 4;\n\n // Constructs a FloatingPoint from a raw floating-point number.\n //\n // On an Intel CPU, passing a non-normalized NAN (Not a Number)\n // around may change its bits, although the new value is guaranteed\n // to be also a NAN. Therefore, don't expect this constructor to\n // preserve the bits in x when x is a NAN.\n explicit FloatingPoint(const RawType& x) { u_.value_ = x; }\n\n // Static methods\n\n // Reinterprets a bit pattern as a floating-point number.\n //\n // This function is needed to test the AlmostEquals() method.\n static RawType ReinterpretBits(const Bits bits) {\n FloatingPoint fp(0);\n fp.u_.bits_ = bits;\n return fp.u_.value_;\n }\n\n // Returns the floating-point number that represent positive infinity.\n static RawType Infinity() {\n return ReinterpretBits(kExponentBitMask);\n }\n\n // Non-static methods\n\n // Returns the bits that represents this number.\n const Bits &bits() const { return u_.bits_; }\n\n // Returns the exponent bits of this number.\n Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }\n\n // Returns the fraction bits of this number.\n Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }\n\n // Returns the sign bit of this number.\n Bits sign_bit() const { return kSignBitMask & u_.bits_; }\n\n // Returns true iff this is NAN (not a number).\n bool is_nan() const {\n // It's a NAN if the exponent bits are all ones and the fraction\n // bits are not entirely zeros.\n return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);\n }\n\n // Returns true iff this number is at most kMaxUlps ULP's away from\n // rhs. In particular, this function:\n //\n // - returns false if either number is (or both are) NAN.\n // - treats really large numbers as almost equal to infinity.\n // - thinks +0.0 and -0.0 are 0 DLP's apart.\n bool AlmostEquals(const FloatingPoint& rhs) const {\n // The IEEE standard says that any comparison operation involving\n // a NAN must return false.\n if (is_nan() || rhs.is_nan()) return false;\n\n return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)\n <= kMaxUlps;\n }\n\n private:\n // The data type used to store the actual floating-point number.\n union FloatingPointUnion {\n RawType value_; // The raw floating-point number.\n Bits bits_; // The bits that represent the number.\n };\n\n // Converts an integer from the sign-and-magnitude representation to\n // the biased representation. More precisely, let N be 2 to the\n // power of (kBitCount - 1), an integer x is represented by the\n // unsigned number x + N.\n //\n // For instance,\n //\n // -N + 1 (the most negative number representable using\n // sign-and-magnitude) is represented by 1;\n // 0 is represented by N; and\n // N - 1 (the biggest number representable using\n // sign-and-magnitude) is represented by 2N - 1.\n //\n // Read http://en.wikipedia.org/wiki/Signed_number_representations\n // for more details on signed number representations.\n static Bits SignAndMagnitudeToBiased(const Bits &sam) {\n if (kSignBitMask & sam) {\n // sam represents a negative number.\n return ~sam + 1;\n } else {\n // sam represents a positive number.\n return kSignBitMask | sam;\n }\n }\n\n // Given two numbers in the sign-and-magnitude representation,\n // returns the distance between them as an unsigned number.\n static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,\n const Bits &sam2) {\n const Bits biased1 = SignAndMagnitudeToBiased(sam1);\n const Bits biased2 = SignAndMagnitudeToBiased(sam2);\n return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);\n }\n\n FloatingPointUnion u_;\n};\n AlmostEquals" }, { "answer_id": 6874157, "author": "Don Reba", "author_id": 49329, "author_profile": "https://Stackoverflow.com/users/49329", "pm_score": 2, "selected": false, "text": "if (fabs(a - b) <= DBL_EPSILON * fmax(fabs(a), fabs(b)))\n{\n // ...\n}\n if (fabs(a - b) <= 16 * DBL_EPSILON * fmax(fabs(a), fabs(b)))\n{\n // ...\n}\n" }, { "answer_id": 9025280, "author": "WaterbugDesign", "author_id": 1171153, "author_profile": "https://Stackoverflow.com/users/1171153", "pm_score": 2, "selected": false, "text": "typedef unsigned int U32;\n// Float Memory Bias (unsigned)\n// ----- ------ ---------------\n// NaN 0xFFFFFFFF 0xFF800001\n// NaN 0xFF800001 0xFFFFFFFF\n// -Infinity 0xFF800000 0x00000000 ---\n// -3.40282e+038 0xFF7FFFFF 0x00000001 |\n// -1.40130e-045 0x80000001 0x7F7FFFFF |\n// -0.0 0x80000000 0x7F800000 |--- Valid <= 0xFF000000.\n// 0.0 0x00000000 0x7F800000 | NaN > 0xFF000000\n// 1.40130e-045 0x00000001 0x7F800001 |\n// 3.40282e+038 0x7F7FFFFF 0xFEFFFFFF |\n// Infinity 0x7F800000 0xFF000000 ---\n// NaN 0x7F800001 0xFF000001\n// NaN 0x7FFFFFFF 0xFF7FFFFF\n//\n// Either value of NaN returns false.\n// -Infinity and +Infinity are not \"close\".\n// -0 and +0 are equal.\n//\nclass CompareFloat{\npublic:\n union{\n float m_f32;\n U32 m_u32;\n };\n static bool CompareFloat::IsClose( float A, float B, U32 unitsDelta = 4 )\n {\n U32 a = CompareFloat::GetBiased( A );\n U32 b = CompareFloat::GetBiased( B );\n\n if ( (a > 0xFF000000) || (b > 0xFF000000) )\n {\n return( false );\n }\n return( (static_cast<U32>(abs( a - b ))) < unitsDelta );\n }\n protected:\n static U32 CompareFloat::GetBiased( float f )\n {\n U32 r = ((CompareFloat*)&f)->m_u32;\n\n if ( r & 0x80000000 )\n {\n return( ~r - 0x007FFFFF );\n }\n return( r + 0x7F800000 );\n }\n};\n" }, { "answer_id": 15012792, "author": "Shafik Yaghmour", "author_id": 1708801, "author_profile": "https://Stackoverflow.com/users/1708801", "pm_score": 5, "selected": false, "text": "bool absoluteToleranceCompare(double x, double y)\n{\n return std::fabs(x - y) <= std::numeric_limits<double>::epsilon() ;\n}\n bool relativeToleranceCompare(double x, double y)\n{\n double maxXY = std::max( std::fabs(x) , std::fabs(y) ) ;\n return std::fabs(x - y) <= std::numeric_limits<double>::epsilon()*maxXY ;\n}\n x y bool combinedToleranceCompare(double x, double y)\n{\n double maxXYOne = std::max( { 1.0, std::fabs(x) , std::fabs(y) } ) ;\n\n return std::fabs(x - y) <= std::numeric_limits<double>::epsilon()*maxXYOne ;\n}\n" }, { "answer_id": 18518064, "author": "Tomilov Anatoliy", "author_id": 1430927, "author_profile": "https://Stackoverflow.com/users/1430927", "pm_score": 0, "selected": false, "text": "epsilon A B #include <limits>\n#include <iomanip>\n#include <iostream>\n\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n\ntemplate< typename A, typename B >\ninline\nbool close_enough(A const & a, B const & b,\n typename std::common_type< A, B >::type const & epsilon)\n{\n using std::isless;\n assert(isless(0, epsilon)); // epsilon is a part of the whole quantity\n assert(isless(epsilon, 1));\n using std::abs;\n auto const delta = abs(a - b);\n auto const x = abs(a);\n auto const y = abs(b);\n // comparable generally and |a - b| < eps * (|a| + |b|) / 2\n return isless(epsilon * y, x) && isless(epsilon * x, y) && isless((delta + delta) / (x + y), epsilon);\n}\n\nint main()\n{\n std::cout << std::boolalpha << close_enough(0.9, 1.0, 0.1) << std::endl;\n std::cout << std::boolalpha << close_enough(1.0, 1.1, 0.1) << std::endl;\n std::cout << std::boolalpha << close_enough(1.1, 1.2, 0.01) << std::endl;\n std::cout << std::boolalpha << close_enough(1.0001, 1.0002, 0.01) << std::endl;\n std::cout << std::boolalpha << close_enough(1.0, 0.01, 0.1) << std::endl;\n return EXIT_SUCCESS;\n}\n" }, { "answer_id": 20345782, "author": "Vijay", "author_id": 674342, "author_profile": "https://Stackoverflow.com/users/674342", "pm_score": -1, "selected": false, "text": "bool IsFlaotEqual(float a, float b, int decimal)\n{\n TCHAR form[50] = _T(\"\");\n _stprintf(form, _T(\"%%.%df\"), decimal);\n\n\n TCHAR a1[30] = _T(\"\"), a2[30] = _T(\"\");\n _stprintf(a1, form, a);\n _stprintf(a2, form, b);\n\n if( _tcscmp(a1, a2) == 0 )\n return true;\n\n return false;\n\n}\n" }, { "answer_id": 22161983, "author": "Murphy78", "author_id": 3331297, "author_profile": "https://Stackoverflow.com/users/3331297", "pm_score": -1, "selected": false, "text": "/// testing whether two doubles are almost equal. We consider two doubles\n/// equal if the difference is within the range [0, epsilon).\n///\n/// epsilon: a positive number (supposed to be small)\n///\n/// if either x or y is 0, then we are comparing the absolute difference to\n/// epsilon.\n/// if both x and y are non-zero, then we are comparing the relative difference\n/// to epsilon.\nbool almost_equal(double x, double y, double epsilon)\n{\n double diff = x - y;\n if (x != 0 && y != 0){\n diff = diff/y; \n }\n\n if (diff < epsilon && -1.0*diff < epsilon){\n return true;\n }\n return false;\n}\n" }, { "answer_id": 35244528, "author": "Daniel Laügt", "author_id": 5229914, "author_profile": "https://Stackoverflow.com/users/5229914", "pm_score": -1, "selected": false, "text": "double EPSILON double EPSILON bool same(double a, double b)\n{\n return std::nextafter(a, std::numeric_limits<double>::lowest()) <= b\n && std::nextafter(a, std::numeric_limits<double>::max()) >= b;\n}\n" }, { "answer_id": 39523514, "author": "André Sousa", "author_id": 3746290, "author_profile": "https://Stackoverflow.com/users/3746290", "pm_score": 0, "selected": false, "text": "template <typename T>\nbool compareNumber(const T& a, const T& b) {\n return std::abs(a - b) < std::numeric_limits<T>::epsilon();\n}\n" }, { "answer_id": 41405501, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 5, "selected": false, "text": "numeric_limits::epsilon() fabs(a-b) <= epsilon max(a,b) //implements relative method - do not use for comparing with zero\n//use this most of the time, tolerance needs to be meaningful in your context\ntemplate<typename TReal>\nstatic bool isApproximatelyEqual(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n TReal diff = std::fabs(a - b);\n if (diff <= tolerance)\n return true;\n\n if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n return true;\n\n return false;\n}\n\n//supply tolerance that is meaningful in your context\n//for example, default tolerance may not work if you are comparing double with float\ntemplate<typename TReal>\nstatic bool isApproximatelyZero(TReal a, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n if (std::fabs(a) <= tolerance)\n return true;\n return false;\n}\n\n\n//use this when you want to be on safe side\n//for example, don't start rover unless signal is above 1\ntemplate<typename TReal>\nstatic bool isDefinitelyLessThan(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n TReal diff = a - b;\n if (diff < tolerance)\n return true;\n\n if (diff < std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n return true;\n\n return false;\n}\ntemplate<typename TReal>\nstatic bool isDefinitelyGreaterThan(TReal a, TReal b, TReal tolerance = std::numeric_limits<TReal>::epsilon())\n{\n TReal diff = a - b;\n if (diff > tolerance)\n return true;\n\n if (diff > std::fmax(std::fabs(a), std::fabs(b)) * tolerance)\n return true;\n\n return false;\n}\n\n//implements ULP method\n//use this when you are only concerned about floating point precision issue\n//for example, if you want to see if a is 1.0 by checking if its within\n//10 closest representable floating point numbers around 1.0.\ntemplate<typename TReal>\nstatic bool isWithinPrecisionInterval(TReal a, TReal b, unsigned int interval_size = 1)\n{\n TReal min_a = a - (a - std::nextafter(a, std::numeric_limits<TReal>::lowest())) * interval_size;\n TReal max_a = a + (std::nextafter(a, std::numeric_limits<TReal>::max()) - a) * interval_size;\n\n return min_a <= b && max_a >= b;\n}\n" }, { "answer_id": 44210773, "author": "Chunde Huang", "author_id": 3308831, "author_profile": "https://Stackoverflow.com/users/3308831", "pm_score": 0, "selected": false, "text": "bool AlmostEqual(double v1, double v2)\n {\n return (std::fabs(v1 - v2) < std::fabs(std::min(v1, v2)) * std::numeric_limits<double>::epsilon());\n }\n" }, { "answer_id": 47514895, "author": "Chameleon", "author_id": 1438465, "author_profile": "https://Stackoverflow.com/users/1438465", "pm_score": -1, "selected": false, "text": "public static boolean equal(double a, double b) {\n final long fm = 0xFFFFFFFFFFFFFL; // fraction mask\n final long sm = 0x8000000000000000L; // sign mask\n final long cm = 0x8000000000000L; // most significant decimal bit mask\n long c = Double.doubleToLongBits(a), d = Double.doubleToLongBits(b); \n int ea = (int) (c >> 52 & 2047), eb = (int) (d >> 52 & 2047);\n if (ea == 2047 && (c & fm) != 0 || eb == 2047 && (d & fm) != 0) return false; // NaN \n if (c == d) return true; // identical - fast check\n if (ea == 0 && eb == 0) return true; // ±0 or subnormals\n if ((c & sm) != (d & sm)) return false; // different signs\n if (abs(ea - eb) > 1) return false; // b > 2*a or a > 2*b\n d <<= 12; c <<= 12;\n if (ea < eb) c = c >> 1 | sm;\n else if (ea > eb) d = d >> 1 | sm;\n c -= d;\n return c < 65536 && c > -65536; // don't use abs(), because:\n // There is a posibility c=0x8000000000000000 which cannot be converted to positive\n}\npublic static boolean zero(double a) { return (Double.doubleToLongBits(a) >> 52 & 2047) < 3; }\n" }, { "answer_id": 50997465, "author": "Steve Hollasch", "author_id": 566185, "author_profile": "https://Stackoverflow.com/users/566185", "pm_score": 3, "selected": false, "text": "std::numeric_limits::epsilon() #include <stdio.h>\n#include <limits>\n\ndouble ItoD (__int64 x) {\n // Return double from 64-bit hexadecimal representation.\n return *(reinterpret_cast<double*>(&x));\n}\n\nvoid test (__int64 ai, __int64 bi) {\n double a = ItoD(ai), b = ItoD(bi);\n bool close = std::fabs(a-b) < std::numeric_limits<double>::epsilon();\n printf (\"%.16f and %.16f %s close.\\n\", a, b, close ? \"are \" : \"are not\");\n}\n\nint main()\n{\n test (0x3fe0000000000000L,\n 0x3fe0000000000001L);\n\n test (0x3ff0000000000000L,\n 0x3ff0000000000001L);\n}\n 0.5000000000000000 and 0.5000000000000001 are close.\n1.0000000000000000 and 1.0000000000000002 are not close.\n" }, { "answer_id": 51015912, "author": "Dana Yan", "author_id": 4472316, "author_profile": "https://Stackoverflow.com/users/4472316", "pm_score": 3, "selected": false, "text": "static inline bool qFuzzyCompare(double p1, double p2)\n{\n return (qAbs(p1 - p2) <= 0.000000000001 * qMin(qAbs(p1), qAbs(p2)));\n}\n\nstatic inline bool qFuzzyCompare(float p1, float p2)\n{\n return (qAbs(p1 - p2) <= 0.00001f * qMin(qAbs(p1), qAbs(p2)));\n}\n static inline bool qFuzzyIsNull(double d)\n{\n return qAbs(d) <= 0.000000000001;\n}\n\nstatic inline bool qFuzzyIsNull(float f)\n{\n return qAbs(f) <= 0.00001f;\n}\n" }, { "answer_id": 59402500, "author": "Prashant Nidgunde", "author_id": 3351974, "author_profile": "https://Stackoverflow.com/users/3351974", "pm_score": 0, "selected": false, "text": "#include <cmath>\n#include <limits>\n#include <iomanip>\n#include <iostream>\n#include <type_traits>\n#include <algorithm>\n\n\n\ntemplate<class T>\ntypename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type\n almost_equal(T x, T y, int ulp)\n{\n // the machine epsilon has to be scaled to the magnitude of the values used\n // and multiplied by the desired precision in ULPs (units in the last place)\n return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp\n // unless the result is subnormal\n || std::fabs(x-y) < std::numeric_limits<T>::min();\n}\n\nint main()\n{\n double d1 = 0.2;\n double d2 = 1 / std::sqrt(5) / std::sqrt(5);\n std::cout << std::fixed << std::setprecision(20) \n << \"d1=\" << d1 << \"\\nd2=\" << d2 << '\\n';\n\n if(d1 == d2)\n std::cout << \"d1 == d2\\n\";\n else\n std::cout << \"d1 != d2\\n\";\n\n if(almost_equal(d1, d2, 2))\n std::cout << \"d1 almost equals d2\\n\";\n else\n std::cout << \"d1 does not almost equal d2\\n\";\n}\n" }, { "answer_id": 59919755, "author": "Amir Saniyan", "author_id": 309798, "author_profile": "https://Stackoverflow.com/users/309798", "pm_score": -1, "selected": false, "text": "#include <cmath>\n#include <limits>\n\nauto Compare = [](float a, float b, float epsilon = std::numeric_limits<float>::epsilon()){ return (std::fabs(a - b) <= epsilon); };\n" }, { "answer_id": 61498650, "author": "derke", "author_id": 2034366, "author_profile": "https://Stackoverflow.com/users/2034366", "pm_score": -1, "selected": false, "text": "template<typename T>\nbool FloatingPointEqual( T a, T b ) { return !(a < b) && !(b < a); }\n" }, { "answer_id": 63838196, "author": "Oleksandr Boiko", "author_id": 12446338, "author_profile": "https://Stackoverflow.com/users/12446338", "pm_score": -1, "selected": false, "text": "bool floatApproximatelyEquals(const float a, const float b) {\n if (b == 0.) return a == 0.; // preventing division by zero\n return abs(1. - a / b) < 1e-6;\n}\n 1e100 1e-100" }, { "answer_id": 65015333, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 2, "selected": false, "text": "== fabs() abs() /// @brief See if two floating point numbers are approximately equal.\n/// @param[in] a number 1\n/// @param[in] b number 2\n/// @param[in] epsilon A small value such that if the difference between the two numbers is\n/// smaller than this they can safely be considered to be equal.\n/// @return true if the two numbers are approximately equal, and false otherwise\nbool is_float_eq(float a, float b, float epsilon) {\n return ((a - b) < epsilon) && ((b - a) < epsilon);\n}\nbool is_double_eq(double a, double b, double epsilon) {\n return ((a - b) < epsilon) && ((b - a) < epsilon);\n}\n constexpr float EPSILON = 0.0001; // 1e-4\nis_float_eq(1.0001, 0.99998, EPSILON);\n float a = 1.0001;\nfloat b = 0.99998;\nfloat epsilon = std::max(std::fabs(a), std::fabs(b)) * 1e-4;\n\nis_float_eq(a, b, epsilon);\n > < /// @brief See if floating point number `a` is > `b`\n/// @param[in] a number 1\n/// @param[in] b number 2\n/// @param[in] epsilon a small value such that if `a` is > `b` by this amount, `a` is considered\n/// to be definitively > `b`\n/// @return true if `a` is definitively > `b`, and false otherwise\nbool is_float_gt(float a, float b, float epsilon) {\n return a > b + epsilon;\n}\nbool is_double_gt(double a, double b, double epsilon) {\n return a > b + epsilon;\n}\n\n/// @brief See if floating point number `a` is < `b`\n/// @param[in] a number 1\n/// @param[in] b number 2\n/// @param[in] epsilon a small value such that if `a` is < `b` by this amount, `a` is considered\n/// to be definitively < `b`\n/// @return true if `a` is definitively < `b`, and false otherwise\nbool is_float_lt(float a, float b, float epsilon) {\n return a < b - epsilon;\n}\nbool is_double_lt(double a, double b, double epsilon) {\n return a < b - epsilon;\n}\n >= <= /// @brief Returns true if `a` is definitively >= `b`, and false otherwise\nbool is_float_ge(float a, float b, float epsilon) {\n return a > b - epsilon;\n}\nbool is_double_ge(double a, double b, double epsilon) {\n return a > b - epsilon;\n}\n\n/// @brief Returns true if `a` is definitively <= `b`, and false otherwise\nbool is_float_le(float a, float b, float epsilon) {\n return a < b + epsilon;\n}\nbool is_double_le(double a, double b, double epsilon) {\n return a < b + epsilon;\n}\n epsilon std::numeric_limits<T>::epsilon() 0 FLT_EPSILON DBL_EPSILON LDBL_EPSILON float.h FLT_EPSILON DBL_EPSILON LDBL_EPSILON float double long double static_assert() epsilon a b max(1.0, abs(a), abs(b)) a b 1.0 a b 1.0 float_comparison is_eq() float_comparison::is_eq(1.0, 1.5); namespace float_comparison {\n\n/// Scale the epsilon value to become large for large-magnitude a or b, \n/// but no smaller than 1.0, per the explanation above, to ensure that \n/// epsilon doesn't ever fall out in floating point error as a and/or b\n/// increase in magnitude.\ntemplate<typename T>\nstatic constexpr T scale_epsilon(T a, T b, T epsilon = \n std::numeric_limits<T>::epsilon()) noexcept \n{\n static_assert(std::is_floating_point_v<T>, \"Floating point comparisons \"\n \"require type float, double, or long double.\");\n T scaling_factor;\n // Special case for when a or b is infinity\n if (std::isinf(a) || std::isinf(b)) \n {\n scaling_factor = 0;\n } \n else \n {\n scaling_factor = std::max({(T)1.0, std::abs(a), std::abs(b)});\n }\n\n T epsilon_scaled = scaling_factor * std::abs(epsilon);\n return epsilon_scaled;\n}\n\n// Compare two values\n\n/// Equal: returns true if a is approximately == b, and false otherwise\ntemplate<typename T>\nstatic constexpr bool is_eq(T a, T b, T epsilon = \n std::numeric_limits<T>::epsilon()) noexcept \n{\n static_assert(std::is_floating_point_v<T>, \"Floating point comparisons \"\n \"require type float, double, or long double.\");\n // test `a == b` first to see if both a and b are either infinity \n // or -infinity\n return a == b || std::abs(a - b) <= scale_epsilon(a, b, epsilon);\n}\n\n/* \netc. etc.:\nis_eq()\nis_ne()\nis_lt()\nis_le()\nis_gt()\nis_ge()\n*/\n\n// Compare against zero\n\n/// Equal: returns true if a is approximately == 0, and false otherwise\ntemplate<typename T>\nstatic constexpr bool is_eq_zero(T a, T epsilon = \n std::numeric_limits<T>::epsilon()) noexcept \n{\n static_assert(std::is_floating_point_v<T>, \"Floating point comparisons \"\n \"require type float, double, or long double.\");\n return is_eq(a, (T)0.0, epsilon);\n}\n\n/* \netc. etc.:\nis_eq_zero()\nis_ne_zero()\nis_lt_zero()\nis_le_zero()\nis_gt_zero()\nis_ge_zero()\n*/\n\n} // namespace float_comparison\n a b" }, { "answer_id": 71252885, "author": "Carlo Wood", "author_id": 1487069, "author_profile": "https://Stackoverflow.com/users/1487069", "pm_score": 0, "selected": false, "text": "abs_relative_error template<class T>\ntypename std::enable_if<std::is_floating_point<T>::value, bool>::type\n almost_equal(T x, T y, T const abs_relative_error)\n{\n return 2 * std::abs(x - y) <= abs_relative_error * std::abs(x + y);\n}\n abs_relative_error abs_relative_error" }, { "answer_id": 73599902, "author": "Athanasios Salamanis", "author_id": 8794361, "author_profile": "https://Stackoverflow.com/users/8794361", "pm_score": 0, "selected": false, "text": "bool approximatelyEqual(double a, double b)\n{\n return fabs(a - b) <= ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * std::numeric_limits<double>::epsilon());\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057/" ]
17,352
<p>In relation to this question on <a href="https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows">Using OpenGL extensions</a>, what's the purpose of these extension functions? Why would I want to use them? Further, are there any tradeoffs or gotchas associated with using them?</p>
[ { "answer_id": 23908, "author": "spate", "author_id": 2276, "author_profile": "https://Stackoverflow.com/users/2276", "pm_score": 3, "selected": false, "text": "NV_vertex_program EXT_vertex_program ARB_vertex_program ARB_vertex_program ARB_vertex_shader ARB_matrix_palette ARB_vertex_buffer_object ARB_vertex_shader ARB_fragment_shader ARB_shader_objects ARB/EXT_framebuffer_object" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803/" ]
17,359
<p>I've created a script that runs every night on my Linux server that uses <code>mysqldump</code> to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to <code>mailx</code> like so:</p> <pre><code>$ cat mysqldbbackup.sql | mailx [email protected] </code></pre> <p><code>cat</code> echoes the backup file's text which is piped into the <code>mailx</code> program with the recipient's email address passed as an argument.</p> <p>While this accomplishes what I need, I think it could be one step better, <strong>Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an <em>attachment</em>?</strong> This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.</p>
[ { "answer_id": 17365, "author": "Chris N", "author_id": 1653, "author_profile": "https://Stackoverflow.com/users/1653", "pm_score": 5, "selected": false, "text": "man mailx echo \"This is the message body\" | mutt -a file.to.attach -s \"subject of message\" [email protected]\n mutt -h" }, { "answer_id": 17366, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 4, "selected": false, "text": "mutt -s \"Backup\" -a mysqldbbackup.sql [email protected] < message.txt\n" }, { "answer_id": 17381, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 6, "selected": false, "text": "mail -s \"Backup\" -a mysqldbbackup.sql [email protected] < message.txt\n cat message.txt | mail -s \"Backup\" -a mysqldbbackup.sql [email protected]\n" }, { "answer_id": 17422, "author": "Daniel Fone", "author_id": 1848, "author_profile": "https://Stackoverflow.com/users/1848", "pm_score": 6, "selected": false, "text": "gzip -c mysqldbbackup.sql | uuencode mysqldbbackup.sql.gz | mail -s \"MySQL DB\" [email protected]\n" }, { "answer_id": 84355, "author": "Gunstick", "author_id": 15653, "author_profile": "https://Stackoverflow.com/users/15653", "pm_score": 2, "selected": false, "text": "metasend -f mysqlbackup.sql.gz -t [email protected] -s Backup -m application/x-gzip -b\n" }, { "answer_id": 1470149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "mpack -s subject file [email protected]\n mpack -s subject /dev/stdin [email protected] < file\n" }, { "answer_id": 4887607, "author": "glenn jackman", "author_id": 7552, "author_profile": "https://Stackoverflow.com/users/7552", "pm_score": 4, "selected": false, "text": "# usage: email_attachment to cc subject body attachment_filename\nemail_attachment() {\n to=\"$1\"\n cc=\"$2\"\n subject=\"$3\"\n body=\"$4\"\n filename=\"${5:-''}\"\n boundary=\"_====_blah_====_$(date +%Y%m%d%H%M%S)_====_\"\n {\n print -- \"To: $to\"\n print -- \"Cc: $cc\"\n print -- \"Subject: $subject\"\n print -- \"Content-Type: multipart/mixed; boundary=\\\"$boundary\\\"\"\n print -- \"Mime-Version: 1.0\"\n print -- \"\"\n print -- \"This is a multi-part message in MIME format.\"\n print -- \"\"\n print -- \"--$boundary\"\n print -- \"Content-Type: text/plain; charset=ISO-8859-1\"\n print -- \"\"\n print -- \"$body\"\n print -- \"\"\n if [[ -n \"$filename\" && -f \"$filename\" && -r \"$filename\" ]]; then\n print -- \"--$boundary\"\n print -- \"Content-Transfer-Encoding: base64\"\n print -- \"Content-Type: application/octet-stream; name=$filename\"\n print -- \"Content-Disposition: attachment; filename=$filename\"\n print -- \"\"\n print -- \"$(perl -MMIME::Base64 -e 'open F, shift; @lines=<F>; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)\"\n print -- \"\"\n fi\n print -- \"--${boundary}--\"\n } | /usr/lib/sendmail -oi -t\n}\n" }, { "answer_id": 9524359, "author": "rynop", "author_id": 563420, "author_profile": "https://Stackoverflow.com/users/563420", "pm_score": 9, "selected": true, "text": "echo \"This is the message body\" | mutt -a \"/path/to/file.to.attach\" -s \"subject of message\" -- [email protected]\n" }, { "answer_id": 14213935, "author": "user1651561", "author_id": 1651561, "author_profile": "https://Stackoverflow.com/users/1651561", "pm_score": 4, "selected": false, "text": "(\n /usr/bin/uuencode attachfile.txt myattachedfilename.txt; \n /usr/bin/echo \"Body of text\"\n) | mailx -s 'Subject' [email protected]\n ( /usr/bin/uuencode /home/el/attachfile.txt myattachedfilename.txt; /usr/bin/echo \"Body of text\" ) | mailx -s 'Subject' [email protected]\n /home/el/attachfile.txt <html><body>\nGovernment discriminates against programmers with cruel/unusual 35 year prison\nsentences for making the world's information free, while bankers that pilfer \ntrillions in citizens assets through systematic inflation get the nod and \nwalk free among us.\n</body></html>\n yum info ksh test.sh /home/el test.sh #!/usr/bin/ksh\nexport MAILFROM=\"[email protected]\"\nexport MAILTO=\"[email protected]\"\nexport SUBJECT=\"Test PDF for Email\"\nexport BODY=\"/home/el/email_body.htm\"\nexport ATTACH=\"/home/el/pdf-test.pdf\"\nexport MAILPART=`uuidgen` ## Generates Unique ID\nexport MAILPART_BODY=`uuidgen` ## Generates Unique ID\n\n(\n echo \"From: $MAILFROM\"\n echo \"To: $MAILTO\"\n echo \"Subject: $SUBJECT\"\n echo \"MIME-Version: 1.0\"\n echo \"Content-Type: multipart/mixed; boundary=\\\"$MAILPART\\\"\"\n echo \"\"\n echo \"--$MAILPART\"\n echo \"Content-Type: multipart/alternative; boundary=\\\"$MAILPART_BODY\\\"\"\n echo \"\"\n echo \"--$MAILPART_BODY\"\n echo \"Content-Type: text/plain; charset=ISO-8859-1\"\n echo \"You need to enable HTML option for email\"\n echo \"--$MAILPART_BODY\"\n echo \"Content-Type: text/html; charset=ISO-8859-1\"\n echo \"Content-Disposition: inline\"\n cat $BODY\n echo \"--$MAILPART_BODY--\"\n\n echo \"--$MAILPART\"\n echo 'Content-Type: application/pdf; name=\"'$(basename $ATTACH)'\"'\n echo \"Content-Transfer-Encoding: uuencode\"\n echo 'Content-Disposition: attachment; filename=\"'$(basename $ATTACH)'\"'\n echo \"\"\n uuencode $ATTACH $(basename $ATTACH)\n echo \"--$MAILPART--\"\n) | /usr/sbin/sendmail $MAILTO\n test.sh /home/el <html><body><b>this is some bold text</b></body></html>\n ./test.sh" }, { "answer_id": 19705851, "author": "Fredrik Wendt", "author_id": 153117, "author_profile": "https://Stackoverflow.com/users/153117", "pm_score": 5, "selected": false, "text": "sendemail -f [email protected] -t [email protected] -m \"Here are your files!\" -a file1.jpg file2.zip" }, { "answer_id": 20817976, "author": "Allan Pinto", "author_id": 2428576, "author_profile": "https://Stackoverflow.com/users/2428576", "pm_score": 0, "selected": false, "text": "mailx -a" }, { "answer_id": 24479275, "author": "Yoav", "author_id": 868331, "author_profile": "https://Stackoverflow.com/users/868331", "pm_score": 0, "selected": false, "text": "git push" }, { "answer_id": 25266816, "author": "Alejandro Santillan", "author_id": 3933842, "author_profile": "https://Stackoverflow.com/users/3933842", "pm_score": 1, "selected": false, "text": "mailx -s \"Sending Files\" -a First_LocalConfig.conf -a\nSecond_LocalConfig.conf [email protected]\n\nThis is the content of my msg.\n\n.\n" }, { "answer_id": 29638575, "author": "Pipo", "author_id": 2118777, "author_profile": "https://Stackoverflow.com/users/2118777", "pm_score": 0, "selected": false, "text": "file=filename_or_filepath;uuencode $file $file|mail -s \"optional subject\" email_address\n file=your_sql.log;gzip -c $file;uuencode ${file}.gz ${file}|mail -s \"file with magnets\" [email protected]\n" }, { "answer_id": 30393142, "author": "Sourabh Potnis", "author_id": 3322308, "author_profile": "https://Stackoverflow.com/users/3322308", "pm_score": 5, "selected": false, "text": " echo -e 'Hi, \\n These are contents of my mail. \\n Thanks' | mailx -s 'This is my email subject' -a /path/to/attachment_file.log -b [email protected] -c [email protected] -r [email protected] [email protected] [email protected] [email protected]\n" }, { "answer_id": 31813090, "author": "poncho", "author_id": 5190280, "author_profile": "https://Stackoverflow.com/users/5190280", "pm_score": 1, "selected": false, "text": "echo \"Start of Body\" && uuencode log.cfg readme.txt | mail -s \"subject\" \"[email protected]\" \n" }, { "answer_id": 32399399, "author": "dagorv", "author_id": 5300945, "author_profile": "https://Stackoverflow.com/users/5300945", "pm_score": 0, "selected": false, "text": "#!/bin/sh\nMAIL_CMD=\"$(which mail)\"\nWHOAMI=\"$(whoami)\"\nHOSTNAME=\"$(hostname)\"\nEMAIL\"[email protected]\"\nLOGDIR=\"/var/log/aide\"\nLOGNAME=\"$(basename \"$0\")_$(date \"+%Y%m%d_%H%M\")\"\n\nif cd ${LOGDIR}; then\n /bin/tar -zcvf \"${LOGDIR}/${LOGNAME}\".tgz \"${LOGDIR}/${LOGNAME}.log\" > /dev/null 2>&1\n if [ -n \"${MAIL_CMD}\" ]; then\n # This works too. The message content will be taken from text file below\n # echo 'Hello!' >/root/scripts/audit_check.sh.txt\n # echo \"Attachment\" | ${MAIL_CMD} -s \"${HOSTNAME} Aide report\" -q /root/scripts/audit_check.sh.txt -a ${LOGNAME}.tgz -S from=${WHOAMI}@${HOSTNAME} ${EMAIL}\n echo \"Attachment\" | ${MAIL_CMD} -s \"${HOSTNAME} Aide report\" -a \"${LOGNAME}.tgz\" -S from=\"${WHOAMI}@${HOSTNAME}\" \"${EMAIL}\"\n /bin/rm \"${LOGDIR}/${LOGNAME}.log\"\n fi\nfi\n" }, { "answer_id": 41791423, "author": "Konchog", "author_id": 5678653, "author_profile": "https://Stackoverflow.com/users/5678653", "pm_score": 1, "selected": false, "text": "mysqldump --defaults-extra-file=sql.cnf database | gzip | base64 | mail [email protected]\n base64 -D -i db.sql.gz.b64 | gzip -d | mysql --defaults-extra-file=sql.cnf\n" }, { "answer_id": 42414622, "author": "nurp", "author_id": 2232573, "author_profile": "https://Stackoverflow.com/users/2232573", "pm_score": 0, "selected": false, "text": "sendmail [email protected] < message.txt\n" }, { "answer_id": 43997990, "author": "Paras Singh", "author_id": 3841982, "author_profile": "https://Stackoverflow.com/users/3841982", "pm_score": -1, "selected": false, "text": "*#!/bin/sh\n\nFilePath=$1\nFileName=$2\nMessage=$3\nMailList=$4\n\ncd $FilePath\n\nRec_count=$(wc -l < $FileName)\nif [ $Rec_count -gt 0 ]\nthen\n(echo \"The attachment contains $Message\" ; uuencode $FileName $FileName.csv ) | mailx -s \"$Message\" $MailList\nfi*\n" }, { "answer_id": 46052152, "author": "Alexander Yancharuk", "author_id": 2648942, "author_profile": "https://Stackoverflow.com/users/2648942", "pm_score": 3, "selected": false, "text": "swaks -tls \\\n --to ${MAIL_TO} \\\n --from ${MAIL_FROM} \\\n --server ${MAIL_SERVER} \\\n --auth LOGIN \\\n --auth-user ${MAIL_USER} \\\n --auth-password ${MAIL_PASSWORD} \\\n --header \"Subject: $MAIL_SUBJECT\" \\\n --header \"Content-Type: text/html; charset=UTF-8\" \\\n --body \"$MESSAGE\" \\\n --attach mysqldbbackup.sql\n" }, { "answer_id": 46114228, "author": "Girdhar Singh Rathore", "author_id": 5115670, "author_profile": "https://Stackoverflow.com/users/5115670", "pm_score": 1, "selected": false, "text": " echo \"Message Body Here\" | mailx -s \"Subject Here\" -a file_name [email protected]\n #!/bin/ksh\n\nfileToAttach=data.txt\n\n`(echo \"To: [email protected]\"\n echo \"Cc: [email protected]\"\n echo \"From: Application\"\n echo \"Subject: your subject\"\n echo your body\n uuencode $fileToAttach $fileToAttach\n )| eval /usr/sbin/sendmail -t `;\n" }, { "answer_id": 48588035, "author": "tripleee", "author_id": 874188, "author_profile": "https://Stackoverflow.com/users/874188", "pm_score": 4, "selected": false, "text": "mail mailx mail mail mail Mail mail mailx x uuencode mail mailx mail mailx Provides: mailx debian$ aptitude search ~Pmailx\ni bsd-mailx - simple mail user agent\np heirloom-mailx - feature-rich BSD mail(1)\np mailutils - GNU mailutils utilities for handling mail\n bsd-mailx mailx heirloom-mailx s-nail -a mailutils mail mailx -A mutt echo base64 qprint base64 qprint sendmail ( printf '%s\\n' \\\n \"From: myself <[email protected]>\" \\\n \"To: backup address <[email protected]>\" \\\n \"Subject: Backup of $(date)\" \\\n \"MIME-Version: 1.0\" \\\n \"Content-type: application/octet-stream; filename=\\\"mysqldbbackup.sql\\\"\" \\\n \"Content-transfer-encoding: base64\" \\\n \"\"\n base64 < mysqldbbackup.sql ) |\nsendmail -oi -t\n" }, { "answer_id": 54726498, "author": "rumpel", "author_id": 597401, "author_profile": "https://Stackoverflow.com/users/597401", "pm_score": 2, "selected": false, "text": "echo \"Body\" | mail.mailutils -M -s \"My Subject\" -A attachment.pdf [email protected]\n -A file -M sudo apt install mailutils\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1339/" ]
17,370
<p>I've been using OpenGL extensions on Windows the <a href="https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows">painful way</a>. Is GLEW the easier way to go? How do I get started with it?</p>
[ { "answer_id": 17371, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 6, "selected": true, "text": "#pragma comment(lib, \"glew32.lib\")\n #include <GL/glew.h> glew.h glewInit() if (GLEW_OK != glewInit())\n{\n // GLEW failed!\n exit(1);\n}\n if (!GLEW_EXT_framebuffer_object)\n{\n exit(1);\n}\n" }, { "answer_id": 17429, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 3, "selected": false, "text": "try\n{\n // init opengl/directx\n // init directaudio\n // init directinput\n\n if (GLEW_OK != glewInit())\n {\n throw std::exception(\"glewInit failed\");\n }\n}\ncatch ( const std::exception& ex )\n{\n // message to screen using ex.what()\n // clear up\n}\n" }, { "answer_id": 17922836, "author": "iMineLink", "author_id": 2627697, "author_profile": "https://Stackoverflow.com/users/2627697", "pm_score": 2, "selected": false, "text": "#include <GL/glew.h> #include <GL/glut.h>" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
17,373
<p>How do I open the default mail program with a Subject and Body in a cross-platform way?</p> <p>Unfortunately, this is for a a client app written in Java, not a website.</p> <p>I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever.</p> <p>In OS X, I have tried executing the command:</p> <pre><code>open mailto:?subject=MySubject&amp;body=TheBody </code></pre> <p>URL escaping is needed to replace spaces with <code>%20</code>.</p> <p><strong>Updated</strong> On Windows, you have to play all sorts of games to get <code>start</code> to run correctly. Here is the proper Java incantation:</p> <pre><code>class Win32 extends OS { public void email(String subject, String body) throws Exception { String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\""; Runtime.getRuntime().exec(cmd); } } </code></pre>
[ { "answer_id": 17389, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 2, "selected": false, "text": "<a href=\"mailto:[email protected]?subject=Mail from Our Site\">Email Us</a> \n <a href=\"mailto:[email protected][email protected]\">Email Us</a>\n <a href=\"mailto:[email protected][email protected], [email protected], [email protected]\">Email Us</a> \n [email protected]?subject=Hello&[email protected]&[email protected]\n <a href=\"mailto:[email protected][email protected]\n&[email protected]&Subject=Please%2C%20I%20insist\n%21&Body=Hi%0DI%20would%20like%20to%20send%20you%20\n%241000000%20to%20divide%20as%20you%20see%20fit%20among\n%20yourselves%20and%20all%20the%20moderators.%0DPlease%\n20let%20me%20know%20to%20whom%20I%20should%20send\n%20the%20check.\">this link</a> \n" }, { "answer_id": 17394, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 0, "selected": false, "text": "public void email(String subject, String body) throws Exception {\n String cmd = \"open mailto:\"; \n cmd += \"?subject=\" + urlEncode(subject);\n cmd += \"&body=\" + urlEncode(body);\n Runtime.getRuntime().exec(cmd);\n}\n\nprivate static String urlEncode(String s) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (Character.isLetterOrDigit(ch)) {\n sb.append(ch);\n }\n else {\n sb.append(String.format(\"%%%02X\", (int)ch));\n }\n }\n return sb.toString();\n}\n +" }, { "answer_id": 17398, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "; %3B\n? %3F\n/ %2F\n: %3A\n# %23\n& %24\n= %3D\n+ %2B\n$ %26\n, %2C\nspace %20 or +\n% %25\n< %3C\n> %3E\n~ %7E\n% %25\n" }, { "answer_id": 17426, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": false, "text": "start start mailto:\"?subject=My%20Subject&body=The%20Body\"\n" }, { "answer_id": 17535, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 2, "selected": false, "text": "private String encodex(final String s) {\n try {\n return java.net.URLEncoder.encode(s, \"utf-8\").replaceAll(\"\\\\+\", \"%20\").replaceAll(\"\\\\%0A\", \"%0D%0A\");\n } catch (Throwable x) {\n return s;\n }\n}\n" }, { "answer_id": 27353, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 2, "selected": false, "text": "Runtime.exec(String) Runtime.exec(String[])" }, { "answer_id": 12107210, "author": "NoNaMe", "author_id": 1410342, "author_profile": "https://Stackoverflow.com/users/1410342", "pm_score": 1, "selected": false, "text": "main(string[] args){ \nString forUri = String.format(\"mailto:?subject=%s&body=%s\", urlEncode(sub), urlEncode(mailBody));\n Desktop.getDesktop().mail(new URI(forUri));\n}\n\nprivate static final String urlEncode(String str) {\n try {\n return URLEncoder.encode(str, \"UTF-8\").replace(\"+\", \"%20\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
17,376
<p>I have a PHP script that runs as a CGI program and the HTTP <code>Authenticate</code> header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored.</p> <p>I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials.</p> <p>So how would you implement this?</p> <p>Cookies?</p> <p>I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.</p>
[ { "answer_id": 31869, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 1, "selected": false, "text": "// At the top of your 'private' page(s):\nif($_SESSION['authenticated'] !== TRUE) {\n header('Location: /login.php');\n die();\n}\n\n// the target of the POST form from login.php\nif(http_authenticate($_POST['username'], $_POST['password']))\n $_SESSION['authenticated'] = TRUE;\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
17,387
<p>I have a blogengine.net install that requires privatization.</p> <p>I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met.</p> <p>How can I privatize my blogEngine.net install so that readers must log in to read my posts?</p>
[ { "answer_id": 17392, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<system.web>\n <authorization>\n <allow roles=\"Admin\" />\n <deny users=\"*\" />\n </authorization>\n</system.web>\n" }, { "answer_id": 222016, "author": "Rafe", "author_id": 27497, "author_profile": "https://Stackoverflow.com/users/27497", "pm_score": 2, "selected": true, "text": "using System;\n\nusing System.Data;\n\nusing System.Configuration;\n\nusing System.Web;\n\nusing System.Web.Security;\n\nusing System.Web.UI;\n\nusing System.Web.UI.HtmlControls;\n\nusing System.Web.UI.WebControls;\n\nusing System.Web.UI.WebControls.WebParts;\n\nusing BlogEngine.Core;\n\nusing BlogEngine.Core.Web.Controls;\n\nusing System.Collections.Generic;\n\n\n\n/// <summary>\n\n/// Summary description for PostSecurity\n\n/// </summary>\n\n[Extension(\"Checks to see if a user can see this blog post.\",\n\n \"1.0\", \"<a href=\\\"http://www.lavablast.com\\\">LavaBlast.com</a>\")]\n\npublic class RequireLogin\n{\n\n static protected ExtensionSettings settings = null;\n\n\n\n public RequireLogin()\n {\n\n Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);\n\n\n\n ExtensionSettings s = new ExtensionSettings(\"RequireLogin\");\n\n // describe specific rules for entering parameters\n\n s.Help = \"Checks to see if the user has any of those roles before displaying the post. \";\n\n s.Help += \"You can associate a role with a specific category. \";\n\n s.Help += \"All posts having this category will require that the user have the role. \";\n\n s.Help += \"A parameter with only a role without a category will enable to filter all posts to this role. \";\n\n ExtensionManager.ImportSettings(s);\n\n settings = ExtensionManager.GetSettings(\"PostSecurity\");\n\n }\n\n\n\n protected void Post_Serving(object sender, ServingEventArgs e)\n {\n MembershipUser user = Membership.GetUser();\n if(HttpContext.Current.Request.RawUrl.Contains(\"syndication.axd\"))\n {\n return;\n }\n\n if (user == null)\n {\n HttpContext.Current.Response.Redirect(\"~/Login.aspx\");\n }\n }\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
17,411
<p>How can you make the display frames per second be independent from the game logic? That is so the game logic runs the same speed no matter how fast the video card can render. </p>
[ { "answer_id": 17415, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 2, "selected": false, "text": "int lastTime = GetCurrentTime();\nwhile(1) {\n // how long is it since we last updated?\n int currentTime = GetCurrentTime();\n int dt = currentTime - lastTime;\n lastTime = currentTime;\n\n // now do the game logic\n Update(dt);\n\n // and you can render\n Draw();\n}\n Update() v v * dt" }, { "answer_id": 17427, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "time0 = getTickCount();\ndo\n{\n time1 = getTickCount();\n frameTime = 0;\n int numLoops = 0;\n\n while ((time1 - time0) TICK_TIME && numLoops < MAX_LOOPS)\n {\n GameTickRun();\n time0 += TICK_TIME;\n frameTime += TICK_TIME;\n numLoops++;\n// Could this be a good idea? We're not doing it, anyway.\n// time1 = getTickCount();\n }\n IndependentTickRun(frameTime);\n\n // If playing solo and game logic takes way too long, discard pending\ntime.\n if (!bNetworkGame && (time1 - time0) TICK_TIME)\n time0 = time1 - TICK_TIME;\n\n if (canRender)\n {\n // Account for numLoops overflow causing percent 1.\n float percentWithinTick = Min(1.f, float(time1 - time0)/TICK_TIME);\n GameDrawWithInterpolation(percentWithinTick);\n }\n}\nwhile (!bGameDone);\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
17,434
<p>I have been reading through the <a href="http://yosefk.com/c++fqa/" rel="noreferrer">C++ FAQ</a> and was curious about the <a href="http://yosefk.com/c++fqa/friend.html" rel="noreferrer"><code>friend</code></a> declaration. I personally have never used it, however I am interested in exploring the language. </p> <p>What is a good example of using <code>friend</code>?</p> <hr> <p>Reading the FAQ a bit longer I like the idea of the <code>&lt;&lt;</code> <code>&gt;&gt;</code> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?</p>
[ { "answer_id": 17443, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 9, "selected": true, "text": "friend friend class Child\n{\n//Mother class members can access the private parts of class Child.\nfriend class Mother;\n\npublic:\n\n string name( void );\n\nprotected:\n\n void setName( string newName );\n};\n" }, { "answer_id": 17505, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "operator << foo friend public private" }, { "answer_id": 17970, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 1, "selected": false, "text": "friend friend /////////////////////////\n// Header file\nclass MySingleton\n{\nprivate:\n // Private c-tor for Singleton pattern\n MySingleton() {}\n\n friend MySingleton& GetMySingleton();\n}\n\n// Accessor function - less verbose than having a \"GetInstance()\"\n// static function on the class\nMySingleton& GetMySingleton();\n\n\n/////////////////////////\n// Implementation file\nMySingleton& GetMySingleton()\n{\n static MySingleton theInstance;\n return theInstance;\n}\n" }, { "answer_id": 44985, "author": "Ray", "author_id": 456786, "author_profile": "https://Stackoverflow.com/users/456786", "pm_score": 2, "selected": false, "text": " Game\n / \\\n TwoPlayer SinglePlayer\n" }, { "answer_id": 53345, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 3, "selected": false, "text": "parent.addChild(child);\nchild.setParent(parent);\n class Parent;\n\nclass Object {\nprivate:\n void setParent(Parent&);\n\n friend void addChild(Parent& parent, Object& child);\n};\n\nclass Parent : public Object {\nprivate:\n void addChild(Object& child);\n\n friend void addChild(Parent& parent, Object& child);\n};\n\nvoid addChild(Parent& parent, Object& child) {\n if( &parent == &child ){ \n wetPants(); \n }\n parent.addChild(child);\n child.setParent(parent);\n}\n" }, { "answer_id": 362581, "author": "shash", "author_id": 11684, "author_profile": "https://Stackoverflow.com/users/11684", "pm_score": -1, "selected": false, "text": "class MyFoo\n{\nprivate:\n static void callback(void * data, void * clientData);\n void localCallback();\n ...\n};\n callback localCallback clientData class MyFoo\n{\n friend void callback(void * data, void * callData);\n void localCallback();\n}\n class MyFooPrivate;\nclass MyFoo\n{\n friend class MyFooPrivate;\npublic:\n MyFoo();\n // Public stuff\nprivate:\n MyFooPrivate _private;\n // Other private members as needed\n};\n class MyFooPrivate\n{\npublic:\n MyFoo *owner;\n // Your complexity here\n};\n\nMyFoo::MyFoo()\n{\n this->_private->owner = this;\n}\n" }, { "answer_id": 365349, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": false, "text": "friend namespace utils {\n class f {\n private:\n typedef int int_type;\n int_type value;\n\n public:\n // let's assume it doesn't only need .value, but some\n // internal stuff.\n friend f operator+(f const& a, f const& b) {\n // name resolution finds names in class-scope. \n // int_type is visible here.\n return f(a.value + b.value);\n }\n\n int getValue() const { return value; }\n };\n}\n\nint main() {\n utils::f a, b;\n std::cout << (a + b).getValue(); // valid\n}\n // possible policy used for flexible-class.\ntemplate<typename Derived>\nstruct Policy {\n void doSomething() {\n // casting this to Derived* requires us to see that we are a \n // base-class of Derived.\n some_type const& t = static_cast<Derived*>(this)->getSomething();\n }\n};\n\n// note, derived privately\ntemplate<template<typename> class SomePolicy>\nstruct FlexibleClass : private SomePolicy<FlexibleClass> {\n // we derive privately, so the base-class wouldn't notice that, \n // (even though it's the base itself!), so we need a friend declaration\n // to make the base a friend of us.\n friend class SomePolicy<FlexibleClass>;\n\n void doStuff() {\n // calls doSomething of the policy\n this->doSomething();\n }\n\n // will return useful information\n some_type getSomething();\n};\n" }, { "answer_id": 1388348, "author": "larsmoa", "author_id": 167251, "author_profile": "https://Stackoverflow.com/users/167251", "pm_score": 2, "selected": false, "text": "template<typename T>\nclass FriendIdentity {\npublic:\n typedef T me;\n};\n\n/**\n * A class to get access to protected stuff in unittests. Don't use\n * directly, use friendMe() instead.\n */\ntemplate<class ToFriend, typename ParentClass>\nclass Friender: public ParentClass\n{\npublic:\n Friender() {}\n virtual ~Friender() {}\nprivate:\n// MSVC != GCC\n#ifdef _MSC_VER\n friend ToFriend;\n#else\n friend class FriendIdentity<ToFriend>::me;\n#endif\n};\n\n/**\n * Gives access to protected variables/functions in unittests.\n * Usage: <code>friendMe(this, someprotectedobject).someProtectedMethod();</code>\n */\ntemplate<typename Tester, typename ParentClass>\nFriender<Tester, ParentClass> & \nfriendMe(Tester * me, ParentClass & instance)\n{\n return (Friender<Tester, ParentClass> &)(instance);\n}\n friendMe(this, someClassInstance).someProtectedFunction();\n" }, { "answer_id": 1388412, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 5, "selected": false, "text": "class c1 {\npublic:\n int x;\n};\n\nclass c2 {\npublic:\n int foo();\nprivate:\n int x;\n};\n\nclass c3 {\n friend int foo();\nprivate:\n int x;\n};\n c1 x c2 x foo c3 x c2 c2 c2 friend class c4 {\npublic:\n int getx();\n void setx(int x);\nprivate:\n int x;\n};\n" }, { "answer_id": 1388471, "author": "Gian Paolo Ghilardi", "author_id": 96081, "author_profile": "https://Stackoverflow.com/users/96081", "pm_score": 2, "selected": false, "text": " class Fred;\n\n class FredBase {\n private:\n friend class Fred;\n FredBase() { }\n };\n\n class Fred : private virtual FredBase {\n public:\n ...\n }; \n" }, { "answer_id": 9909272, "author": "Lubo Antonov", "author_id": 677131, "author_profile": "https://Stackoverflow.com/users/677131", "pm_score": 1, "selected": false, "text": "Point p;\ncout << p;\n friend ostream& operator<<(ostream& output, const Point& p);\n class A\n{\npublic:\n void need_your_data(B & myBuddy)\n {\n myBuddy.take_this_name(name_);\n }\nprivate:\n string name_;\n};\n\nclass B\n{\npublic:\n void print_buddy_name(A & myBuddy)\n {\n myBuddy.need_your_data(*this);\n }\n void take_this_name(const string & name)\n {\n cout << name;\n }\n}; \n" }, { "answer_id": 14078313, "author": "Ephemera", "author_id": 1618592, "author_profile": "https://Stackoverflow.com/users/1618592", "pm_score": 2, "selected": false, "text": "friend friend friend class Beer {\npublic:\n friend bool equal(Beer a, Beer b);\nprivate:\n // ...\n};\n equal(Beer, Beer) a b char *brand float percentAlcohol friend == operator friend public friends friends Mat2x2 Mat3x3 Mat4x4 Vec2 Vec3 Vec4 friend << >> == class Birds {\npublic:\n friend Birds operator +(Birds, Birds);\nprivate:\n int numberInFlock;\n};\n\n\nBirds operator +(Birds b1, Birds b2) {\n Birds temp;\n temp.numberInFlock = b1.numberInFlock + b2.numberInFlock;\n return temp;\n}\n friend" }, { "answer_id": 21599285, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 0, "selected": false, "text": "// friend functions\n#include <iostream>\nusing namespace std;\n\nclass Rectangle {\n int width, height;\n public:\n Rectangle() {}\n Rectangle (int x, int y) : width(x), height(y) {}\n int area() {return width * height;}\n friend Rectangle duplicate (const Rectangle&);\n};\n\nRectangle duplicate (const Rectangle& param)\n{\n Rectangle res;\n res.width = param.width*2;\n res.height = param.height*2;\n return res;\n}\n\nint main () {\n Rectangle foo;\n Rectangle bar (2,3);\n foo = duplicate (bar);\n cout << foo.area() << '\\n';\n return 0;\n}\n" }, { "answer_id": 36225178, "author": "Shiv", "author_id": 4843113, "author_profile": "https://Stackoverflow.com/users/4843113", "pm_score": 2, "selected": false, "text": "\"<<\" \"cout << pointobj\" \"operator <<()\" \"friend\" \"friend ostream &operator<<(ostream &cout, Point &pointobj);\" \"funcBridge()\" \"funcBridge()\" friend return_type funcBridge(A &a_obj, B & b_obj);" }, { "answer_id": 42187092, "author": "Francis Cugler", "author_id": 1757805, "author_profile": "https://Stackoverflow.com/users/1757805", "pm_score": 0, "selected": false, "text": "class ClubHouse {\npublic:\n friend class VIPMember; // VIP Members Have Full Access To Class\nprivate:\n unsigned nonMembers_;\n unsigned paidMembers_;\n unsigned vipMembers;\n\n std::vector<Member> members_;\npublic:\n ClubHouse() : nonMembers_(0), paidMembers_(0), vipMembers(0) {}\n\n addMember( const Member& member ) { // ...code } \n void updateMembership( unsigned memberID, Member::MembershipType type ) { // ...code }\n Amenity getAmenity( unsigned memberID ) { // ...code }\n\nprotected:\n void joinVIPEvent( unsigned memberID ) { // ...code }\n\n}; // ClubHouse\n class Member {\npublic:\n enum MemberShipType {\n NON_MEMBER_PAID_EVENT, // Single Event Paid (At Door)\n PAID_MEMBERSHIP, // Monthly - Yearly Subscription\n VIP_MEMBERSHIP, // Highest Possible Membership\n }; // MemberShipType\n\nprotected:\n MemberShipType type_;\n unsigned id_;\n Amenity amenity_;\npublic:\n Member( unsigned id, MemberShipType type ) : id_(id), type_(type) {}\n virtual ~Member(){}\n unsigned getId() const { return id_; }\n MemberShipType getType() const { return type_; }\n virtual void getAmenityFromClubHouse() = 0 \n};\n\nclass NonMember : public Member {\npublic:\n explicit NonMember( unsigned id ) : Member( id, MemberShipType::NON_MEMBER_PAID_EVENT ) {} \n\n void getAmenityFromClubHouse() override {\n Amenity = ClubHouse::getAmenity( this->id_ );\n }\n};\n\nclass PaidMember : public Member {\npublic:\n explicit PaidMember( unsigned id ) : Member( id, MemberShipType::PAID_MEMBERSHIP ) {}\n\n void getAmenityFromClubHouse() override {\n Amenity = ClubHouse::getAmenity( this->id_ );\n }\n};\n\nclass VIPMember : public Member {\npublic:\n friend class ClubHouse;\npublic:\n explicit VIPMember( unsigned id ) : Member( id, MemberShipType::VIP_MEMBERSHIP ) {}\n\n void getAmenityFromClubHouse() override {\n Amenity = ClubHouse::getAmenity( this->id_ );\n }\n\n void attendVIPEvent() {\n ClubHouse::joinVIPEvent( this->id );\n }\n};\n class Amenity{};\n" }, { "answer_id": 45748046, "author": "lixunhuan", "author_id": 2228340, "author_profile": "https://Stackoverflow.com/users/2228340", "pm_score": 2, "selected": false, "text": "friend" }, { "answer_id": 74651861, "author": "kaba", "author_id": 1566112, "author_profile": "https://Stackoverflow.com/users/1566112", "pm_score": 0, "selected": false, "text": "Vertex Edge Graph Vertex Edge graph.addVertex() graph.addEdge(aVertex, bVertex) Vertex Edge Graph graph.removeVertex(vertex) graph.removeEdge(edge) Vertex Edge Graph Vertex Edge Graph Graph Vertex Graph Graph Vertex Graph Vertex Graph Vertex Graph Vertex Vertex Graph Vertex graph.addVertex() Vertex Graph Graph Vertex Vertex Graph" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/716/" ]
17,483
<p>Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?</p> <pre><code>class Base { public: bool someGuaranteedResult() { return true; } }; class Child : public Base { public: bool someGuaranteedResult() { return false; /* Haha I broke things! */ } }; </code></pre> <p>Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.</p>
[ { "answer_id": 17485, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 0, "selected": false, "text": "Parent* obj = new Child();\n" }, { "answer_id": 17487, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": -1, "selected": false, "text": "virtual" }, { "answer_id": 1561974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "int foo() { return 1; }\n int foo() { return 2; }\n" }, { "answer_id": 16906116, "author": "moooeeeep", "author_id": 1025391, "author_profile": "https://Stackoverflow.com/users/1025391", "pm_score": 5, "selected": false, "text": "final class Base {\npublic:\n virtual bool someGuaranteedResult() final { return true; }\n};\n\nclass Child : public Base {\npublic:\n bool someGuaranteedResult() { return false; /* Haha I broke things! */ }\n};\n $ g++ test.cc -std=c++11\ntest.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’\ntest.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’\n sealed" }, { "answer_id": 38759520, "author": "Abhay Bhave", "author_id": 5974168, "author_profile": "https://Stackoverflow.com/users/5974168", "pm_score": -1, "selected": false, "text": "final" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
17,500
<p>The <code>System.Windows.Threading.DispatcherObject</code> class (which <code>DependencyObject</code> is based on) contains a useful function, called <code>CheckAccess()</code>, that determines whether or not the code is running on the UI thread.</p> <p>When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor <code>VerifyAccess()</code>, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an <code>EditorBrowsable(EditorBrowsableState.Never)</code> attribute attached to it. The <code>Dispatcher</code> class, which is used by <code>DispatcherObject</code>, has the same attribute attached to <code>CheckAccess()</code> and <code>VerifyAccess()</code>:</p> <pre><code>public abstract class DispatcherObject { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... [EditorBrowsable(EditorBrowsableState.Advanced)] public Dispatcher Dispatcher { get; } } public sealed class Dispatcher { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... } </code></pre> <p>I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they <code>protected</code> (or <code>internal</code>, like some of the most useful methods in the WPF)?</p>
[ { "answer_id": 17507, "author": "Eric Haskins", "author_id": 100, "author_profile": "https://Stackoverflow.com/users/100", "pm_score": 0, "selected": false, "text": "[EditorBrowsable(EditorBrowsableState.Never)]\npublic bool CheckAccess()\n{\n//CODE\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2074/" ]