qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
333,620
<p>I need to add user roles and permission system into my web application built using PHP/MySQL. I want to have this functionality: </p> <ol> <li>One root user can create sub-roots, groups, rules and normal users( all privileges) .</li> <li>Sub-roots can create only rules, permissions and users for his/her own group ( no groups).</li> <li>A user can access either content created by him or his group, based on the permission assigned to him, by group root.</li> </ol> <p>I need the system to be flexible enough, so that new roles and permissions are assigned to content.</p> <p>I have a <code>users</code> table storing group key along with other information. Currently I am using two feilds in each content table i.e. <code>createdBy</code> and <code>CreatedByGroup</code>, and using that as the point whether a certain user has permissions. But its not flexible enough, because for every new content, I have to go throug all data updates and permission updates. Please help me by discussing your best practices for schema design.</p>
[ { "answer_id": 333668, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 3, "selected": false, "text": "PermissionMaster(FormName)\n PermissionChild(PermissionMasterID, PermissionName, Desc, DefaultValue, DependOn) PermissionGroupChild(GroupID, PermissionChildID, Allow)\n" }, { "answer_id": 25643919, "author": "Suresh Kamrushi", "author_id": 1900692, "author_profile": "https://Stackoverflow.com/users/1900692", "pm_score": 5, "selected": false, "text": "CREATE TABLE IF NOT EXISTS `permission` (\n `bit` int(11) NOT NULL,\n `name` varchar(50) NOT NULL,\n PRIMARY KEY (`bit`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n INSERT INTO `permission` (`bit`, `name`) VALUES\n(1, 'User-Add'),\n(2, 'User-Edit'),\n(4, 'User-Delete'),\n(8, 'User-View'),\n(16, 'Blog-Add'),\n(32, 'Blog-Edit'),\n(64, 'Blog-Delete'),\n(128, 'Blog-View');\n CREATE TABLE IF NOT EXISTS `user` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(50) NOT NULL,\n `role` int(11) NOT NULL,\n `created_date` datetime NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n INSERT INTO `user` (`id`, `name`, `role`, `created_date`)\n VALUES (NULL, 'Ketan', '65', '2013-01-09 00:00:00'),\n (NULL, 'Mehata', '132', '2013-01-09 00:00:00');\n SELECT permission.bit,permission.name \n FROM user LEFT JOIN permission ON user.role & permission.bit\n WHERE user.id = 1\n User-Add - 1\nBlog-Delete - 64\n SELECT * FROM `user` \n WHERE role & (select bit from permission where name='user-edit')\n" }, { "answer_id": 46278154, "author": "Meloman", "author_id": 2282880, "author_profile": "https://Stackoverflow.com/users/2282880", "pm_score": 2, "selected": false, "text": "INSERT INTO `permission` (`bit`, `name`) VALUES\n(1, 'add-yes'),\n(2, 'add-no'),\n(4, 'edit-yes'),\n(8, 'edit-no'),\n(16, 'del-yes'),\n(32, 'del-no'),\n(64, 'view-yes'),\n(128, 'view-no');\n 00000000 00 add-yes add-no 01010110 01 add-no" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29656/" ]
333,629
<p>UDP doesnot sends any ack back, but will it send any response?</p> <p>I have set up client server UDP program. If I give client to send data to non existent server then will client receive any response?</p> <p>My assumption is as;</p> <p>Client -->Broadcast server address (ARP) Server --> Reply to client with its mac address(ARP) Client sends data to server (UDP)</p> <p>In any case Client will only receive ARP response. If server exists or not it will not get any UDP response? </p> <p>Client is using sendto function to send data. We can get error information after sendto call.</p> <p>So my question is how this info is available when client doesn't get any response. Error code can be get from WSAGetLastError.</p> <p>I tried to send data to non existent host and sendto call succeeded . As per documentation it should fail with return value SOCKET_ERROR.</p> <p>Any thoughts??</p>
[ { "answer_id": 7426932, "author": "David Schwartz", "author_id": 721269, "author_profile": "https://Stackoverflow.com/users/721269", "pm_score": 3, "selected": false, "text": "sendto sendto getsockopt" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
333,630
<p>I have a single line CEikLabel in my application that needs to scroll text.</p> <p>The simple solution that comes to mind (but possibly naive) would be something like..</p> <pre><code>[begin pseduo code] on timer.fire { set slightly shifted text in label redraw label } start timer [end pseudo code] </code></pre> <p>Using a CPeriodic class as the timer and label.DrawDeferred() on each update.</p> <p>Do you think this is the best way, it may be rather inefficient redrawing the label two or three times a second.. but is there any other way?</p> <p>Thanks :)</p>
[ { "answer_id": 7426932, "author": "David Schwartz", "author_id": 721269, "author_profile": "https://Stackoverflow.com/users/721269", "pm_score": 3, "selected": false, "text": "sendto sendto getsockopt" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33604/" ]
333,632
<p>I'm making some changes to a legacy classic ASP application. I've made the changes locally, and now I want to copy the changed files to the server. At the same time, I need to download the Access database, add some fields to some tables, and upload it again. For this reason, I need to be able to stop visitors from modifying the database while this is happening.</p> <p>My main question is, what is the best way to setup a quick "Down for Maintenance" page that will be shown immediately and no matter which page the visitor requests. The application is already established, so I'd rather an answer that didn't require me to rework the application's architecture.</p> <p>My second question (maybe this should be a separate question): Is there a better way to add fields to a db table than to copy it down, modify, and stick it up again? Please forgive if that's a dumb question - I'm new to ASP - new to Windows too.</p> <p>I only have FTP access to the remote server.</p> <p>Thanks.</p>
[ { "answer_id": 1441999, "author": "brianary", "author_id": 54323, "author_profile": "https://Stackoverflow.com/users/54323", "pm_score": 0, "selected": false, "text": "Application(\"Offline\")= True\n If VarType(Application(\"Offline\")) = vbBoolean Then If Application(\"Offline\") Then Response.Redirect \"App_Offline.htm\"\n Set fso= Server.CreateObject(\"Scripting.FileSystemObject\")\nApplication(\"Offline\")= fso.FileExists(Server.MapPath(\"App_Offline.htm\"))\nSet fso= Nothing\n" }, { "answer_id": 47867932, "author": "Shaista", "author_id": 9113227, "author_profile": "https://Stackoverflow.com/users/9113227", "pm_score": 0, "selected": false, "text": "\n <?xml version=\"1.0\"?>\n <configuration>\n <system.webServer>\n <modules runAllManagedModulesForAllRequests=\"true\" />\n </system.webServer>\n </configuration>" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31092/" ]
333,634
<p>Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?</p> <p>My motivation is to conserve bandwidth.</p> <p>If not, is it possible to fake it?</p>
[ { "answer_id": 333657, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 8, "selected": true, "text": "function UrlExists(url, callback)\n{\n var http = new XMLHttpRequest();\n http.open('HEAD', url);\n http.onreadystatechange = function() {\n if (this.readyState == this.DONE) {\n callback(this.status != 404);\n }\n };\n http.send();\n}\n onload onerror ontimeout onreadystatechange" }, { "answer_id": 333659, "author": "adam", "author_id": 33604, "author_profile": "https://Stackoverflow.com/users/33604", "pm_score": -1, "selected": false, "text": "getAllResponseHeaders();\ngetResponseHeader(\"header-name\")\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6691/" ]
333,655
<p>I've got a name of a method: "Garden.Plugins.Code.Beta.Business.CalculateRest"</p> <p>How to run it? I think about this fancy reflection based solution like RunMethod(string MethodName)</p>
[ { "answer_id": 333671, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "BindingFlags.Public | BindingFlags.Static" }, { "answer_id": 333719, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "Type.GetType(\"Garden.Plugins.Code.Beta.Business\")\n .GetMethod(\"CalculateRest\").Invoke(myInstanceOfTheType, param1, param2);\n Type.GetType(\"Garden.Plugins.Code.Beta.Business\")\n .GetMethod(\"CalculateRest\").Invoke(null, param1, param2);\n" }, { "answer_id": 333772, "author": "Sean", "author_id": 26095, "author_profile": "https://Stackoverflow.com/users/26095", "pm_score": 2, "selected": false, "text": "class X\n{\n class Y\n {\n // etc\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38940/" ]
333,664
<p>I can find lots of information on how Long Polling works (For example, <a href="http://jfarcand.wordpress.com/2007/05/15/new-adventures-in-comet-polling-long-polling-or-http-streaming-with-ajax-which-one-to-choose/" rel="noreferrer">this</a>, and <a href="http://en.wikipedia.org/wiki/Comet_(programming)#Ajax_with_long_polling" rel="noreferrer">this</a>), but no <em>simple</em> examples of how to implement this in code.</p> <p>All I can find is <a href="http://code.google.com/p/cometd/" rel="noreferrer">cometd</a>, which relies on the Dojo JS framework, and a fairly complex server system..</p> <p>Basically, how would I use Apache to serve the requests, and how would I write a simple script (say, in PHP) which would "long-poll" the server for new messages?</p> <p>The example doesn't have to be scaleable, secure or complete, it just needs to work!</p>
[ { "answer_id": 333702, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "while (!hasNewData())\n usleep(50);\n\noutputNewData();\n hasNewData()" }, { "answer_id": 333884, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 10, "selected": true, "text": "msgsrv.php <?php\nif(rand(1,3) == 1){\n /* Fake an error */\n header(\"HTTP/1.0 404 Not Found\");\n die();\n}\n\n/* Send a string after a random number of seconds (2-10) */\nsleep(rand(2,10));\necho(\"Hi! Have a random number: \" . rand(1,10));\n?>\n msg_srv.php msgsrv.php #messages setTimeout() msgsrv.php #messages long_poller.htm <html>\n<head>\n <title>BargePoller</title>\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n\n <style type=\"text/css\" media=\"screen\">\n body{ background:#000;color:#fff;font-size:.9em; }\n .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}\n .old{ background-color:#246499;}\n .new{ background-color:#3B9957;}\n .error{ background-color:#992E36;}\n </style>\n\n <script type=\"text/javascript\" charset=\"utf-8\">\n function addmsg(type, msg){\n /* Simple helper to add a div.\n type is the name of a CSS class (old/new/error).\n msg is the contents of the div */\n $(\"#messages\").append(\n \"<div class='msg \"+ type +\"'>\"+ msg +\"</div>\"\n );\n }\n\n function waitForMsg(){\n /* This requests the url \"msgsrv.php\"\n When it complete (or errors)*/\n $.ajax({\n type: \"GET\",\n url: \"msgsrv.php\",\n\n async: true, /* If set to non-async, browser shows page as \"Loading..\"*/\n cache: false,\n timeout:50000, /* Timeout in ms */\n\n success: function(data){ /* called when request to barge.php completes */\n addmsg(\"new\", data); /* Add response to a .msg div (with the \"new\" class)*/\n setTimeout(\n waitForMsg, /* Request next message */\n 1000 /* ..after 1 seconds */\n );\n },\n error: function(XMLHttpRequest, textStatus, errorThrown){\n addmsg(\"error\", textStatus + \" (\" + errorThrown + \")\");\n setTimeout(\n waitForMsg, /* Try again after.. */\n 15000); /* milliseconds (15seconds) */\n }\n });\n };\n\n $(document).ready(function(){\n waitForMsg(); /* Start the inital request */\n });\n </script>\n</head>\n<body>\n <div id=\"messages\">\n <div class=\"msg old\">\n BargePoll message requester!\n </div>\n </div>\n</body>\n</html>\n" }, { "answer_id": 338685, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 5, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<!-- Copyright (c) 2008 Dustin Sallings <dustin+html@spy.net> -->\n<html lang=\"en\">\n <head>\n <title>slosh chat</title>\n <script type=\"text/javascript\"\n src=\"http://code.jquery.com/jquery-latest.js\"></script>\n <link title=\"Default\" rel=\"stylesheet\" media=\"screen\" href=\"style.css\" />\n </head>\n\n <body>\n <h1>Welcome to Slosh Chat</h1>\n\n <div id=\"messages\">\n <div>\n <span class=\"from\">First!:</span>\n <span class=\"msg\">Welcome to chat. Please don't hurt each other.</span>\n </div>\n </div>\n\n <form method=\"post\" action=\"#\">\n <div>Nick: <input id='from' type=\"text\" name=\"from\"/></div>\n <div>Message:</div>\n <div><textarea id='msg' name=\"msg\"></textarea></div>\n <div><input type=\"submit\" value=\"Say it\" id=\"submit\"/></div>\n </form>\n\n <script type=\"text/javascript\">\n function gotData(json, st) {\n var msgs=$('#messages');\n $.each(json.res, function(idx, p) {\n var from = p.from[0]\n var msg = p.msg[0]\n msgs.append(\"<div><span class='from'>\" + from + \":</span>\" +\n \" <span class='msg'>\" + msg + \"</span></div>\");\n });\n // The jQuery wrapped msgs above does not work here.\n var msgs=document.getElementById(\"messages\");\n msgs.scrollTop = msgs.scrollHeight;\n }\n\n function getNewComments() {\n $.getJSON('/topics/chat.json', gotData);\n }\n\n $(document).ready(function() {\n $(document).ajaxStop(getNewComments);\n $(\"form\").submit(function() {\n $.post('/topics/chat', $('form').serialize());\n return false;\n });\n getNewComments();\n });\n </script>\n </body>\n</html>\n" }, { "answer_id": 1426901, "author": "xoblau", "author_id": 173669, "author_profile": "https://Stackoverflow.com/users/173669", "pm_score": 3, "selected": false, "text": "1000 /* ..after 1 seconds */\n \"1000\"); /* ..after 1 seconds */\n django-admin.py startproject lp\n python manage.py startapp msgsrv\n import os.path\nPROJECT_DIR = os.path.dirname(__file__)\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_DIR, 'templates'),\n)\n from django.views.generic.simple import direct_to_template\nfrom lp.msgsrv.views import retmsg\n\nurlpatterns = patterns('',\n (r'^msgsrv\\.php$', retmsg),\n (r'^long_poller\\.htm$', direct_to_template, {'template': 'long_poller.htm'}),\n)\n from random import randint\nfrom time import sleep\nfrom django.http import HttpResponse, HttpResponseNotFound\n\ndef retmsg(request):\n if randint(1,3) == 1:\n return HttpResponseNotFound('<h1>Page not found</h1>')\n else:\n sleep(randint(2,10))\n return HttpResponse('Hi! Have a random number: %s' % str(randint(1,10)))\n" }, { "answer_id": 5739159, "author": "Ryan Henderson", "author_id": 718220, "author_profile": "https://Stackoverflow.com/users/718220", "pm_score": 3, "selected": false, "text": "abstract class LongPoller {\n\n protected $sleepTime = 5;\n protected $timeoutTime = 30;\n\n function __construct() {\n }\n\n\n function setTimeout($timeout) {\n $this->timeoutTime = $timeout;\n }\n\n function setSleep($sleep) {\n $this->sleepTime = $sleepTime;\n }\n\n\n public function run() {\n $data = NULL;\n $timeout = 0;\n\n set_time_limit($this->timeoutTime + $this->sleepTime + 15);\n\n //Query database for data\n while($data == NULL && $timeout < $this->timeoutTime) {\n $data = $this->loadData();\n if($data == NULL){\n\n //No new orders, flush to notify php still alive\n flush();\n\n //Wait for new Messages\n sleep($this->sleepTime);\n $timeout += $this->sleepTime;\n }else{\n echo $data;\n flush();\n }\n }\n\n }\n\n\n protected abstract function loadData();\n\n}\n" }, { "answer_id": 13777448, "author": "Jasdeep Khalsa", "author_id": 1365289, "author_profile": "https://Stackoverflow.com/users/1365289", "pm_score": 4, "selected": false, "text": "Content-type: multipart/x-mixed-replace <?\n\nheader('Content-type: multipart/x-mixed-replace; boundary=endofsection');\n\n// Keep in mind that the empty line is important to separate the headers\n// from the content.\necho 'Content-type: text/plain\n\nAfter 5 seconds this will go away and a cat will appear...\n--endofsection\n';\nflush(); // Don't forget to flush the content to the browser.\n\n\nsleep(5);\n\n\necho 'Content-type: image/jpg\n\n';\n\n$stream = fopen('cat.jpg', 'rb');\nfpassthru($stream);\nfclose($stream);\n\necho '\n--endofsection\n';\n" }, { "answer_id": 19106928, "author": "ideawu", "author_id": 427640, "author_profile": "https://Stackoverflow.com/users/427640", "pm_score": 2, "selected": false, "text": "var comet = new iComet({\n sign_url: 'http://' + app_host + '/sign?obj=' + obj,\n sub_url: 'http://' + icomet_host + '/sub',\n callback: function(msg){\n // on server push\n alert(msg.content);\n }\n});\n" }, { "answer_id": 50002668, "author": "sp3c1", "author_id": 4503893, "author_profile": "https://Stackoverflow.com/users/4503893", "pm_score": 0, "selected": false, "text": "const http = require('http');\n\nconst server = http.createServer((req, res) => {\n SomeVeryLongAction(res);\n});\n\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\n\nserver.listen(8000);\n\n// the long running task - simplified to setTimeout here\n// but can be async, wait from websocket service - whatever really\nfunction SomeVeryLongAction(response) {\n setTimeout(response.end, 10000);\n}\n response <Response> response.end() const http = require('http');\nvar responsesArray = [];\n\nconst server = http.createServer((req, res) => {\n // not dealing with connection\n // put it on stack (array in this case)\n responsesArray.push(res);\n // end this is where normal api flow ends\n});\n\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\n\n// and eventually when we are ready to resolve\n// that if is there just to ensure you actually \n// called endpoint before the timeout kicks in\nfunction SomeVeryLongAction() {\n if ( responsesArray.length ) {\n let localResponse = responsesArray.shift();\n localResponse.end();\n }\n}\n\n// simulate some action out of endpoint flow\nsetTimeout(SomeVeryLongAction, 10000);\nserver.listen(8000);\n id" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
333,665
<p>I tried the following code to get an alert upon closing a browser window:</p> <pre><code>window.onbeforeunload = confirmExit; function confirmExit() { return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?"; } </code></pre> <p>It works, but if the page contains one hyperlink, clicking on that hyperlink raises the same alert. I need to show the alert only when I close the browser window and not upon clicking hyperlinks.</p>
[ { "answer_id": 333672, "author": "M. Utku ALTINKAYA", "author_id": 40948, "author_profile": "https://Stackoverflow.com/users/40948", "pm_score": 6, "selected": true, "text": "$(function () {\n $(\"a\").click(function {\n window.onbeforeunload = null;\n });\n});\n" }, { "answer_id": 333673, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 6, "selected": false, "text": "<html>\n <head>\n <script type=\"text/javascript\">\n var hook = true;\n window.onbeforeunload = function() {\n if (hook) {\n return \"Did you save your stuff?\"\n }\n }\n function unhook() {\n hook=false;\n }\n </script>\n </head>\n <body>\n <!-- this will ask for confirmation: -->\n <a href=\"http://google.com\">external link</a>\n\n <!-- this will go without asking: -->\n <a href=\"anotherPage.html\" onClick=\"unhook()\">internal link, un-hooked</a>\n </body>\n</html>\n" }, { "answer_id": 34755194, "author": "Michał Perłakowski", "author_id": 3853934, "author_profile": "https://Stackoverflow.com/users/3853934", "pm_score": 3, "selected": false, "text": "beforeunload window beforeunload window true click document a event.target.tagName true submit document let disableConfirmation = false;\nwindow.addEventListener('beforeunload', event => {\n const confirmationText = 'Are you sure?';\n if (!disableConfirmation) {\n event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+\n return confirmationText; // Gecko, WebKit, Chrome <34\n } else {\n // Set flag back to false, just in case\n // user stops loading page after clicking a link.\n disableConfirmation = false;\n }\n});\ndocument.addEventListener('click', event => {\n if (event.target.tagName.toLowerCase() === 'a') {\n disableConfirmation = true;\n }\n});\ndocument.addEventListener('submit', event => {\n disableConfirmation = true;\n}); <p><a href=\"https://stacksnippets.net/\">google.com</a></p>\n<form action=\"https://stacksnippets.net/\"><button type=\"submit\">Submit</button></form>\n<p>Try clicking the link or the submit button. The confirmation dialog won't be displayed.</p>\n<p>Try reloading the frame (right click -> \"Reload frame\" in Chrome). You will see a confirmation dialog.</p> event.returnValue beforeunload return beforeunload" }, { "answer_id": 62790669, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "let disableConfirmation = false;\nwindow.addEventListener('beforeunload', event => {\n const confirmationText = 'Are you sure?';\n if (!disableConfirmation) {\n event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+\n return confirmationText; // Gecko, WebKit, Chrome <34\n } else {\n // Set flag back to false, just in case\n // user stops loading page after clicking a link.\n disableConfirmation = false;\n }\n});\n $(window).on('unload', function() {\n // async: false will make the AJAX synchronous in case you're using jQuery\n axios\n .get('ajax_url')\n .then(response => {});\n });\n navigator.sendBeacon(url, data);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42348/" ]
333,682
<p><strong><a href="http://en.wikipedia.org/wiki/Anti-pattern" rel="noreferrer">anti-pattern</a></strong> : there must be at least two key elements present to formally distinguish an actual anti-pattern from a simple bad habit, bad practice, or bad idea:</p> <ul> <li>Some repeated pattern of action, process or structure that initially appears to be beneficial, but ultimately produces more bad consequences than beneficial results, and</li> <li>A refactored solution that is clearly documented, proven in actual practice and repeatable.</li> </ul> <p>Vote for the TDD anti-pattern that you have seen "in the wild" one time too many.<br> <a href="http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/" rel="noreferrer">The blog post by James Carr</a> and <a href="http://tech.groups.yahoo.com/group/testdrivendevelopment/message/20745" rel="noreferrer">Related discussion on testdrivendevelopment yahoogroup</a></p> <p>If you've found an 'unnamed' one.. post 'em too. <strong>One post per anti-pattern please</strong> to make the votes count for something.</p> <p><em>My vested interest is to find the top-n subset so that I can discuss 'em in a lunchbox meet in the near future.</em></p>
[ { "answer_id": 333814, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 6, "selected": false, "text": "teardown()" }, { "answer_id": 333820, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 5, "selected": false, "text": "run()" }, { "answer_id": 334026, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "[Test]\npublic void ShouldNotThrow()\n{\n DoSomethingThatShouldNotThrowAnException();\n}\n" }, { "answer_id": 334051, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 5, "selected": false, "text": "[Test]\n[ExpectedException(typeof(Exception))]\npublic void ItShouldThrowDivideByZeroException()\n{\n // some code that throws another exception yet passes the test\n}\n" }, { "answer_id": 1526583, "author": "Reverend Gonzo", "author_id": 84378, "author_profile": "https://Stackoverflow.com/users/84378", "pm_score": 4, "selected": false, "text": "class TD_SomeClass {\n public void testAdd() {\n assertEquals(1+1, 2);\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
333,687
<p>My function iterates through every node of an instance of an <code>XMLDocument</code>. It checks to see if the current node's name is in a lookup list. If it is, it applies appropriate validation to the value of the current node.</p> <p>When the validation method indicates that the value has been changed, I want to replace the value in the original document with the updated value.</p> <p>I think the easiest way to achieve this might be to write out to an <code>XMLTextWriter</code> as I process each node in the original <code>XMLDocument</code>, either writing out the original or modified node and value as appropriate. This method would rely on determining whether the current node has any children, or is a stand-alone node.</p> <p>Is there a better way I could update the values in the original document? I need to end up with the complete <code>XMLDocument</code>, but with updated node values, where appropriate.</p> <p>Thanks in advance.</p>
[ { "answer_id": 333718, "author": "xan", "author_id": 15667, "author_profile": "https://Stackoverflow.com/users/15667", "pm_score": 3, "selected": true, "text": ".InnerText\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7703/" ]
333,690
<p>Every tutorial or explanation of REST just goes too complicated too quickly - the learning curve rises so fast after the initial explanation of CRUD and the supposed simplicity over SOAP. Why can't people write decent tutorials anymore!</p> <p>I'm looking at Restlet - and its not the best, there are things missing in the tutorial and the language/grammar is a bit confusing and unclear. It has took me hours to untangle their First Steps tutorial (with the help of another Java programmer!)</p> <p><strong>RESTlet Tutorial Comments</strong></p> <p>Overall I'm not sure exactly who the tutorial was aimed at - because there is a fair degree of assumed knowledge all round, so coming into REST and Restlet framework cold leaves you with a lot of 'catchup work' to do, and re-reading paragraphs over and over again.</p> <ol> <li><p>We had difficulty working out that the jars had to be in copied into the correct lib folder. </p></li> <li><p>Problems with web.xml creating a HTTP Status 500 error - </p></li> </ol> <blockquote> <p>The server encountered an internal error () that prevented it from fulfilling this request</p> </blockquote> <p>, the tutorial says: </p> <blockquote> <p>"Create a new Servlet Web application as usual, add a "com.firstStepsServlet" package and put the resource and application classes in."</p> </blockquote> <p>This means that your fully qualified name for your class <strong>FirstStepsApplication</strong> is <strong>com.firstStepsServlet.FirstStepsApplication</strong>, so we had to alter web.xml to refer to the correct class e.g:</p> <p>original:</p> <pre><code>&lt;param-value&gt; firstStepsServlet.FirstStepsApplication &lt;/param-value&gt; </code></pre> <p>should be:</p> <pre><code>&lt;param-value&gt; com.firstStepsServlet.FirstStepsApplication &lt;/param-value&gt; </code></pre> <hr> <p><strong>Conclusion</strong></p> <p>I was under the impression that the concepts of REST were supposed to be much simpler than SOAP - but it seems just as bad if not more complicated - don't get it at all! grrrr</p> <p>Any good links - much appreciated.</p>
[ { "answer_id": 4084583, "author": "PIXAR", "author_id": 495573, "author_profile": "https://Stackoverflow.com/users/495573", "pm_score": 3, "selected": false, "text": "// Outputting the content of a Web page \nnew ClientResource(\"http://\").get().write(System.out); \n // Create the client resource \nClientResource resource = new ClientResource(\"http://www.restlet.org\"); \n\n// Customize the referrer property \nresource.setReferrerRef(\"http://www.mysite.org\"); \n\n// Write the response entity on the console \nresource.get().write(System.out); \n public class Part03 extends ServerResource { \n\n public static void main(String[] args) throws Exception { \n // Create the HTTP server and listen on port 8182 \n new Server(Protocol.HTTP, 8182, Part03.class).start(); \n } \n\n @Get \n public String toString() { \n return \"hello, world\"; \n } \n\n} \n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ]
333,693
<p>In a world where IE didn't exist, what things would be easier, less hacky, less buggy and generally more used.</p> <p>What could the internet have been if all features were available cross browser?</p> <p>List one point per post.</p> <p>This is community wiki, so feel free to amend the question/answers for clarity.</p>
[ { "answer_id": 333699, "author": "adam", "author_id": 33604, "author_profile": "https://Stackoverflow.com/users/33604", "pm_score": 2, "selected": false, "text": "Web Programming\n" }, { "answer_id": 333734, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 2, "selected": false, "text": "display:table :focus" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
333,706
<p>There is one thing that I do not understand... </p> <p>Imagine you have a <strong>text</strong> = "hello world" and you want to split it.</p> <p>In some places I see people that want to split the <strong>text</strong> doing:</p> <pre><code>string.split(text) </code></pre> <p>In other places I see people just doing:</p> <pre><code>text.split() </code></pre> <p>What’s the difference? Why you do in one way or in the other way? Can you give me a theory explanation about that?</p>
[ { "answer_id": 333715, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "string.split(stringobj) string stringobj.split() stringobj string" }, { "answer_id": 333727, "author": "csl", "author_id": 21028, "author_profile": "https://Stackoverflow.com/users/21028", "pm_score": 5, "selected": true, "text": ">>> import string\n>>> help(string.split)\nHelp on function split in module string:\n\nsplit(s, sep=None, maxsplit=-1)\n split(s [,sep [,maxsplit]]) -> list of strings\n\n Return a list of the words in the string s, using sep as the\n delimiter string. If maxsplit is given, splits at no more than\n maxsplit places (resulting in at most maxsplit+1 words). If sep\n is not specified or is None, any whitespace string is a separator.\n\n (split and splitfields are synonymous)\n\n>>> help(\"\".split)\nHelp on built-in function split:\n\nsplit(...)\n S.split([sep [,maxsplit]]) -> list of strings\n\n Return a list of the words in the string S, using sep as the\n delimiter string. If maxsplit is given, at most maxsplit\n splits are done. If sep is not specified or is None, any\n whitespace string is a separator.\n" }, { "answer_id": 334013, "author": "babbageclunk", "author_id": 38851, "author_profile": "https://Stackoverflow.com/users/38851", "pm_score": 3, "selected": false, "text": "str 'a b c'.split()\nstr.split('a b c')\n\n# both return ['a', 'b', 'c']\n str.split s.split str str.split self" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41795/" ]
333,729
<p>I want to include a js file depending on the value of the current Locale. I have tried to access it from JSP as follows: </p> <pre><code>&lt;%@ page import="java.util.Locale" %&gt; &lt;% if( ((Locale) pageContext.getAttribute("org.apache.struts.action.LOCALE",PageContext.REQUEST_SCOPE)).getLanguage().equals("de")) { %&gt; &lt;script src="../themes/administration/js/languages/i18nDE.js" type="text/javascript"&gt; &lt;/script&gt; &lt;% } else { %&gt; &lt;script src="../themes/administration/js/languages/i18nEN.js" type="text/javascript"&gt; &lt;/script&gt; &lt;% } %&gt; </code></pre> <p>However, I am getting a <code>java.lang.NullPointerException</code> because <code>pageContext.getAttribute("org.apache.struts.action.LOCALE",PageContext.REQUEST_SCOPE)</code> is <code>NULL</code>. </p> <p>Does anyone knows how I can solve this?</p>
[ { "answer_id": 333915, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "org.apache.struts.action.LOCALE org.apache.struts.Globals.LOCALE_KEY LOCALE_KEY org.apache.struts.action.LOCALE org.apache.struts.Global.LOCALE_KEY LOCALE Request LOCALE_KEY PageContext.SESSION_SCOPE" }, { "answer_id": 334018, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 0, "selected": false, "text": "pageContext.getAttribute(\"org.apache.struts.action.LOCALE\",PageContext.SESSION_SCOPE) \n pageContext.getAttribute(\"org.apache.struts.action.LOCALE\",PageContext.REQUEST_SCOPE)\n" }, { "answer_id": 352628, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<%@page import=\"java.util.Locale\"%>\n<%@page import=\"org.apache.struts.Globals\"%>\n\n\n<%Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);\nif (locale.getLanguage().equals(\"fr\")) {%>\n <script language=\"JavaScript\" src=\"lib/js/dateofday.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"<%=request.getContextPath() %>/lib/js/jscalendar-1.0/lang/calendar-fr.js\"></script>\n<%} else {%>\n <script language=\"JavaScript\" src=\"lib/js/dateofday-en.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"<%=request.getContextPath() %>/lib/js/jscalendar-1.0/lang/calendar-en.js\"></script>\n<%}%>\n" }, { "answer_id": 670605, "author": "Faisal Feroz", "author_id": 62848, "author_profile": "https://Stackoverflow.com/users/62848", "pm_score": 2, "selected": false, "text": "Locale locale = (locale)request.getSession().getAttribute(Globals.LOCALE_KEY);\n" }, { "answer_id": 1710176, "author": "dawez", "author_id": 112106, "author_profile": "https://Stackoverflow.com/users/112106", "pm_score": 4, "selected": false, "text": "<c:set var=\"localeCode\" value=\"${pageContext.response.locale}\" />\n ${localeCode} localeCode <%\n Object ob_localeCode = pageContext.getAttribute(\"localeCode\");\n if (ob_localeCode != null) {\n String currentLanguageCode = (String) ob_localeCode;\n }\n //more code\n%>\n <c:set var=\"localeCode\" value=\"${pageContext.response.locale}\" />\n<c:choose>\n <c:when test=\"$localecode == 'de' }\"> \n <script src=\"../themes/administration/js/languages/i18nDE.js\" type=\"text/javascript\"> </script>\n </c:when>\n <c:otherwise>\n <script src=\"../themes/administration/js/languages/i18nEN.js\" type=\"text/javascript\"> </script>\n </c:otherwise>\n</c:choose>\n <c:set var=\"localeCode\" value=\"${fn:toUpperCase(pageContext.response.locale)}\" />\n<c:set var=\"availLanguages\" value=\"EN,DE\" />\n<c:if test=\"${!fn:contains(availLanguages,localeCode)}\">\n <c:set var=\"localeCode\" value=\"EN\" />\n</c:if>\n\n<script src=\"../themes/administration/js/languages/i18n{$localeCode}.js\" type=\"text/javascript\"> </script>\n" }, { "answer_id": 2594485, "author": "Carles Barrobés", "author_id": 166761, "author_profile": "https://Stackoverflow.com/users/166761", "pm_score": 1, "selected": false, "text": "${sessionScope[\"org.apache.struts2.action.LOCALE\"]}\n <c:out value='${sessionScope[\"org.apache.struts2.action.LOCALE\"]}'/>\n" }, { "answer_id": 6830750, "author": "sunil", "author_id": 863532, "author_profile": "https://Stackoverflow.com/users/863532", "pm_score": 3, "selected": false, "text": "<s:if test=\"#request.locale.language=='us'\">\n <s:select name=\"gender\" list=\"#{'M':'Male','F':'female'}\" ></s:select>\n </s:if>\n" }, { "answer_id": 8120379, "author": "jeremy", "author_id": 1045407, "author_profile": "https://Stackoverflow.com/users/1045407", "pm_score": 0, "selected": false, "text": "locale getLocale <s:hidden name=\"locale\"/> <s:property value\"%{locale}\"/> ${pageContext.response.locale}" }, { "answer_id": 15607646, "author": "PbxMan", "author_id": 1652451, "author_profile": "https://Stackoverflow.com/users/1652451", "pm_score": 1, "selected": false, "text": "<%=request.getLocale()%>\n Struts2 Locale: <s:property value=\"#request.locale\"/>\n <s:url id=\"localeDE\" namespace=\"/\">\n <s:param name=\"request_locale\" >de</s:param>\n</s:url>\n<s:a href=\"%{localeDE}\" >German</s:a>\n" }, { "answer_id": 23241972, "author": "Thilina Rubasingha", "author_id": 1594389, "author_profile": "https://Stackoverflow.com/users/1594389", "pm_score": 1, "selected": false, "text": "<s:if test='locale.toString() == \"si\"'>\n <script src=\"../themes/administration/js/languages/i18nDE.js\" type=\"text/javascript\"> </script>\n</s:if>\n<s:elseif test='locale.toString() == \"ta\"'>\n <script src=\"../themes/administration/js/languages/i18nEN.js\" type=\"text/javascript\"> </script>\n</s:elseif>\n<s:else>\n ANOTHER SCRIPT\n</s:else>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
333,735
<p>What's the best way to:</p> <ol> <li>Get the data from the db using a single query</li> <li>Loop through the results building e.g. a nested unordered list</li> </ol> <p>My table has <code>id</code>, <code>name</code> and <code>parent_id</code> columns.</p> <hr> <p>Here's an update to my last answer, with a counter that gives each ul a nesting 'level' class, and some comments.</p> <p>Could anyone suggest how to adapt this to use table rows, without nesting, but with some kind of class numbering hierarchy for css/js hooks?</p> <pre><code>&lt;? // // Get the data // include_once("inc/config.php"); $query = "SELECT c.* FROM categories AS c ORDER BY c.id LIMIT 1000"; $result = pg_query($db, $query); // // Load all the results into the row array // while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) { // // Wrap the row array in a parent array, using the id as they key // Load the row values into the new parent array // $categories[$row['id']] = array( 'id' =&gt; $row['id'], 'description' =&gt; $row['description'], 'parent_id' =&gt; $row['parent_id'] ); } // print '&lt;pre&gt;'; // print_r($category_array); // ---------------------------------------------------------------- // // Create a function to generate a nested view of an array (looping through each array item) // From: http://68kb.googlecode.com/svn-history/r172/trunk/upload/includes/application/controllers/admin/utility.php // function generate_tree_list($array, $parent = 0, $level = 0) { // // Reset the flag each time the function is called // $has_children = false; // // Loop through each item of the list array // foreach($array as $key =&gt; $value) { // // For the first run, get the first item with a parent_id of 0 (= root category) // (or whatever id is passed to the function) // // For every subsequent run, look for items with a parent_id matching the current item's key (id) // (eg. get all items with a parent_id of 2) // // This will return false (stop) when it find no more matching items/children // // If this array item's parent_id value is the same as that passed to the function // eg. [parent_id] =&gt; 0 == $parent = 0 (true) // eg. [parent_id] =&gt; 20 == $parent = 0 (false) // if ($value['parent_id'] == $parent) { // // Only print the wrapper ('&lt;ul&gt;') if this is the first child (otherwise just print the item) // Will be false each time the function is called again // if ($has_children === false) { // // Switch the flag, start the list wrapper, increase the level count // $has_children = true; echo '&lt;ul class="level-' . $level . '"&gt;'; $level++; } // // Print the list item // echo '&lt;li&gt;&lt;a href="?id=' . $value['id'] . '"&gt;' . $value['description'] . '&lt;/a&gt;'; // // Repeat function, using the current item's key (id) as the parent_id argument // Gives us a nested list of subcategories // generate_tree_list($array, $key, $level); // // Close the item // echo '&lt;/li&gt;'; } } // // If we opened the wrapper above, close it. // if ($has_children === true) echo '&lt;/ul&gt;'; } // ---------------------------------------------------------------- // // generate list // generate_tree_list($categories); ?&gt; </code></pre>
[ { "answer_id": 7231292, "author": "Maystro", "author_id": 917971, "author_profile": "https://Stackoverflow.com/users/917971", "pm_score": 2, "selected": false, "text": "function generate_list($array,$parent,$level)\n{\n\n foreach ($array as $value)\n {\n $has_children=false;\n\n if ($value['parent_id']==$parent)\n {\n\n if ($has_children==false)\n {\n $has_children=true;\n echo '<ul>';\n }\n\n echo '<li>'.$value['member_name'].' -- '.$value['id'].' -- '.$value['parent_id'];\n\n generate_list($array,$value['id'],$level);\n\n echo '</li>';\n }\n\n if ($has_children==true) echo '</ul>';\n\n echo $value['parent_id'];\n }\n\n}\n" }, { "answer_id": 36717570, "author": "Boopathi .R", "author_id": 6202798, "author_profile": "https://Stackoverflow.com/users/6202798", "pm_score": 0, "selected": false, "text": "$category = CHtml::listData(TblCategory::model()->findAllCategory(array(\n'distinct'=>true,\n'join'=>'LEFT JOIN tbl_category b on b.id = t.cat_parent',\n'join'=>'LEFT JOIN tbl_category c on c.cat_parent = 0',\n'order' => 'cat_name')),'id','cat_name'); join foreach() public function findAllCategory($condition='',$params=array())\n{\n \n Yii::trace(get_class($this).'.findAll()','system.db.ar.CActiveRecord');\n $criteria=$this->getCommandBuilder()->createCriteria($condition,$params); \n \n $category = array();\n $cat_before;\n $parent_id = array();\n $cat_before = $this->query($criteria,true); \n \n //echo \"<br><br><br><br><br><br><br>\";\n \n foreach($cat_before as $key => $val)\n {\n $category[$key] = $val;\n $parent_id[$key]['cat_parent'] =$val['cat_parent'];\n $parent_id[$key]['cat_name'] =$val['cat_name']; \n \n foreach($parent_id as $key_1=> $val_1)\n { \n \n if($parent_id[$key]['cat_parent'] == $category[$key_1]['id'])\n {\n $category[$key]['cat_name']= $category[$key_1]['cat_name'] .' > '. $parent_id[$key]['cat_name'];\n \n }\n }\n } \n return $cat_before; \n} Main cat >> subcat 1 >> subcat_1 inner >> ..." } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
333,736
<p>I've been programming a long time, and the programs I see, when they run out of memory, attempt to clean up and exit, i.e. fail gracefully. I can't remember the last time I saw one actually attempt to recover and continue operating normally.</p> <p>So much processing relies on being able to successfully allocate memory, especially in garbage collected languages, it seems that out of memory errors should be classified as non-recoverable. (Non-recoverable errors include things like stack overflows.)</p> <p>What is the compelling argument for making it a recoverable error?</p>
[ { "answer_id": 333860, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 1, "selected": false, "text": "malloc() setrlimit()" }, { "answer_id": 334309, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "T new2(T)( lazy T old_new ) {\n T obj;\n try{\n obj = old_new;\n }catch(OutOfMemoryException oome) {\n foreach(compact; Global_List_Of_Delegates_From_Compatible_Objects)\n compact();\n obj = old_new;\n }\n return obj;\n}\n" }, { "answer_id": 1244755, "author": "nos", "author_id": 126769, "author_profile": "https://Stackoverflow.com/users/126769", "pm_score": -1, "selected": false, "text": "void *smalloc(size_t size) {\n void *mem = null; \n for(;;) {\n mem = malloc(size);\n if(mem == NULL) {\n sleep(1);\n } else \n break;\n }\n return mem;\n}\n" }, { "answer_id": 18065723, "author": "Keith Thompson", "author_id": 827263, "author_profile": "https://Stackoverflow.com/users/827263", "pm_score": 1, "selected": false, "text": "Storage_Error malloc() new malloc() new" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33949/" ]
333,737
<p>Is there a function the .NET framework that can evaluate a numeric expression contained in a string and return the result? F.e.:</p> <pre><code>string mystring = "3*(2+4)"; int result = EvaluateExpression(mystring); Console.Writeln(result); // Outputs 18 </code></pre> <p>Is there a standard framework function that you can replace my <code>EvaluateExpression</code> method with?</p>
[ { "answer_id": 334378, "author": "Beardo", "author_id": 33724, "author_profile": "https://Stackoverflow.com/users/33724", "pm_score": 2, "selected": false, "text": "IronPython.Hosting.PythonEngine pythonEngine = new IronPython.Hosting.PythonEngine();\nstring expression = \"3*(2+4)\";\ndouble result = pythonEngine.EvaluateAs<double>(expression);\n" }, { "answer_id": 1417442, "author": "Olav Botterli", "author_id": 172720, "author_profile": "https://Stackoverflow.com/users/172720", "pm_score": 4, "selected": false, "text": "public static double Evaluate(string expression)\n{\n return (double)new System.Xml.XPath.XPathDocument\n (new StringReader(\"<r/>\")).CreateNavigator().Evaluate\n (string.Format(\"number({0})\", new\n System.Text.RegularExpressions.Regex(@\"([\\+\\-\\*])\")\n .Replace(expression, \" ${1} \")\n .Replace(\"/\", \" div \")\n .Replace(\"%\", \" mod \")));\n}\n" }, { "answer_id": 1417488, "author": "pero", "author_id": 21645, "author_profile": "https://Stackoverflow.com/users/21645", "pm_score": 6, "selected": false, "text": "static double Evaluate(string expression) {\n var loDataTable = new DataTable();\n var loDataColumn = new DataColumn(\"Eval\", typeof (double), expression);\n loDataTable.Columns.Add(loDataColumn);\n loDataTable.Rows.Add(0);\n return (double) (loDataTable.Rows[0][\"Eval\"]);\n}\n" }, { "answer_id": 1564836, "author": "Sébastien Ros - MSFT", "author_id": 142772, "author_profile": "https://Stackoverflow.com/users/142772", "pm_score": 6, "selected": false, "text": "Expression e = new Expression(\"2 + 3 * 5\");\nDebug.Assert(17 == e.Evaluate());\n" }, { "answer_id": 4195437, "author": "Tawani", "author_id": 61525, "author_profile": "https://Stackoverflow.com/users/61525", "pm_score": 4, "selected": false, "text": "public class MathEvaluator\n{\n public static void Run()\n {\n Eval(\"(1+2)\");\n Eval(\"5*4/2\");\n Eval(\"((3+5)-6)\");\n }\n\n public static void Eval(string input)\n {\n var ans = Evaluate(input);\n Console.WriteLine(input + \" = \" + ans);\n }\n\n public static double Evaluate(String input)\n {\n String expr = \"(\" + input + \")\";\n Stack<String> ops = new Stack<String>();\n Stack<Double> vals = new Stack<Double>();\n\n for (int i = 0; i < expr.Length; i++)\n {\n String s = expr.Substring(i, 1);\n if (s.Equals(\"(\")){}\n else if (s.Equals(\"+\")) ops.Push(s);\n else if (s.Equals(\"-\")) ops.Push(s);\n else if (s.Equals(\"*\")) ops.Push(s);\n else if (s.Equals(\"/\")) ops.Push(s);\n else if (s.Equals(\"sqrt\")) ops.Push(s);\n else if (s.Equals(\")\"))\n {\n int count = ops.Count;\n while (count > 0)\n {\n String op = ops.Pop();\n double v = vals.Pop();\n if (op.Equals(\"+\")) v = vals.Pop() + v;\n else if (op.Equals(\"-\")) v = vals.Pop() - v;\n else if (op.Equals(\"*\")) v = vals.Pop()*v;\n else if (op.Equals(\"/\")) v = vals.Pop()/v;\n else if (op.Equals(\"sqrt\")) v = Math.Sqrt(v);\n vals.Push(v);\n\n count--;\n }\n }\n else vals.Push(Double.Parse(s));\n }\n return vals.Pop();\n }\n}\n" }, { "answer_id": 5298476, "author": "Rajesh Jinaga", "author_id": 658761, "author_profile": "https://Stackoverflow.com/users/658761", "pm_score": 3, "selected": false, "text": " // 2+(100/5)+10 = 32\n //((2.5+10)/5)+2.5 = 5\n // (2.5+10)/5+2.5 = 1.6666\n public static double Evaluate(String expr)\n {\n\n Stack<String> stack = new Stack<String>();\n\n string value = \"\";\n for (int i = 0; i < expr.Length; i++)\n {\n String s = expr.Substring(i, 1);\n char chr = s.ToCharArray()[0];\n\n if (!char.IsDigit(chr) && chr != '.' && value != \"\")\n {\n stack.Push(value);\n value = \"\";\n }\n\n if (s.Equals(\"(\")) {\n\n string innerExp = \"\";\n i++; //Fetch Next Character\n int bracketCount=0;\n for (; i < expr.Length; i++)\n {\n s = expr.Substring(i, 1);\n\n if (s.Equals(\"(\"))\n bracketCount++;\n\n if (s.Equals(\")\"))\n if (bracketCount == 0)\n break;\n else\n bracketCount--;\n\n\n innerExp += s;\n }\n\n stack.Push(Evaluate(innerExp).ToString());\n\n }\n else if (s.Equals(\"+\")) stack.Push(s);\n else if (s.Equals(\"-\")) stack.Push(s);\n else if (s.Equals(\"*\")) stack.Push(s);\n else if (s.Equals(\"/\")) stack.Push(s);\n else if (s.Equals(\"sqrt\")) stack.Push(s);\n else if (s.Equals(\")\"))\n {\n }\n else if (char.IsDigit(chr) || chr == '.')\n {\n value += s;\n\n if (value.Split('.').Length > 2)\n throw new Exception(\"Invalid decimal.\");\n\n if (i == (expr.Length - 1))\n stack.Push(value);\n\n }\n else\n throw new Exception(\"Invalid character.\");\n\n }\n\n\n double result = 0;\n while (stack.Count >= 3)\n {\n\n double right = Convert.ToDouble(stack.Pop());\n string op = stack.Pop();\n double left = Convert.ToDouble(stack.Pop());\n\n if (op == \"+\") result = left + right;\n else if (op == \"+\") result = left + right;\n else if (op == \"-\") result = left - right;\n else if (op == \"*\") result = left * right;\n else if (op == \"/\") result = left / right;\n\n stack.Push(result.ToString());\n }\n\n\n return Convert.ToDouble(stack.Pop());\n }\n" }, { "answer_id": 6315645, "author": "Fat-Wednesday", "author_id": 793901, "author_profile": "https://Stackoverflow.com/users/793901", "pm_score": 2, "selected": false, "text": "public static double Evaluate(string expr)\n {\n expr = expr.ToLower();\n expr = expr.Replace(\" \", \"\");\n expr = expr.Replace(\"true\", \"1\");\n expr = expr.Replace(\"false\", \"0\");\n\n Stack<String> stack = new Stack<String>();\n\n string value = \"\";\n for (int i = 0; i < expr.Length; i++)\n {\n String s = expr.Substring(i, 1);\n // pick up any doublelogical operators first.\n if (i < expr.Length - 1)\n {\n String op = expr.Substring(i, 2);\n if (op == \"<=\" || op == \">=\" || op == \"==\")\n {\n stack.Push(value);\n value = \"\";\n stack.Push(op);\n i++;\n continue;\n }\n }\n\n char chr = s.ToCharArray()[0];\n\n if (!char.IsDigit(chr) && chr != '.' && value != \"\")\n {\n stack.Push(value);\n value = \"\";\n }\n if (s.Equals(\"(\"))\n {\n string innerExp = \"\";\n i++; //Fetch Next Character\n int bracketCount = 0;\n for (; i < expr.Length; i++)\n {\n s = expr.Substring(i, 1);\n\n if (s.Equals(\"(\")) bracketCount++;\n\n if (s.Equals(\")\"))\n {\n if (bracketCount == 0) break;\n bracketCount--;\n }\n innerExp += s;\n }\n stack.Push(Evaluate(innerExp).ToString());\n }\n else if (s.Equals(\"+\") ||\n s.Equals(\"-\") ||\n s.Equals(\"*\") ||\n s.Equals(\"/\") ||\n s.Equals(\"<\") ||\n s.Equals(\">\"))\n {\n stack.Push(s);\n }\n else if (char.IsDigit(chr) || chr == '.')\n {\n value += s;\n\n if (value.Split('.').Length > 2)\n throw new Exception(\"Invalid decimal.\");\n\n if (i == (expr.Length - 1))\n stack.Push(value);\n\n }\n else\n {\n throw new Exception(\"Invalid character.\");\n }\n\n }\n double result = 0;\n List<String> list = stack.ToList<String>();\n for (int i = list.Count - 2; i >= 0; i--)\n {\n if (list[i] == \"/\")\n {\n list[i] = (Convert.ToDouble(list[i - 1]) / Convert.ToDouble(list[i + 1])).ToString();\n list.RemoveAt(i + 1);\n list.RemoveAt(i - 1);\n i -= 2;\n }\n }\n\n for (int i = list.Count - 2; i >= 0; i--)\n {\n if (list[i] == \"*\")\n {\n list[i] = (Convert.ToDouble(list[i - 1]) * Convert.ToDouble(list[i + 1])).ToString();\n list.RemoveAt(i + 1);\n list.RemoveAt(i - 1);\n i -= 2;\n }\n }\n for (int i = list.Count - 2; i >= 0; i--)\n {\n if (list[i] == \"+\")\n {\n list[i] = (Convert.ToDouble(list[i - 1]) + Convert.ToDouble(list[i + 1])).ToString();\n list.RemoveAt(i + 1);\n list.RemoveAt(i - 1);\n i -= 2;\n }\n }\n for (int i = list.Count - 2; i >= 0; i--)\n {\n if (list[i] == \"-\")\n {\n list[i] = (Convert.ToDouble(list[i - 1]) - Convert.ToDouble(list[i + 1])).ToString();\n list.RemoveAt(i + 1);\n list.RemoveAt(i - 1);\n i -= 2;\n }\n }\n stack.Clear();\n for (int i = 0; i < list.Count; i++)\n {\n stack.Push(list[i]);\n }\n while (stack.Count >= 3)\n {\n double right = Convert.ToDouble(stack.Pop());\n string op = stack.Pop();\n double left = Convert.ToDouble(stack.Pop());\n\n if (op == \"<\") result = (left < right) ? 1 : 0;\n else if (op == \">\") result = (left > right) ? 1 : 0;\n else if (op == \"<=\") result = (left <= right) ? 1 : 0;\n else if (op == \">=\") result = (left >= right) ? 1 : 0;\n else if (op == \"==\") result = (left == right) ? 1 : 0;\n\n stack.Push(result.ToString());\n }\n return Convert.ToDouble(stack.Pop());\n }\n" }, { "answer_id": 9731201, "author": "mishamosher", "author_id": 1273042, "author_profile": "https://Stackoverflow.com/users/1273042", "pm_score": 4, "selected": false, "text": "static double Evaluate(string expression) { \n var loDataTable = new DataTable(); \n var loDataColumn = new DataColumn(\"Eval\", typeof (double), expression); \n loDataTable.Columns.Add(loDataColumn); \n loDataTable.Rows.Add(0); \n return (double) (loDataTable.Rows[0][\"Eval\"]); \n} \n var loDataTable = new DataTable(); var loDataColumn = new DataColumn(\"Eval\", typeof (double), expression); \"Eval\" typeof (double) System.Type.GetType(\"System.Double\"); expression Evaluate Expression loDataTable.Columns.Add(loDataColumn); loDataColumn loDataTable loDataTable.Rows.Add(0); loDataTable return (double) (loDataTable.Rows[0][\"Eval\"]); DataTable MyTable = new DataTable();\nDataColumn MyColumn = new DataColumn();\nMyColumn.ColumnName = \"MyColumn\";\nMyColumn.Expression = \"5+5/5\"\nMyColumn.DataType = typeof(double);\nMyTable.Columns.Add(MyColumn);\nDataRow MyRow = MyTable.NewRow();\nMyTable.Rows.Add(MyRow);\nreturn (double)(MyTable.Rows[0][\"MyColumn\"]);\n DataTable MyTable = new DataTable(); DataColumn MyColumn = new DataColumn(); MyColumn.ColumnName = \"MyColumn\"; MyColumn.DataType = typeof(double); MyTable.Columns.Add(MyColumn); DataRow MyRow = MyTable.NewRow(); MyTable.Rows.Add(MyRow); MyColumn MyTable return (double)(MyTable.Rows[0][\"MyColumn\"]);" }, { "answer_id": 11029886, "author": "Ramesh Sambari", "author_id": 1455789, "author_profile": "https://Stackoverflow.com/users/1455789", "pm_score": 8, "selected": false, "text": "using System.Data;\n\nDataTable dt = new DataTable();\nvar v = dt.Compute(\"3 * (2+4)\",\"\");\n" }, { "answer_id": 12539151, "author": "Mr.Black", "author_id": 1356748, "author_profile": "https://Stackoverflow.com/users/1356748", "pm_score": 2, "selected": false, "text": "function = relation[0].Replace(\"and\",\"&&\").Replace(\"x\",x);\n\nDataTable f_dt = new DataTable();\nvar f_var = f_dt.Compute(function,\"\");\n\nif (bool.Parse(f_var.ToString()) { do stuff }\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37119/" ]
333,750
<p>I have the following five tables:</p> <ul> <li>ISP</li> <li>Product</li> <li>Connection</li> <li>AddOn</li> <li>AddOn/Product (pivot table for many-to-many relationship).</li> </ul> <p>Each Product is linked to an ISP, each Connection is listed to a Product. Each product can have a number of add-ons, through the use of the pivot table (which simply has 2 fields, one for the product ID and one for the AddOn ID).</p> <p>The result I am interested in is each connection with the addons listed (I am making use of MySQL's GROUP_CONCAT for this, to make a comma-separated list of the addon's <em>name</em> field). This works fine as is, the query looks something like this:</p> <pre><code>SELECT i.name AS ispname, i.img_link, c.download, c.upload, c.monthly_price, c.link, GROUP_CONCAT(a.name) AS addons, SUM(pa.monthly_fee) AS addon_price FROM isp i JOIN product p ON i.id = p.isp_id JOIN `connection` c ON p.id = c.product_id LEFT JOIN product_addon pa ON pa.product_id = p.id AND pa.forced = 0 LEFT JOIN addon a ON pa.addon_id = a.id GROUP BY c.id </code></pre> <p>I am using LEFT JOINS as it is possible for products to have no addons at all.</p> <p>My problem is that it is possible to select some addons that listed connections MUST have, presented as a list of addon IDs, like (1,14,237). If I put it in as an additional condition in the JOIN statements (<em>AND pa.addon_id IN (...)</em>), it will return all connections that have just one of the listed addons, but not necessarily all of them.</p> <p>Is there some way to return all connections that as a <strong>minimum</strong> have all the addons (they can have additional as well) via SQL?</p>
[ { "answer_id": 333816, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "AND NOT EXISTS (SELECT NULL FROM addon a2\n WHERE a2.addon_id IN (1,14,237)\n AND NOT EXISTS\n ( SELECT NULL\n FROM product_addon pa2\n WHERE pa2.addon_id = a2.addon_id\n AND pa2.product_id = p.product_id\n )\n )\n AND NOT EXISTS (SELECT NULL FROM addon a2\n LEFT JOIN product_addon pa2\n ON pa2.addon_id = a2.addon_id\n AND pa2.product_id = p.product_id\n WHERE a2.addon_id IN (1,14,237)\n AND pa2.product_id IS NULL\n )\n )\n" }, { "answer_id": 333867, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 3, "selected": true, "text": "GROUP BY set-of-column\nHAVING SUM(CASE WHEN ISNULL(pa.addon_id, 0) IN (1,14,237) THEN 1 ELSE 0 END) = 3\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479/" ]
333,767
<p>Is there some smart way to retreive the installation path when working within a dll (C#) which will be called from an application in a different folder?</p> <p>I'm developing an add-in for an application. My add-in is written in C#. The application that will use is written in C and needs to compile some stuff during evaluation, so I have a middlestep with a C++ dll that handles the interop business with C# and only shows a clean interface outward that C can work with.</p> <p>What I deploy will be a set of .dll's and a .lib and .h for the C++ part (sometimes static binding will be necessary). </p> <p>When trying out the setup and printing out the current directory info from the C# dll with:</p> <pre><code> Console.WriteLine(Directory.GetCurrentDirectory()); </code></pre> <p>or:</p> <pre><code> Console.WriteLine(System.Environment.CurrentDirectory); </code></pre> <p>I get the executables path.</p> <p>So ... once again, how do I get the installation path of my dll?</p> <p>Edit: They both worked! Thanks for the quick reply guys!</p>
[ { "answer_id": 333786, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": "Assembly.GetExecutingAssembly().Location" }, { "answer_id": 333790, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "typeof(TypeInMyModule).Assembly.Location\n" }, { "answer_id": 15783403, "author": "Sonhja", "author_id": 760893, "author_profile": "https://Stackoverflow.com/users/760893", "pm_score": 2, "selected": false, "text": "using System.IO;\nusing System.Windows.Forms;\nstring appPath = Path.GetDirectoryName(Application.ExecutablePath);\n using System.IO;\nusing System.Reflection;\nstring path = Path.GetDirectoryName(\nAssembly.GetAssembly(typeof(MyClass)).CodeBase);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15763/" ]
333,812
<p>How can I list all the local users configured on a windows machine (Win2000+) using java.<br> I would prefer doing this with ought using any java 2 com bridges, or any other third party library if possible.<br> Preferable some native method to Java. </p>
[ { "answer_id": 333848, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": true, "text": "import java.util.Enumeration;\nimport com.jacob.activeX.ActiveXComponent;\nimport com.jacob.com.ComThread;\nimport com.jacob.com.EnumVariant;\nimport com.jacob.com.Variant;\n\npublic class ComTst {\npublic static void main(String[] args) {\n ComThread.InitMTA();\n try {\n ActiveXComponent wmi = new ActiveXComponent(\"winmgmts:\\\\\\\\.\");\n Variant instances = wmi.invoke(\"InstancesOf\", \"Win32_SystemUsers\");\n Enumeration<Variant> en = new EnumVariant(instances.getDispatch());\n while (en.hasMoreElements())\n {\n ActiveXComponent bb = new ActiveXComponent(en.nextElement().getDispatch());\n System.out.println(bb.getPropertyAsString(\"PartComponent\"));\n }\n } finally {\n ComThread.Release();\n }\n}\n}\n" }, { "answer_id": 334079, "author": "Alex Shnayder", "author_id": 26042, "author_profile": "https://Stackoverflow.com/users/26042", "pm_score": 1, "selected": false, "text": "private boolean isUserPresent() {\n //Load user list\n ProcessBuilder processBuilder = new ProcessBuilder(\"net\",\"user\");\n processBuilder.redirectErrorStream(true);\n String output = runProcessAndReturnOutput(processBuilder);\n //Check if user is in list\n //We assume the output to be a list of users with the net user\n //Remove long space sequences\n output = output.replaceAll(\"\\\\s+\", \" \").toLowerCase();\n //Locate user name in resulting list\n String[] tokens = output.split(\" \");\n Arrays.sort(tokens);\n if (Arrays.binarySearch(tokens, \"SomeUserName\".toLowerCase()) >= 0){\n //We found the user name\n return true;\n }\n return false;\n}\n" }, { "answer_id": 10541754, "author": "arkon", "author_id": 726315, "author_profile": "https://Stackoverflow.com/users/726315", "pm_score": 2, "selected": false, "text": "public static void EnumerateUsers() {\n\n String query = \"SELECT * FROM Win32_UserAccount\";\n ActiveXComponent axWMI = new ActiveXComponent(\"winmgmts:\\\\\");\n Variant vCollection = axWMI.invoke(\"ExecQuery\", new Variant(query));\n EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());\n Dispatch item = null;\n StringBuilder sb = new StringBuilder();\n\n while (enumVariant.hasMoreElements()) {\n item = enumVariant.nextElement().toDispatch();\n sb.append(\"User: \" + Dispatch.call(item, \"Name\")).toString();\n System.out.println(sb);\n sb.setLength(0);\n } \n\n}\n" }, { "answer_id": 62174240, "author": "John", "author_id": 8067983, "author_profile": "https://Stackoverflow.com/users/8067983", "pm_score": 1, "selected": false, "text": "import com.sun.jna.platform.win32.Netapi32Util;\n\n Netapi32Util.User[] users = Netapi32Util.getUsers();\n for(Netapi32Util.User user : users) {\n System.out.println(user.name);\n }\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26042/" ]
333,828
<p>I've built a small application which has User Management, a frontend console to enter data and a backend console to control parts of the frontend. The frontend adds rows to a MySQL database which are timestamped. The backend needs to be able to select rows from the database between X and Y dates.</p> <p>Everything works so far, except the date part which I'm really struggling with.</p> <p>The frontend SQL input looks like this (simplified with spurious code removed):</p> <pre><code>$date = time(); $top_level_category = $_POST['top_level_category']; $sub_level_category = $_POST['sub_level_category']; $company = $_POST['company']; $agent_name = $_POST['agent_name']; $ticket_id = $_POST['ticket_id']; $sql = "INSERT INTO dacc_data (" . "id, top_level_category, sub_level_category, " . "agent_name, date, ticket_id, company" . ") VALUES (" . "NULL, '$top_level_category', '$sub_level_category', " . "'$agent_name', FROM_UNIXTIME('$date'), '$ticket_id', '$company'" . ")" ; $result = mysql_query($sql) or die (mysql_error()); </code></pre> <p>That seems to work ok, the timestamp is being picked up and added to a DATETIME column in my table. It displays as dd/mm/yyyy hh:mm:ss within the database.</p> <p>So ... my first question is - is this the right way to do it?</p> <p>The second question being, what sort of SQL statement would I need to pull out an array of rows between X and Y date.</p> <p>Apologies if this is rambling a bit, hope it's clear but if you need more information let me know.</p>
[ { "answer_id": 333844, "author": "Tim", "author_id": 33914, "author_profile": "https://Stackoverflow.com/users/33914", "pm_score": 4, "selected": true, "text": "select *\nfrom table\nwhere date >= '[start date]' and date <= '[end date]';\n select * \nfrom table \nwhere date between '[start date]' and '[end date]';\n" }, { "answer_id": 333859, "author": "suitedupgeek", "author_id": 42428, "author_profile": "https://Stackoverflow.com/users/42428", "pm_score": 0, "selected": false, "text": "// Initial questions still stand :)\n" }, { "answer_id": 333863, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 0, "selected": false, "text": "SELECT * FROM `dacc_data` where `date` between \"2008-11-01\" and \"2008-12-01\"\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42428/" ]
333,829
<p>In .NET, a value type (C# <code>struct</code>) can't have a constructor with no parameters. According to <a href="https://stackoverflow.com/questions/203695/structure-vs-class-in-c#204009">this post</a> this is mandated by the CLI specification. What happens is that for every value-type a default constructor is created (by the compiler?) which initialized all members to zero (or <code>null</code>).</p> <p>Why is it disallowed to define such a default constructor?</p> <p>One trivial use is for rational numbers:</p> <pre><code>public struct Rational { private long numerator; private long denominator; public Rational(long num, long denom) { /* Todo: Find GCD etc. */ } public Rational(long num) { numerator = num; denominator = 1; } public Rational() // This is not allowed { numerator = 0; denominator = 1; } } </code></pre> <p>Using current version of C#, a default Rational is <code>0/0</code> which is not so cool.</p> <p><strong>PS</strong>: Will default parameters help solve this for C#&nbsp;4.0 or will the CLR-defined default constructor be called?</p> <hr> <p><a href="https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net#333840">Jon Skeet</a> answered:</p> <blockquote> <p>To use your example, what would you want to happen when someone did:</p> <pre><code> Rational[] fractions = new Rational[1000]; </code></pre> <p>Should it run through your constructor 1000 times?</p> </blockquote> <p>Sure it should, that's why I wrote the default constructor in the first place. The CLR should use the <em>default zeroing</em> constructor when no explicit default constructor is defined; that way you only pay for what you use. Then if I want a container of 1000 non-default <code>Rational</code>s (and want to optimize away the 1000 constructions) I will use a <code>List&lt;Rational&gt;</code> rather than an array.</p> <p>This reason, in my mind, is not strong enough to prevent definition of a default constructor.</p>
[ { "answer_id": 333840, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "MyStruct[] foo = new MyStruct[1000];\n Rational[] fractions = new Rational[1000];\n new Guid()" }, { "answer_id": 334683, "author": "user42467", "author_id": 42467, "author_profile": "https://Stackoverflow.com/users/42467", "pm_score": 6, "selected": false, "text": "MyClass m;\nMyStruct m2;\n m m2" }, { "answer_id": 433233, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "public static Rational One => new Rational(0, 1); \n var rat = Rational.One;\n" }, { "answer_id": 40577856, "author": "G1xb17", "author_id": 5054603, "author_profile": "https://Stackoverflow.com/users/5054603", "pm_score": -1, "selected": false, "text": "public struct Point2D {\n public static Point2D NULL = new Point2D(-1,-1);\n private int[] Data;\n\n public int X {\n get {\n return this.Data[ 0 ];\n }\n set {\n try {\n this.Data[ 0 ] = value;\n } catch( Exception ) {\n this.Data = new int[ 2 ];\n } finally {\n this.Data[ 0 ] = value;\n }\n }\n }\n\n public int Z {\n get {\n return this.Data[ 1 ];\n }\n set {\n try {\n this.Data[ 1 ] = value;\n } catch( Exception ) {\n this.Data = new int[ 2 ];\n } finally {\n this.Data[ 1 ] = value;\n }\n }\n }\n\n public Point2D( int x , int z ) {\n this.Data = new int[ 2 ] { x , z };\n }\n\n public static Point2D operator +( Point2D A , Point2D B ) {\n return new Point2D( A.X + B.X , A.Z + B.Z );\n }\n\n public static Point2D operator -( Point2D A , Point2D B ) {\n return new Point2D( A.X - B.X , A.Z - B.Z );\n }\n\n public static Point2D operator *( Point2D A , int B ) {\n return new Point2D( B * A.X , B * A.Z );\n }\n\n public static Point2D operator *( int A , Point2D B ) {\n return new Point2D( A * B.Z , A * B.Z );\n }\n\n public override string ToString() {\n return string.Format( \"({0},{1})\" , this.X , this.Z );\n }\n}\n public struct Rational {\n private long[] Data;\n\n public long Numerator {\n get {\n try {\n return this.Data[ 0 ];\n } catch( Exception ) {\n this.Data = new long[ 2 ] { 0 , 1 };\n return this.Data[ 0 ];\n }\n }\n set {\n try {\n this.Data[ 0 ] = value;\n } catch( Exception ) {\n this.Data = new long[ 2 ] { 0 , 1 };\n this.Data[ 0 ] = value;\n }\n }\n }\n\n public long Denominator {\n get {\n try {\n return this.Data[ 1 ];\n } catch( Exception ) {\n this.Data = new long[ 2 ] { 0 , 1 };\n return this.Data[ 1 ];\n }\n }\n set {\n try {\n this.Data[ 1 ] = value;\n } catch( Exception ) {\n this.Data = new long[ 2 ] { 0 , 1 };\n this.Data[ 1 ] = value;\n }\n }\n }\n\n public Rational( long num , long denom ) {\n this.Data = new long[ 2 ] { num , denom };\n /* Todo: Find GCD etc. */\n }\n\n public Rational( long num ) {\n this.Data = new long[ 2 ] { num , 1 };\n this.Numerator = num;\n this.Denominator = 1;\n }\n}\n" }, { "answer_id": 46453936, "author": "M.kazem Akhgary", "author_id": 4767498, "author_profile": "https://Stackoverflow.com/users/4767498", "pm_score": 2, "selected": false, "text": "public struct Tempo\n{\n const double DefaultBpm = 120;\n private double _bpm; // this field must not be modified other than with its property.\n\n public double BeatsPerMinute\n {\n get => _bpm + DefaultBpm;\n set => _bpm = value - DefaultBpm;\n }\n}\n public struct Difficaulty\n{\n Easy,\n Medium,\n Hard\n}\n\npublic struct Level\n{\n const Difficaulty DefaultLevel = Difficaulty.Medium;\n private Difficaulty _level; // this field must not be modified other than with its property.\n\n public Difficaulty Difficaulty\n {\n get => _level + DefaultLevel;\n set => _level = value - DefaultLevel;\n }\n}\n" }, { "answer_id": 51901010, "author": "eMeL", "author_id": 1743206, "author_profile": "https://Stackoverflow.com/users/1743206", "pm_score": -1, "selected": false, "text": "public struct Rational \n{\n private long numerator;\n private long denominator;\n\n public Rational(long num = 0, long denom = 1) // This is allowed!!!\n {\n numerator = num;\n denominator = denom;\n }\n}\n" }, { "answer_id": 58951696, "author": "Axel Samyn", "author_id": 4456593, "author_profile": "https://Stackoverflow.com/users/4456593", "pm_score": 2, "selected": false, "text": "public struct SomeStruct {\n private SomeRefType m_MyRefVariableBackingField;\n\n public SomeRefType MyRefVariable {\n get { return m_MyRefVariableBackingField ?? (m_MyRefVariableBackingField = new SomeRefType()); }\n }\n}\n" }, { "answer_id": 70238841, "author": "rekaha", "author_id": 17597874, "author_profile": "https://Stackoverflow.com/users/17597874", "pm_score": 1, "selected": false, "text": "struct Data\n {\n public int Point { get; set; }\n public HazardMap Map { get; set; }\n public Data Initialize()\n {\n Point = 1; //set anything you want as default\n Map = new HazardMap();\n return this;\n }\n }\n Data input = new Data().Initialize();\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
333,839
<p>I have a MySQL query that I use to retrieve random rows from a table. The query is:</p> <pre><code>SELECT * FROM QUESTION WHERE TESTID=1 ORDER BY RAND() LIMIT 10; </code></pre> <p>Now I need to change this query to <strong><em>Hibernate</em></strong>. Did a bit of googling but couldn't find the answer. Can someone provide help on this?</p>
[ { "answer_id": 333846, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 2, "selected": true, "text": "String query = \"from QUESTION order by newid()\";\nQuery q = session.createQuery(query);\nq.setMaxResults(10);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40945/" ]
333,841
<p>Is there any way to have a look at signatures of anonymous functions in ActionScript 3 during runtime?</p> <p>I would like to validate <code>Function</code> objects passed in as arguments to other functions and make sure that they accept the correct number of arguments (with the correct types) and return a value of the correct type.</p> <p><code>flash.utils.describeType()</code> doesn't seem to return this info for anonymous functions.</p>
[ { "answer_id": 334491, "author": "Luca Tettamanti", "author_id": 42448, "author_profile": "https://Stackoverflow.com/users/42448", "pm_score": 1, "selected": false, "text": "function doStuff(callback:Function) {\n trace(callback.length);\n}\n" }, { "answer_id": 348585, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 3, "selected": true, "text": "dynamic \"minotaur\" uint 0 public interface IFancyCallback {\n public function fancyFunction(frog:Frog, princess:Girl):UsefulReturnType;\n}\n public class ConcreteCallback implements IFancyCallback {\n public function fancyFunction(frog:Frog, princess:Girl):UsefulReturnType {\n princess.kiss(frog);\n return new UsefulReturnType(\"jabberwocky\");\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4111/" ]
333,850
<p>I'm trying to work out a way of passing the web current http context to a service class (or initialising the class with a reference to it). I am doing this to abstract the rest of the app away from needing to know anything about the http context. </p> <p>I also want the service to be testable using TDD, probably using one of the Mockable frameworks. Hence it would be preferable to use an interface rather than an actual class.</p> <p>An example of what I'd like to achieve:</p> <pre><code>class WebInstanceService { private IHttpContext _Context; public WebInstanceService( ... , IHttpContext HttpContext ) { .... _Context = HttpContext; } // Methods... public string GetInstanceVariable(string VariableName) { return _Context.Current.Session[VariableName]; } } </code></pre> <p>One of the main issues I have is that there is no IHttpContext, the .net http context is a subclass of an abstract class which can't be mocked (easily?).</p> <p>Another issue is that I can't initialise global instances of the class as then the context won't be relevant for most requests. </p> <p>I could make the class static, and require the Context to be passed to each function as it is called i.e.</p> <pre><code>public static string GetInstanceVariable(string VariableName, HttpContext Context) { ... } </code></pre> <p>but this doesn't make the class any easier to test, I still need to create an HttpContext and additionally any non-web-aware services which want to use this class suddenly need to be able to retrieve the Context requiring them to be closely coupled to the web server - the whole reason for wanting to create this class in the first place.</p> <p>I'm open to ALL suggestions - particularly those which people know facilitate easy tdd testing. <strong>How would people suggest I tackle this problem?</strong></p> <p>Cheers</p>
[ { "answer_id": 333866, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "new HttpContextWrapper( httpContext ) class WebInstanceService \n{\n private HttpContextBase _Context; \n\n public WebInstanceService( ... , HttpContextBase HttpContext )\n {\n ....\n _Context = HttpContext;\n }\n\n // Methods...\n public string GetInstanceVariable(string VariableName)\n {\n return _Context.Session[VariableName];\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31128/" ]
333,856
<p>Is it possible to get a report of the records that are updated using a update query, without using a recordset?</p> <p>Ex:</p> <p><code>sqltext = update table employees set bonus = 0 where salary &gt; 50000<br> DoCmd.RunSQL sqltext</code></p> <p>After this query runs, is it possible to get the name of the employees for whom this update query was performed?</p>
[ { "answer_id": 342881, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 3, "selected": true, "text": "DoCmd.RunSQL Public Function SQLRun(strSQL As String) As Boolean\nOn Error GoTo errHandler\n\n CurrentDB.Execute strSQL, dbFailOnError\n SQLRun= True\n\nexitRoutine:\n Exit Function\n\nerrHandler:\n MsgBox err.Number & \": \" & err.Description, vbExclamation, \"Error in SQLRun()\"\n Resume exitRoutine\nEnd Function\n DoCmd.RunSQL SQLRun" }, { "answer_id": 30557650, "author": "Avagut", "author_id": 2849004, "author_profile": "https://Stackoverflow.com/users/2849004", "pm_score": 2, "selected": false, "text": "sqltext = \"update table employees set bonus = 0 where salary > 50000\"\nCurrentDb.Execute sqltext\nAffectedRows = CurrentDb.RecordsAffected\n'Optional Notification\n MsgBox CStr(AffectedRows) & \" records were affected by this SQL statement.\"\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31132/" ]
333,875
<p>I have a SelectList that I first check for a selected value != null and then want to use this selectedvalue in a where clause for a filter. Like so:</p> <pre><code>if(searchBag.Qualities.SelectedValue != null){ ListItem selected = (ListItem)searchBag.Qualities.SelectedValue; } </code></pre> <p>I made the cast in a seperate useless line to pinpoint the problem. This gives me a </p> <blockquote> <p>Unable to cast object of type 'WhereListIterator`1[System.Web.Mvc.ListItem]' to type 'System.Web.Mvc.ListItem'.</p> </blockquote> <p>Weuh?</p> <p><strong>--EDIT--</strong><br> It was indeed because multiple selections were made. This was because on creation I set the selected value to theItems.Where(i=>i.someCriterea) and I forgot to put .FirstOrDefault() at the end. Ending up in the possibility of multiple answers. Since it was an IEnumerable, it was a lazy list and hence the WhereListIterator I guess. I solved it by simple putting FirstOrDefault at the end.</p>
[ { "answer_id": 342881, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 3, "selected": true, "text": "DoCmd.RunSQL Public Function SQLRun(strSQL As String) As Boolean\nOn Error GoTo errHandler\n\n CurrentDB.Execute strSQL, dbFailOnError\n SQLRun= True\n\nexitRoutine:\n Exit Function\n\nerrHandler:\n MsgBox err.Number & \": \" & err.Description, vbExclamation, \"Error in SQLRun()\"\n Resume exitRoutine\nEnd Function\n DoCmd.RunSQL SQLRun" }, { "answer_id": 30557650, "author": "Avagut", "author_id": 2849004, "author_profile": "https://Stackoverflow.com/users/2849004", "pm_score": 2, "selected": false, "text": "sqltext = \"update table employees set bonus = 0 where salary > 50000\"\nCurrentDb.Execute sqltext\nAffectedRows = CurrentDb.RecordsAffected\n'Optional Notification\n MsgBox CStr(AffectedRows) & \" records were affected by this SQL statement.\"\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
333,876
<p>Is there some way to determine what file currently is being rendered by Rails (2.2) in a helper method. An example result would be "/sessions/new.html.erb" or something similar.</p> <p>I am trying to write a helper function that does something based on the file name that is being rendered, so I need a reliable way to obtain this information. Is there an official way to get this information?</p>
[ { "answer_id": 342881, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 3, "selected": true, "text": "DoCmd.RunSQL Public Function SQLRun(strSQL As String) As Boolean\nOn Error GoTo errHandler\n\n CurrentDB.Execute strSQL, dbFailOnError\n SQLRun= True\n\nexitRoutine:\n Exit Function\n\nerrHandler:\n MsgBox err.Number & \": \" & err.Description, vbExclamation, \"Error in SQLRun()\"\n Resume exitRoutine\nEnd Function\n DoCmd.RunSQL SQLRun" }, { "answer_id": 30557650, "author": "Avagut", "author_id": 2849004, "author_profile": "https://Stackoverflow.com/users/2849004", "pm_score": 2, "selected": false, "text": "sqltext = \"update table employees set bonus = 0 where salary > 50000\"\nCurrentDb.Execute sqltext\nAffectedRows = CurrentDb.RecordsAffected\n'Optional Notification\n MsgBox CStr(AffectedRows) & \" records were affected by this SQL statement.\"\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42431/" ]
333,889
<p>Why does C++ have header files and .cpp files?</p>
[ { "answer_id": 333964, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 9, "selected": false, "text": "// A.CPP\nvoid doSomething()\n{\n doSomethingElse(); // Defined in B.CPP\n}\n\n// B.CPP\nvoid doSomethingElse()\n{\n // Etc.\n}\n // A.CPP\nvoid doSomethingElse() ; // From B.CPP\n\nvoid doSomething()\n{\n doSomethingElse() ; // Defined in B.CPP\n}\n // B.HPP (here, we decided to declare every symbol defined in B.CPP)\nvoid doSomethingElse() ;\n\n// A.CPP\n#include \"B.HPP\"\n\nvoid doSomething()\n{\n doSomethingElse() ; // Defined in B.CPP\n}\n\n// B.CPP\n#include \"B.HPP\"\n\nvoid doSomethingElse()\n{\n // Etc.\n}\n\n// C.CPP\n#include \"B.HPP\"\n\nvoid doSomethingAgain()\n{\n doSomethingElse() ; // Defined in B.CPP\n}\n include // A.HPP\nvoid someFunction();\nvoid someOtherFunction();\n // B.CPP\n#include \"A.HPP\"\n\nvoid doSomething()\n{\n // Etc.\n}\n // B.CPP\nvoid someFunction();\nvoid someOtherFunction();\n\nvoid doSomething()\n{\n // Etc.\n}\n doSomethingElse doSomethingElse #ifndef B_HPP_\n#define B_HPP_\n\n// The declarations in the B.hpp file\n\n#endif // B_HPP_\n #pragma once\n\n// The declarations in the B.hpp file\n" }, { "answer_id": 9508122, "author": "Alex v", "author_id": 1241439, "author_profile": "https://Stackoverflow.com/users/1241439", "pm_score": -1, "selected": false, "text": "class A {..};\nclass B : public A {...};\n\nclass C {\n include A.cpp;\n include B.cpp;\n .....\n};\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
333,911
<p>I'm getting crazy with this IE 7...</p> <p>==> hhttp://neu.emergent-innovation.com/</p> <p>Why does following function not work in IE 7, but perfectly with Firefox? Is there a bug in the animate-function?</p> <pre><code>function accordion_starting_page(){ // hide all elements except the first one $('#FCE-Inhalt02-ContentWrapper .FCE-Fade:not(:first)').css("height", "0").hide(); $('#FCE-Inhalt02-ContentWrapper .FCE-Fade:first').addClass("isVisible"); $('div.FCE-Title').click(function(){ // if user clicks on an already opened element =&gt; do nothing if (parseFloat($(this).next('.FCE-Fade').css("height")) &gt; 0) { return false; } var toHide = $(this).siblings('.FCE-Fade.isVisible'); toHide.removeClass("isVisible"); // close all opened siblings toHide.animate({"height": "0", "display": "none"}, 1000); $(this).next('.FCE-Fade').addClass("isVisible").animate({"height" : "200"}, 1000); return false; }); } </code></pre> <p>Thank you very much for your help...</p> <hr> <p>Thank you very much, those were great hints! Unfortunately, it still doesn't work...</p> <p>The problem is that IE shows the content of both containers until the animation is over... Firefox behaves correctly... I thought it's the thing with "overflow: hidden" - but that didn't change anything.</p> <p>I already tried the accordion-plugin, but it behaves exactly the same...</p>
[ { "answer_id": 333975, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "display: none toHide.animate({ height : 0 }, 1000, function() { $(this).hide(); });\n overflow: hidden" }, { "answer_id": 491221, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "var re = /px/;\nvar currentLeft = $(\"#mydiv\").css('left').replace(re,'') - 0;\n$(\"#mydiv\").css('left',(currentLeft-20)+'px');\n #mydiv { position: absolute; top: 0; left: 0; }\n" }, { "answer_id": 2552944, "author": "Tadeu Luis", "author_id": 282221, "author_profile": "https://Stackoverflow.com/users/282221", "pm_score": 2, "selected": true, "text": "li p (bottom:-178px; color: white; background-color: # 4d4d4d; height: 100%; padding: 30px 10px 0 10px;)\n $('li').hover(function(){\n\n $this = $(this);\n\n var bottom = '-45px'; //valor default para subir.\n\n if( $this.css('height') == '320px' ){bottom = '-115px';}\n\n $this.css('cursor', 'pointer').find('p').stop().find('.first').hide().end().animate({bottom: bottom}, {queue:false, duration:300});\n\n }, function(){\n\n var $this = $(this);\n\n var bottom = '-178px'; //valor default para descer\n\n if( $this.css('height') == '320px' ){bottom = '-432px';}\n\n $this.find('p').stop().animate({***position: 'absolute'***, bottom:bottom}, {queue:false, duration:300}).find('.first').show();\n\n });//fim do hover()\n li p (position: absolute; left: 0; bottom:-178px; color: white; background-color: # 4d4d4d; height: 100%; padding: 30px 10px 0 10px;)\n $('li').hover(function(){\n\n $this = $(this);\n\n var bottom = '-45px'; //valor default para subir.\n\n if( $this.css('height') == '320px' ){bottom = '-115px';}\n\n $this.css('cursor', 'pointer').find('p').stop().find('.first').hide().end().animate({bottom: bottom}, {queue:false, duration:300});\n\n }, function(){\n\n var $this = $(this);\n\n var bottom = '-178px'; //valor default para descer\n\n if( $this.css('height') == '320px' ){bottom = '-432px';}\n\n $this.find('p').stop().animate({bottom:bottom}, {queue:false, duration:300}).find('.first').show();\n\n });//fim do hover()\n" }, { "answer_id": 2829068, "author": "John K", "author_id": 340552, "author_profile": "https://Stackoverflow.com/users/340552", "pm_score": 0, "selected": false, "text": "$(\"#map\").animate({\"top\": (pageY - 101) + \"px\"},{\"easing\" : \"linear\", \"duration\" : 200});\n $(\"#map\").animate({\"top\": (pageY - 101) + \"px\"},{\"easing\" : \"linear\", \"duration\" : 20});\n" }, { "answer_id": 6181213, "author": "Mladen", "author_id": 776845, "author_profile": "https://Stackoverflow.com/users/776845", "pm_score": 1, "selected": false, "text": "$('#bs1').animate({\n \"left\": bs1x\n}, 300, function() {\n // Animation complete.\n});\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27404/" ]
333,946
<p>How would you write ToUpper() if it didn't exist? Bonus points for i18n and L10n</p> <p>Curiosity sparked by this: <a href="http://thedailywtf.com/Articles/The-Long-Way-toUpper.aspx" rel="nofollow noreferrer">http://thedailywtf.com/Articles/The-Long-Way-toUpper.aspx</a></p>
[ { "answer_id": 333971, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": false, "text": "(string-upcase \"Straße\") ⇒ \"STRASSE\"\n(string-downcase \"Straße\") ⇒ \"straße\"\n(string-upcase \"ΧΑΟΣ\") ⇒ \"ΧΑΟΣ\"\n(string-downcase \"ΧΑΟΣ\") ⇒ \"χαος\"\n(string-downcase \"ΧΑΟΣΣ\") ⇒ \"χαοσς\"\n(string-downcase \"ΧΑΟΣ Σ\") ⇒ \"χαος σ\"\n(string-upcase \"χαος\") ⇒ \"ΧΑΟΣ\"\n(string-upcase \"χαοσ\") ⇒ \"ΧΑΟΣ\"\n" }, { "answer_id": 333972, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 1, "selected": false, "text": "char toupper(char c)\n{\n if ((c < 'a') || (c > 'z')) { return c; }\n else { return c & 0xdf; }\n}" }, { "answer_id": 334006, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 0, "selected": false, "text": "touppe_map = { massive dictionary to handle all cases in all languages }\ndef to_upper( c ):\n return toupper_map.get( c, c )\n def to_upper( c ):\n for k,v in toupper_map.items():\n if k == c: return v\n return c\n" }, { "answer_id": 334091, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 3, "selected": false, "text": "i İ I i" }, { "answer_id": 334142, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 4, "selected": true, "text": "public static String upper(String s) {\n if (s == null) {\n return null;\n }\n\n final int N = s.length(); // Mind the optimization!\n PreparedStatement stmtName = null;\n PreparedStatement stmtSmall = null;\n ResultSet rsName = null;\n ResultSet rsSmall = null;\n StringBuilder buffer = new StringBuilder (N); // Much faster than StringBuffer!\n try {\n conn = DBFactory.getConnection();\n stmtName = conn.prepareStatement(\"select name from unicode.chart where codepoint = ?\");\n // TODO Optimization: Maybe move this in the if() so we don't create this\n // unless there are uppercase characters in the string.\n stmtSmall = conn.prepareStatement(\"select codepoint from unicode.chart where name = ?\");\n for (int i=0; i<N; i++) {\n int c = s.charAt(i);\n stmtName.setInt(1, c);\n rsName = stmtName.execute();\n if (rsName.next()) {\n String name = rsName.getString(1);\n if (name.contains(\" SMALL \")) {\n name = name.replaceAll(\" SMALL \", \" CAPITAL \");\n\n stmtSmall.setString(1, name);\n rsSmall = stmtSmall.execute();\n if (rsSmall.next()) {\n c = rsSmall.getInt(1);\n }\n\n rsSmall = DBUtil.close(rsSmall);\n }\n }\n rsName = DBUtil.close(rsName);\n }\n }\n finally {\n // Always clean up\n rsSmall = DBUtil.close(rsSmall);\n rsName = DBUtil.close(rsName);\n stmtSmall = DBUtil.close(stmtSmall);\n stmtName = DBUtil.close(stmtName);\n }\n\n // TODO Optimization: Maybe read the table once into RAM at the start\n // Would waste a lot of memory, though :/\n return buffer.toString();\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12744/" ]
333,953
<p>Is there a C# equivalent method to Java's <code>Exception.printStackTrace()</code> or do I have to write something myself, working my way through the InnerExceptions?</p>
[ { "answer_id": 333966, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 8, "selected": true, "text": "Console.WriteLine(ex.ToString());\n ToString System.Object ToString" }, { "answer_id": 333973, "author": "Steve Brouillard", "author_id": 26516, "author_profile": "https://Stackoverflow.com/users/26516", "pm_score": 2, "selected": false, "text": " catch (Exception ex)\n{\n Console.WriteLine(ex.StackTrace);\n}\n" }, { "answer_id": 333979, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "using System;\n\nclass Test\n{\n static void Main()\n {\n try\n {\n ThrowException();\n }\n catch (Exception e)\n {\n Console.WriteLine(e);\n }\n }\n\n static void ThrowException()\n {\n\n try\n {\n ThrowException2();\n }\n catch (Exception e)\n {\n throw new Exception(\"Outer\", e);\n }\n }\n\n static void ThrowException2()\n {\n throw new Exception(\"Inner\");\n }\n}\n System.Exception: Outer ---> System.Exception: Inner\n at Test.ThrowException2()\n at Test.ThrowException()\n --- End of inner exception stack trace ---\n at Test.ThrowException()\n at Test.Main()\n" }, { "answer_id": 339899, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 7, "selected": false, "text": "Console.WriteLine(System.Environment.StackTrace);\n" }, { "answer_id": 59930612, "author": "gianlucaparadise", "author_id": 6155481, "author_profile": "https://Stackoverflow.com/users/6155481", "pm_score": 0, "selected": false, "text": "System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();\nConsole.WriteLine(stackTrace)\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
333,965
<p>I'm trying to write a query for an advanced search page on my document archiving system. I'm attempting to search by multiple optional parameters. I have about 5 parameters that could be empty strings or search strings. I know I shouldn't have to check for each as a string or empty and create a separate stored procedure for each combination.</p> <p>Edit: Ended up using:</p> <pre><code>ISNULL(COALESCE(@var, a.col), '') = ISNULL(a.col, '') </code></pre>
[ { "answer_id": 333974, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "WHERE \n (@var1 = '' OR col1 = @var1) AND\n (@var2 = '' OR col1 = @var2) AND\n (@var3 = '' OR col1 = @var3) ...\n" }, { "answer_id": 333984, "author": "edosoft", "author_id": 6399, "author_profile": "https://Stackoverflow.com/users/6399", "pm_score": 4, "selected": true, "text": "WHERE COALESCE(@var1, col1) = col1 \nAND COALESCE(@var2, col2) = col2 \nAND COALESCE(@var3, col3) = col3\n" }, { "answer_id": 334003, "author": "clyc", "author_id": 29702, "author_profile": "https://Stackoverflow.com/users/29702", "pm_score": 3, "selected": false, "text": "WHERE (@var1 IS NULL OR col1 = @var1)\nAND (@var2 IS NULL OR col2 = @var2)\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491425/" ]
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be passed debug options too.</p>
[ { "answer_id": 334073, "author": "dowski", "author_id": 21712, "author_profile": "https://Stackoverflow.com/users/21712", "pm_score": 1, "selected": false, "text": "$ USING_PDB=1 pdb yourprog.py\n import os\nif os.environ.get('USING_PDB'):\n # debugging actions\n pass\n" }, { "answer_id": 334090, "author": "babbageclunk", "author_id": 38851, "author_profile": "https://Stackoverflow.com/users/38851", "pm_score": 5, "selected": false, "text": "sys.settrace sys sys.gettrace() None" }, { "answer_id": 334612, "author": "do3cc", "author_id": 39345, "author_profile": "https://Stackoverflow.com/users/39345", "pm_score": 1, "selected": false, "text": "import inspect\ninspect.getouterframes(inspect.currentframe()\n" }, { "answer_id": 338391, "author": "Stéphane Bonniez", "author_id": 11618, "author_profile": "https://Stackoverflow.com/users/11618", "pm_score": 5, "selected": true, "text": "import inspect\n\ndef isdebugging():\n for frame in inspect.stack():\n if frame[1].endswith(\"pydevd.py\"):\n return True\n return False\n pydevd.py pdb.py" }, { "answer_id": 7546741, "author": "Mvoicem", "author_id": 867844, "author_profile": "https://Stackoverflow.com/users/867844", "pm_score": 3, "selected": false, "text": "import sys\nif 'pydevd' in sys.modules: \n print \"Debugger\"\nelse:\n print \"commandline\"\n" }, { "answer_id": 8028466, "author": "Travelling Man", "author_id": 246627, "author_profile": "https://Stackoverflow.com/users/246627", "pm_score": 3, "selected": false, "text": "__debug__\nThis constant is true if Python was not started with an -O option.\n if __debug__:\n print 'Python started without optimization'\n" }, { "answer_id": 22724125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "manage.py #!/usr/bin/env python\nimport os\nimport sys\n\nif __debug__:\n sys.path.append('/path/to/views.py')\n\n\nif __name__ == \"__main__\":\n ....\n" }, { "answer_id": 26605963, "author": "jordeu", "author_id": 1078883, "author_profile": "https://Stackoverflow.com/users/1078883", "pm_score": 4, "selected": false, "text": "try:\n import pydevd\n DEBUGGING = True\nexcept ImportError:\n DEBUGGING = False\n" }, { "answer_id": 69457243, "author": "Adam Smooch", "author_id": 10761353, "author_profile": "https://Stackoverflow.com/users/10761353", "pm_score": 0, "selected": false, "text": "from sys import gettrace as sys_gettrace\n\nDEBUG = sys_gettrace() is not None\nprint(\"debugger? %s\" % DEBUG)\n" }, { "answer_id": 71946445, "author": "snoopyjc", "author_id": 11397243, "author_profile": "https://Stackoverflow.com/users/11397243", "pm_score": 0, "selected": false, "text": "if 'pdb' in sys.modules:\n # We are being debugged\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/333995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11618/" ]
334,038
<p>In a Swing app a method should continue only after user enters a correct answer. The correct answer is stored in a <code>String</code> with user answer being set by a listener to another <code>String</code>. So, the code is</p> <pre><code>while (!correctAnswer.equals(currentAnswer)) { // wait for user to click the button with the correct answer typed into the textfield } // and then continue </code></pre> <p>Is everything fine with this approach or would you somehow refactor it? Doesn't it impose extra penalty on CPU? Here's a somewhat <a href="https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop" title="Best refactoring for the dreaded While (True) loop">similar question</a>.</p>
[ { "answer_id": 334056, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "do-while" }, { "answer_id": 334064, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 4, "selected": true, "text": "ActionListener" }, { "answer_id": 334145, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 3, "selected": false, "text": "ActionListener actionPerformed ...\nfinal JTextField textField = new JTextField();\nfinal JButton okButton = new JButton(\"OK\");\nokButton.addActionListner(new ActionListener() {\n public void actionPerformed(ActionEvent e)\n {\n if (\"some text\".equals(textField.getText()))\n System.out.println(\"Yes, text matches.\");\n else\n System.out.println(\"No, text does not match.\");\n }\n});\n...\n ActionListener final if textField.getText().equals(\"some text\") \"some text\".equals(textField.getText()) NullPointerException textField null" }, { "answer_id": 336121, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "// * used for brevity. Preffer single class per import\nimport javax.swing.*;\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.net.*;\nimport java.io.*;\n\n\npublic class MatchString{\n\n private final JTextField password;\n private final JFrame frame;\n\n public static void main( String [] args ){\n MatchString.show();\n }\n\n public static void show(){\n SwingUtilities.invokeLater( new Runnable(){\n public void run(){\n new MatchString();\n }\n });\n }\n\n private MatchString(){\n password = new JPasswordField( 20 );\n frame = new JFrame(\"Go to www.stackoverflow\");\n init();\n frame.pack();\n frame.setVisible( true );\n }\n\n\n private void init(){\n\n frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n\n frame.add( new JPanel(){{\n add( new JLabel(\"Password:\"));\n add( password );\n }});\n\n // This is the key of this question.\n // the password textfield is added an \n // action listener\n // When the user press enter, the method \n // validatePassword() is invoked.\n password.addActionListener( new ActionListener(){\n public void actionPerformed( ActionEvent e ) {\n validatePassword();\n }\n });\n }\n\n\n private void validatePassword(){ \n // If the two strings match\n // then continue with the flow\n // in this case, open SO site. \n if ( \"stackoverflow\".equals(password.getText())) try {\n Desktop.getDesktop().browse( new URI(\"http://stackoverflow.com\"));\n frame.dispose();\n } catch ( IOException ioe ){\n showError( ioe.getMessage() );\n } catch ( URISyntaxException use ){\n showError( use.getMessage() );\n } else {\n // If didn't match.. clear the text.\n password.setText(\"\");\n }\n }\n }\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
334,057
<p>I have a very simple html page here:</p> <p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22407" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22407</a></p> <p>And I have 4 layers on the page. The reason for this is it is the framework oif a much more complicated site, I have simplified it to ask my question. Basically, I want to be able to click on different links in layer 2 and have the image in layer1 change, however The way I have found to do this:</p> <pre><code>&lt;script type="text/javascript"&gt;&lt;!-- function sbox(boxName,xname) { theBox = document.getElementById(boxName); theBox.className = xname; } //--&gt; &lt;/script&gt; </code></pre> <p>Results in the text nto going away, which I need, as well as a way to click and replace whatever image is there with the text. I found alternative javascript code, but could not apply it to my html page.</p> <pre><code>&lt;script type="text/javascript"&gt; function toggleImg(myid) { objtxt = document.getElementById(myid); objimg = document.getElementById(myid+'_img'); if( objtxt.style.display == 'block' ) { // Show image, hide text objtxt.style.display = 'none'; objimg.style.display = 'block'; } else { // Hide image, show text objimg.style.display = 'none'; objtxt.style.display = 'block'; } } &lt;/script&gt; </code></pre> <p>What is the easiest way to do this without changing the design of my page? note: I do not want to use a framework, I want to understand how this is done and do it for myself.</p> <p>My additional question is on if layers should replace tables: Is it always bad to use tables when css could be used instead? Is it easy to use layers to make row and column equivalents just to format text data, not the structure of a site?</p>
[ { "answer_id": 334146, "author": "Carl", "author_id": 38375, "author_profile": "https://Stackoverflow.com/users/38375", "pm_score": 0, "selected": false, "text": "<html>\n <head>\n <style type=\"text/css\">\n .class1{color:#000;}\n .class2{color:#00f;}\n .class3{color:#0f0;}\n .class4{color:#f00; background-image:url('someimage.jpg');}\n </style>\n </head>\n <body>\n <script type=\"text/javascript\">\n function sbox(divid, classname)\n {\n document.getElementById(divid).className=classname;\n if(document.getElementById(divid+\"_text\")!=null)\n document.getElementById(divid+\"_text\").style.display=\"none\";\n }\n </script>\n <div>\n <a href=\"#\" onclick=\"sbox('div1','class2');return false;\">Test Div1, Class2(blue)</a><br/>\n <a href=\"#\" onclick=\"sbox('div1','class3'); return false;\">Test Div1, Class3(green)</a><br/>\n <a href=\"#\" onclick=\"sbox('div1','class4');return false;\">Test Div1, Class4(red)</a>\n </div>\n <div id=\"div1\" class=\"class1\"><span id=\"div1_text\">Blah blah blah</span></div>\n </body>\n</html>\n" }, { "answer_id": 334318, "author": "Carl", "author_id": 38375, "author_profile": "https://Stackoverflow.com/users/38375", "pm_score": 1, "selected": true, "text": "<html>\n <head>\n <style type=\"text/css\">\n .class1{color:#000;}\n .class2{color:#00f;}\n .class3{color:#0f0;}\n .class4{color:#f00; background-image:url('someimage.jpg');}\n .class4 span { display: none;}\n </style>\n </head>\n <body>\n <script type=\"text/javascript\">\n function sbox(divid, classname)\n {\n document.getElementById(divid).className=classname;\n }\n </script>\n <div>\n <a href=\"#\" onclick=\"sbox('div1','class1');return false;\">Reset</a><br/>\n <a href=\"#\" onclick=\"sbox('div1','class2');return false;\">Test Div1, Class2(blue)</a><br/>\n <a href=\"#\" onclick=\"sbox('div1','class3'); return false;\">Test Div1, Class3(green)</a><br/>\n <a href=\"#\" onclick=\"sbox('div1','class4');return false;\">Test Div1, Class4(red)</a>\n </div>\n <div id=\"div1\" class=\"class1\"><span id=\"div1_text\">Blah blah blah</span></div>\n </body>\n</html>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
334,095
<p>I have been trying to get more in to TDD. Currently keeping it simple with lots of <code>Debug.Asserts</code> in a console application.</p> <p>Part of the tests I wanted to complete was ensuring that events were raised from the object, the correct number of times, since client code will depend on these events.</p> <p>So, I began thinking about how to test the events were being raised, and how I could track them. So I came up with a <strong>Monitor</strong> "pattern" (if you could call it that). This is basically a class that takes an object of the type under test in its constructor.</p> <p>The events are then hooked up to the monitor, with delegates created which both count and log when the event is raised.</p> <p>I then go back to my test code and do something like:</p> <pre><code> bool Test() { MyObject mo = new MyObject(); MyMonitor mon = new MyMonitor(mo); // Do some tests that should cause the object to raise events.. return mon.EventCount == expectedCount; } </code></pre> <p>This works fine, and when I intentionally busted my code, the tests failed as expected, but <strong>I wonder, is this too much "free form" test code (i.e. code without supporting tests)?</strong></p> <hr> <p><strong>Additional Thoughts</strong></p> <ul> <li>Do you test for events?</li> <li><em>How</em> do you test for events?</li> <li>Do you think the above has any holes/room for improvement?</li> </ul> <p>All input gratefully received! <code>^_^</code></p>
[ { "answer_id": 334118, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 3, "selected": true, "text": "MyObject subjectUnderTest = new MyObject();\nEventMonitor monitor = new Monitor();\nsubjectUnderTest.Event += monitor.EventCatcher;\n\n// testcode;\n\nAssert.Equal( 1, monitor.EventsFired );\n public interface IEventHandlerStub\n{\n event EventHandler<T> Event(object sender, T arguments);\n}\n var eventHandlerStub = MockRepository.GenerateStub<IEventHandlerStub>();\nmyObject.Event += eventHandlerStub.Event;\n\n// Run your code\n\neventHandlerStub.AssertWasCalled(x => x.Event(null, null));\n" }, { "answer_id": 334152, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "private int counterEvent;\n\n[Test]\npublic void abcTest()\n{\n counterEvent = 0;\n //1- Initialize object to test\n //2- Set the event to test (abcTest_event for example)\n //Assert the object incremented (counterEvent for example)\n}\n\nprivate void abcTest_event(object sender)\n{\n counterEvent++;\n}\n" }, { "answer_id": 334445, "author": "Ilja Preuß", "author_id": 11765, "author_profile": "https://Stackoverflow.com/users/11765", "pm_score": 1, "selected": false, "text": "FooListener listener = createMock(FooListener.class);\nexpect(listener.someEvent());\nreplay(listener);\nmyObject.addListener(listener);\nmyObject.doSomethingThatFiresEvent();\nverify(listener);\n" }, { "answer_id": 2693767, "author": "Tim Lloyd", "author_id": 189516, "author_profile": "https://Stackoverflow.com/users/189516", "pm_score": 2, "selected": false, "text": "AsyncEventPublisher publisher = new AsyncEventPublisher();\n\nAction test = () =>\n{\n publisher.RaiseA();\n publisher.RaiseB();\n publisher.RaiseC();\n};\n\nvar expectedSequence = new[] { \"EventA\", \"EventB\", \"EventC\" };\n\nEventMonitor.Assert(test, publisher, expectedSequence, TimeoutMS);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
334,102
<p>When trying to launch and run a flex/java project in eclipse I kept getting a "Out of Memory Exception" and "Java Heap Space" using Eclipse, Tomcat and a JRE.</p> <p>While researching trying to adjust the memory settings I found three places to adjust these:</p> <ul> <li><p>Eclipse.ini</p></li> <li><p>The JRE Settings under Window > Preferences</p></li> <li><p>Catalina.sh or Catalina.bat</p></li> </ul> <p>What are the differences between setting -xms and -xmx in these different places and what does is mean?</p> <p>Is there any way to verify these memory settings are being set accordingly?</p> <p>What are the optimal -xms and -xmx settings for a computer with 2gb of RAM?</p> <p>Any other memory tips?</p> <p>Thanks.</p>
[ { "answer_id": 334254, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 4, "selected": false, "text": "-xms -xmx -xmx -xmx -xmx" }, { "answer_id": 1720281, "author": "Andreas Mattisson", "author_id": 209334, "author_profile": "https://Stackoverflow.com/users/209334", "pm_score": 1, "selected": false, "text": "Heap\n def new generation total 36352K, used 11534K [0x10040000, 0x127b0000, 0x14f00000)\n eden space 32320K, 29% used [0x10040000, 0x10994c30, 0x11fd0000)\n from space 4032K, 49% used [0x123c0000, 0x125aed80, 0x127b0000)\n to space 4032K, 0% used [0x11fd0000, 0x11fd0000, 0x123c0000)\n tenured generation total 483968K, used 125994K [0x14f00000, 0x327a0000, 0x50040000)\n the space 483968K, 26% used [0x14f00000, 0x1ca0ab38, 0x1ca0ac00, 0x327a0000)\n compacting perm gen total 58112K, used 57928K [0x50040000, 0x53900000, 0x60040000)\n the space 58112K, 99% used [0x50040000, 0x538d2160, 0x538d2200, 0x53900000)\nNo shared spaces configured.\n -showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n1024M\n-framework\nplugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-XX:MaxPermSize=256m\n-Xms512m\n-Xmx1024m\n" }, { "answer_id": 3111704, "author": "dmatej", "author_id": 375449, "author_profile": "https://Stackoverflow.com/users/375449", "pm_score": 1, "selected": false, "text": "-vmargs\n...\n-Duser.name=...\n-XX:PermSize=256m\n-XX:MaxPermSize=256m\n-Xmn128m\n-Xms256m\n-Xmx768m\n" }, { "answer_id": 9993926, "author": "Adrian Pirvulescu", "author_id": 129270, "author_profile": "https://Stackoverflow.com/users/129270", "pm_score": 2, "selected": false, "text": "-vm\nC:/jdk1.6.0_25/bin\n-startup\nplugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar\n–launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502\n-product\norg.eclipse.epp.package.jee.product\n–launcher.defaultAction\nopenFile\n–launcher.XXMaxPermSize\n256M\n-showsplash\norg.eclipse.platform\n–launcher.XXMaxPermSize\n256m\n–launcher.defaultAction\nopenFile\n-vmargs\n-server\n-Dosgi.requiredJavaVersion=1.5\n-Xmn128m\n-Xms1024m\n-Xmx1024m\n-Xss2m\n-XX:PermSize=128m\n-XX:MaxPermSize=128m\n-XX:+UseParallelGC\n" }, { "answer_id": 12664000, "author": "Tarun", "author_id": 363075, "author_profile": "https://Stackoverflow.com/users/363075", "pm_score": 0, "selected": false, "text": "-vmargs -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:PermSize=64m\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23133/" ]
334,108
<p>I want to check for data, but ignore it if it's null or empty. Currently the query is as follows...</p> <pre><code>Select Coalesce(listing.OfferText, company.OfferText, '') As Offer_Text, from tbl_directorylisting listing Inner Join tbl_companymaster company On listing.company_id= company.company_id </code></pre> <p>But I want to get <code>company.OfferTex</code>t if <code>listing.Offertext</code> is an empty string, as well as if it's null.</p> <p>What's the best performing solution?</p>
[ { "answer_id": 334115, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": false, "text": "SELECT\n CASE WHEN LEN(listing.OfferText) > 0 THEN listing.OfferText \n ELSE COALESCE(Company.OfferText, '') END \n AS Offer_Text,\n\n... \n listing.OfferText COALESCE(NULLIF(listing.OfferText,''), Company.OfferText, '')\n Company.OfferText NULLIF()" }, { "answer_id": 334122, "author": "Patrick Harrington", "author_id": 41165, "author_profile": "https://Stackoverflow.com/users/41165", "pm_score": 5, "selected": false, "text": "Select \nCASE\n WHEN listing.OfferText is null or listing.OfferText = '' THEN company.OfferText\n ELSE COALESCE(Company.OfferText, '')\nEND As Offer_Text, \nfrom tbl_directorylisting listing \n Inner Join tbl_companymaster company \n On listing.company_id= company.company_id\n" }, { "answer_id": 334125, "author": "Code Trawler", "author_id": 22073, "author_profile": "https://Stackoverflow.com/users/22073", "pm_score": 4, "selected": false, "text": "ISNULL SELECT case when ISNULL(col1, '') = '' then '' else col1 END AS COL1 FROM TEST\n" }, { "answer_id": 334128, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 2, "selected": false, "text": "Select \nCoalesce(Case When Len(listing.Offer_Text) = 0 Then Null Else listing.Offer_Text End, company.Offer_Text, '') As Offer_Text, \nfrom tbl_directorylisting listing \n Inner Join tbl_companymaster company \n On listing.company_id= company.company_id\n" }, { "answer_id": 677426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "SELECT Isnull(Nullif(listing.offertext, ''), company.offertext) AS offer_text, \nFROM tbl_directorylisting listing \n INNER JOIN tbl_companymaster company \n ON listing.company_id = company.company_id\n" }, { "answer_id": 3235307, "author": "Martin Ba", "author_id": 321013, "author_profile": "https://Stackoverflow.com/users/321013", "pm_score": 10, "selected": true, "text": "SELECT \n ISNULL(NULLIF(listing.Offer_Text, ''), company.Offer_Text) AS Offer_Text\nFROM ...\n // a) NULLIF:\nif (listing.Offer_Text == '')\n temp := null;\nelse\n temp := listing.Offer_Text; // may now be null or non-null, but not ''\n// b) ISNULL:\nif (temp is null)\n result := true;\nelse\n result := false;\n" }, { "answer_id": 11700429, "author": "Code Crawler", "author_id": 1511606, "author_profile": "https://Stackoverflow.com/users/1511606", "pm_score": 2, "selected": false, "text": "Empty Null ..... WHERE Column_name != '' or 'null'" }, { "answer_id": 14348633, "author": "Anoop Verma", "author_id": 1951057, "author_profile": "https://Stackoverflow.com/users/1951057", "pm_score": 2, "selected": false, "text": "SELECT \n COALESCE(listing.OfferText, 'company.OfferText') AS Offer_Text, \nFROM \n tbl_directorylisting listing \n INNER JOIN tbl_companymaster company ON listing.company_id= company.company_id\n" }, { "answer_id": 16539726, "author": "Romain Durand", "author_id": 1085411, "author_profile": "https://Stackoverflow.com/users/1085411", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM tbl_directorylisting listing\nWHERE (civilite_etudiant IS NULL)\n" }, { "answer_id": 18711567, "author": "Muhammad Sharjeel Ahsan", "author_id": 1165902, "author_profile": "https://Stackoverflow.com/users/1165902", "pm_score": 2, "selected": false, "text": "Select \nCoalesce(NullIf(listing.OfferText, ''), NullIf(company.OfferText, ''), '') As Offer_Text, \nfrom tbl_directorylisting listing \n Inner Join tbl_companymaster company \n On listing.company_id= company.company_id\n" }, { "answer_id": 25073939, "author": "lkurylo", "author_id": 453396, "author_profile": "https://Stackoverflow.com/users/453396", "pm_score": 4, "selected": false, "text": "IIF SELECT IIF(field IS NULL, 1, 0) AS IsNull\n" }, { "answer_id": 32570972, "author": "Zach Johnson", "author_id": 1181012, "author_profile": "https://Stackoverflow.com/users/1181012", "pm_score": 3, "selected": false, "text": "SELECT \n CASE WHEN NULL > 0 THEN 'NULL > 0 = true' ELSE 'NULL > 0 = false' END,\n CASE WHEN LEN(NULL) > 0 THEN 'LEN(NULL) = true' ELSE 'LEN(NULL) = false' END,\n CASE WHEN LEN('') > 0 THEN 'LEN('''') > 0 = true' ELSE 'LEN('''') > 0 = false' END,\n CASE WHEN LEN(' ') > 0 THEN 'LEN('' '') > 0 = true' ELSE 'LEN('' '') > 0 = false' END,\n CASE WHEN LEN(' test ') > 0 THEN 'LEN('' test '') > 0 = true' ELSE 'LEN('' test '') > 0 = false' END\n" }, { "answer_id": 35025034, "author": "contactmatt", "author_id": 175057, "author_profile": "https://Stackoverflow.com/users/175057", "pm_score": 2, "selected": false, "text": "SELECT \n Coalesce(NULLIF(listing.OfferText, ''), company.OfferText) As Offer_Text\n...\n" }, { "answer_id": 45153954, "author": "user3829854", "author_id": 3829854, "author_profile": "https://Stackoverflow.com/users/3829854", "pm_score": 2, "selected": false, "text": "[Column_name] IS NULL OR LEN(RTRIM(LTRIM([Column_name]))) = 0\n" }, { "answer_id": 45924905, "author": "Milan", "author_id": 1438675, "author_profile": "https://Stackoverflow.com/users/1438675", "pm_score": 3, "selected": false, "text": "...WHEN LEN(ISNULL(MyField, '')) < 1 THEN NewValue...\n" }, { "answer_id": 53706093, "author": "Fábio Nascimento", "author_id": 1331310, "author_profile": "https://Stackoverflow.com/users/1331310", "pm_score": 2, "selected": false, "text": "IF LEN(ISNULL(@var, '')) = 0\n -- Is empty or NULL\nELSE\n -- Is not empty and is not NULL\n" }, { "answer_id": 58617281, "author": "ramit girdhar", "author_id": 1070820, "author_profile": "https://Stackoverflow.com/users/1070820", "pm_score": 0, "selected": false, "text": "(len(rtrim(ltrim(isnull(MyField,'')))) !=0\n" }, { "answer_id": 64259017, "author": "Vedran", "author_id": 769137, "author_profile": "https://Stackoverflow.com/users/769137", "pm_score": 1, "selected": false, "text": "VARCHAR NVARCHAR IsNullOrWhiteSpace IsNullOrEmpty IIF(ISNULL(DATALENGTH(val), 0) = 0, whenTrueValue, whenFalseValue)\n SELECT\n '\"' + val + '\"' AS [StrValue],\n IIF(ISNULL(DATALENGTH(val), 0) = 0, 'TRUE', 'FALSE') AS IsNullOrEmpty\nFROM ( VALUES \n (NULL), \n (''), \n (' '), \n ('a'), \n ('a ')\n) S (val)\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
334,123
<p>I need a regex for the following pattern:</p> <ul> <li><p>Total of 5 characters (alpha and numeric, nothing else).</p></li> <li><p>first character must be a letter (<code>A</code>, <code>B</code>, or <code>C</code> only)</p></li> <li><p>the remaining 4 characters can be number or letter.</p></li> </ul> <p>Clarifcation: the first letter can only be <code>A</code>, <code>B</code>, or <code>C</code>.</p> <p>Examples:</p> <ul> <li><code>A1234</code> is valid</li> <li><code>D1234</code> is invalid</li> </ul>
[ { "answer_id": 334134, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 7, "selected": true, "text": "^[A-C][a-zA-Z0-9]{4}$\n ^ $ [A-C] A B C [a-zA-Z0-9]{4}" }, { "answer_id": 334143, "author": "Martin", "author_id": 18660, "author_profile": "https://Stackoverflow.com/users/18660", "pm_score": 3, "selected": false, "text": "[A-C][A-Za-z0-9]{4}\n" }, { "answer_id": 334173, "author": "Carl", "author_id": 38375, "author_profile": "https://Stackoverflow.com/users/38375", "pm_score": 2, "selected": false, "text": "[A-C][a-zA-Z0-9]{4}\n" }, { "answer_id": 334188, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "[ABC][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]\n" }, { "answer_id": 335127, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "/[ABC](?i:[a-z0-9]{4})/\n" }, { "answer_id": 1064623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "^[A-C]\\w{4}$\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/750/" ]
334,149
<p>What's the quickest/neatest way to calculate the next anniversary of someone's birthday.</p> <p>For example, if I knew a person was born on 31st January, 1990, and today is the 10th February 2000, their next anniversary will be 31st January, 2001.</p> <p>February 29th should roll onto March 1st (e.g. if they were born on February 29th 1990, their first birthday will be March 1st, 1991).</p> <p>EDIT : Wow - I thought this would be a lot more trivial. I really assumed there would be some library function I could use. Anyhoo, thanks to all of you, I've got what I <em>think</em> is a working solution, that deals with all the stupid Feb 29th issues. It's not very pretty though :-(</p> <pre><code>Function NextBirthDay2(ByVal dStartDate As Date, ByVal dNow As Date) As Date Dim oDate As Date Dim bFeb29thHack As Boolean = dStartDate.Month = 2 And dStartDate.Day = 29 If bFeb29thHack Then oDate = New Date(dNow.Year, 3, 1) Else oDate = New Date(dNow.Year, dStartDate.Month, dStartDate.Day) End If If (oDate &lt;= dNow) Then oDate = oDate.AddYears(1) End If If Date.IsLeapYear(oDate.Year) And bFeb29thHack Then oDate = oDate.AddDays(-1) End If Return oDate End Function </code></pre>
[ { "answer_id": 334168, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 3, "selected": true, "text": "private DateTime nextDate(DateTime currentDate, DateTime anniversaryDate)\n{\n DateTime nextDate;\n try{\n nextDate = new DateTime(currentDate.Year, anniversaryDate.Month, anniversaryDate.Day);\n } catch (ArgumentOutOfRangeException)\n {\n //for 29 Feb case.\n nextDate = new DateTime(currentDate.Year, anniversaryDate.Month, anniversaryDate.Day-1).AddDays(1);\n }\n\n if (nextDate <= currentDate)\n nextDate = nextDate.AddYears(1);\n return nextDate;\n}\n" }, { "answer_id": 334205, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": "int bMon = 3; // for March\nint bDayOfMon = 26 // for March 26th\n\nDateTime nextBirthDay = \n (new DateTime(DateTime.Today.Year, bMon, bDayOfMon - 1 ))\n .AddDays(1).AddYears((DateTime.Today.Month > bMon || \n (DateTime.Today.Month == bMon && \n DateTime.Today.Day > bDayOfMon ))? 1: 0);\n" }, { "answer_id": 334271, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 0, "selected": false, "text": "Function NextBirthDay(ByVal BirthDate As Date) As Date\n\n If Not Date.IsLeapYear(Now.Year) And BirthDate.Month = 2 And BirthDate.Day = 29 Then BirthDate.AddDays(1)\n\n Dim TestDate As Date = New Date(Now.Year, BirthDate.Month, BirthDate.Day)\n\n If DateDiff(DateInterval.Day, TestDate, Now) > 0 Then\n\n TestDate.AddYears(1)\n REM now check if NEXT year are leapyear, if so and birthday was a leapday, change back to leapday\n If Date.IsLeapYear(TestDate.Year) AndAlso BirthDate.Month = 2 AndAlso BirthDate.Day = 29 Then\n Return New Date(TestDate.Year, 2, 29)\n Else\n Return TestDate\n End If\n\n Else\n\n Return TestDate\n\n End If\n\nEnd Function\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15393/" ]
334,163
<p>I created a vbscript custom action which checks for some registry keys and alters them if neccessary. In case a key could not be written or something like that, the setup should be aborted.</p> <p>In order to achieve this, I set a property which I tried to use as a condition for the next step within the execute sequence but this does not work.</p> <p>I found out that this can not work since the custom action cannot write the property at the time it is executed. </p> <p>So the question is: How can I achieve an abort of installation depending on what my custom action says? Is there a method to pass an "abort installation request" to the Installer or something like that?</p>
[ { "answer_id": 334363, "author": "Ken", "author_id": 18836, "author_profile": "https://Stackoverflow.com/users/18836", "pm_score": 3, "selected": true, "text": "Function ExitSetupFromVBS( )\n\nConst IDABORT = 3\n\n ' ...do some work...\n\n ' abort the installation\n ExitSetupFromVBS = IDABORT\n\nEnd Function\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25428/" ]
334,183
<p>I am implementing a tagging system on my website similar to one stackoverflow uses, my question is - what is the most effective way to store tags so that they may be searched and filtered?</p> <p>My idea is this:</p> <pre><code>Table: Items Columns: Item_ID, Title, Content Table: Tags Columns: Title, Item_ID </code></pre> <p>Is this too slow? Is there a better way?</p>
[ { "answer_id": 32061474, "author": "Dmitry Shvedov", "author_id": 1434116, "author_profile": "https://Stackoverflow.com/users/1434116", "pm_score": 3, "selected": false, "text": "Table: Items\nColumns: Item_ID:int, Title:text, Content:text\n\nTable: Tags\nColumns: Item_ID:int, Tag_Title:text[]\n" }, { "answer_id": 67516434, "author": "Rafiq", "author_id": 12816049, "author_profile": "https://Stackoverflow.com/users/12816049", "pm_score": 0, "selected": false, "text": "tags (each row only keeps information about a particular tag)\ntaggings (each row keeps information about trigger and who will receive the trigger )\nproducts_tags (each row keeps information about tag with particular product)\ntag_status (each row keeps track of a tag status)\n id(PK)\nuserId(FK users)(not null)(A tag only belongs to one user, but a user can create multiple tags. So it is one to many relationships.)\ngenreId(FK products_geners)(not null)\nname (string) (not null)\ndescription (string)\nstatus (int) (0=inactive, 1=pending, 2=active, there could be more flag)\nrank(int) (rank is the popularity of a particular tag), this field can be use for sorting among similar tags.)\ntype (int) (0=type1, 1=type2, 2=type3)\nphoto(string)\nvisibility (int) (0=public, 2=protected, 3 = private)(private means the tag only visible to assigned users of a product, protected means a tag only visible to all friends and followers of the creator of the tag, public means search by public, such as all admin created tag)\ncreatedAt(timestamp for the tag was created at)\nupdatedAt (timestamp for the tag last time updated)\ndeletedAt (default value null) (timestamp when tag was deleted, we need this field because we will delete tag permanently from audit table). \n Id(PK)\ntagId(a tagging row only belongs to a tag, but a tag can have multiple row).\ntaggableId (id of a user who will receive notification)\ntaggableType(int) (0=notification, 1=feed message)\ntaggerId(the person who triggered the broadcast)\ntaggerType(ad, product, news)\ncreatedAt(timestamp for the tag was created at)\n Id (PK)\nproductId(FK)\ntagId(FK)\n id(PK)\nsenderId(Id of the user)\nreceiverId(Id of admin user)\ncreatedAt(timestamp of created at)\nupdatedAt(timestamp of updated at)\ndeletedAt(timestamp of deletedAt) default value null\nexpiredAt (if a tag never gets approved it will expire after a certain time for removing its information from the database. If a rejected tag gets updated by user then expiredAt will reset to new future time)\nstatus \nMessage (string varchar(256)) (message for user)\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29595/" ]
334,201
<p>At every company I have worked at, I have found that people are still writing their SQL queries in the ANSI-89 standard:</p> <pre><code>select a.id, b.id, b.address_1 from person a, address b where a.id = b.id </code></pre> <p>rather than the ANSI-92 standard:</p> <pre><code>select a.id, b.id, b.address_1 from person a inner join address b on a.id = b.id </code></pre> <p>For an extremely simple query like this, there's not a big difference in readability, but for large queries I find that having my join criteria grouped in with listing out the table makes it much easier to see where I might have issues in my join, and let's me keep all my filtering in my WHERE clause. Not to mention that I feel that outer joins are much intuitive than the (+) syntax in Oracle.</p> <p>As I try to evangelize ANSI-92 to people, are there any concrete performance benefits in using ANSI-92 over ANSI-89? I would try it on my own, but the Oracle setups we have here don't allow us to use EXPLAIN PLAN - wouldn't want people to try to optimize their code, would ya?</p>
[ { "answer_id": 334245, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 7, "selected": true, "text": "(+) *=" }, { "answer_id": 334469, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 0, "selected": false, "text": "ORA-01445: cannot select ROWID from a join view without a key-preserved table.\n" }, { "answer_id": 334701, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "SELECT c.* \nFROM companies AS c \nJOIN users AS u USING(companyid) \nJOIN jobs AS j USING(userid) \nJOIN useraccounts AS us USING(userid) \nWHERE j.jobid = 123\n" }, { "answer_id": 9738675, "author": "Dave", "author_id": 21294, "author_profile": "https://Stackoverflow.com/users/21294", "pm_score": 2, "selected": false, "text": "select foo.baz\nfrom foo\n left outer join bar\n on foo.a = bar.a\n select foo.baz\nfrom foo, bar\nwhere foo.a *= bar.a\n" }, { "answer_id": 21367005, "author": "magallanes", "author_id": 202705, "author_profile": "https://Stackoverflow.com/users/202705", "pm_score": 1, "selected": false, "text": "(1)select * from TABLE_OFFICES to,BIG_TABLE_USERS btu\nwhere to.iduser=tbu.iduser and to.idoffice=1\n (2)select * from TABLE_OFFICES to\ninner join BIG_TABLE_USERS btu on to.iduser=tbu.iduser\nwhere to.idoffice=1\n (3)select * from TABLE_OFFICES to\ninner join BIG_TABLE_USERS btu on to.iduser=tbu.iduser and to.idoffice=1\n" }, { "answer_id": 47720615, "author": "Evan Carroll", "author_id": 124486, "author_profile": "https://Stackoverflow.com/users/124486", "pm_score": 2, "selected": false, "text": "NATURAL JOINS USING id id id person_id id company_id USING CROSS JOIN CROSS JOIN FROM T1,T2 FROM T1 CROSS JOIN T2 WHERE , JOIN JOIN" }, { "answer_id": 47751743, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": -1, "selected": false, "text": "NATURAL JOIN inner join SELECT INNER NATURAL" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41165/" ]
334,204
<p>ASP.NET master pages - essential things.</p> <p>However, I have a lot of very similar UserControls in my projects - it might be a standard layout for an AJAX ModalPopup, or something more involved.</p> <p>I wish I could get rid of some of my duplicated code (both in ascx files and code-behind) with some Master UserControls.</p> <p>Does anyone have any suggestions of a way to achieve this?</p>
[ { "answer_id": 3883057, "author": "Mike", "author_id": 469251, "author_profile": "https://Stackoverflow.com/users/469251", "pm_score": 1, "selected": false, "text": "public class MasterLoader : UserControl\n{\n MasterUserControl _masterUserControl;\n\n protected override void CreateChildControls()\n {\n Controls.Clear();\n base.CreateChildControls();\n\n Controls.Add(MasterControl);\n }\n\n protected override void AddedControl(Control control, int index)\n {\n if (control is MasterUserControl)\n base.AddedControl(control, index);\n else\n MasterControl.ContentArea.Controls.Add(control);\n }\n\n private MasterUserControl MasterControl\n {\n get\n {\n if (_masterUserControl== null)\n _masterUserControl= (MasterUserControl)LoadControl(\"~/MasterUserControl.ascx\");\n\n return _masterUserControl;\n }\n }\n}\n public partial class MasterUserControl: UserControl\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n public PlaceHolder ContentArea \n {\n get\n {\n return phContent;\n }\n }\n}\n" }, { "answer_id": 7168155, "author": "Alexander Taylor", "author_id": 345648, "author_profile": "https://Stackoverflow.com/users/345648", "pm_score": 2, "selected": false, "text": "namespace MasterControls\n{\n // code written by alexander taylor on 2011-08-22. http://www.alexsapps.com\n\n public abstract class ChildUserControl : UserControl\n {\n Control master;\n\n public abstract string MasterControlVirtualPath { get; }\n\n protected override void OnInit(EventArgs e)\n {\n master = LoadControl(MasterControlVirtualPath);\n Controls.Add(master);\n\n base.OnInit(e);\n }\n\n protected override void Render(HtmlTextWriter writer)\n {\n master.RenderControl(writer);\n }\n }\n public class ControlContentPlaceHolder : Control\n {\n protected override void Render(HtmlTextWriter writer)\n {\n ControlContent found = null;\n\n foreach (Control c in NamingContainer.NamingContainer.Controls)\n {\n ControlContent search;\n search = c as ControlContent;\n if (search != null && search.ControlContentPlaceHolderID.Equals(ID))\n {\n found = search;\n break;\n }\n }\n\n if (found != null)\n { \n //write content of the ContentControl\n found.RenderControl(writer);\n }\n else\n {\n //use default content\n base.Render(writer);\n }\n }\n }\n public class ControlContent : Control\n {\n public string ControlContentPlaceHolderID { get; set; }\n }\n\n}\n <%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"MasterControl1.ascx.cs\" Inherits=\"MasterControl1\" %>\n<%@ Register Namespace=\"MasterControls\" TagPrefix=\"masterControls\" %>\n\n<p>content 1 below:<br />\n<masterControls:ControlContentPlaceHolder ID=\"myContent1\" runat=\"server\">\n default content 1 here!\n</masterControls:ControlContentPlaceHolder></p>\n\n<p>content 2 below:<br />\n<masterControls:ControlContentPlaceHolder ID=\"myContent2\" runat=\"server\">\n default content 2 here!\n</masterControls:ControlContentPlaceHolder></p>\n <%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"ChildControl1.ascx.cs\" Inherits=\"Control1\" %>\n<%@ Register Namespace=\"MasterControls\" TagPrefix=\"masterControls\" %>\n\n<masterControls:ControlContent ControlContentPlaceHolderID=\"myContent1\" runat=\"server\">\n custom content 1\n</masterControls:ControlContent>\n\n<masterControls:ControlContent ControlContentPlaceHolderID=\"myContent2\" runat=\"server\">\n custom content 2\n</masterControls:ControlContent>\n using MasterControls;\n\n//you must inherit the ChildUserControl class!\npublic partial class Control1 : ChildUserControl\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n public override string MasterControlVirtualPath\n {\n //below, type the location to the master control\n //you wish to apply to this control\n get { return \"~/MasterControl1.ascx\"; }\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39709/" ]
334,207
<p>I would like to document the file format of regedit utility, so data can be merged into the registry. </p> <p>From the command-line you can (silently) merge data from a batch file like this:</p> <pre><code>regedit /s file.reg </code></pre> <p>Exporting from a subkey goes like this:</p> <pre><code>regedit /e file.reg "HKEY_XX\key" </code></pre>
[ { "answer_id": 334208, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 6, "selected": true, "text": "REGEDIT4\n[-HKEY_CURRENT_USER\\RemoveThisTree]\n[HKEY_CURRENT_USER\\RemoveValue]\n\"valueName\"=-\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
334,214
<p>I have been asked to find training resources to bring engineers up to speed on VBA programming.</p> <p>The target trainee will have some systems engineering experience but little to no non-systems programming experience. </p> <p>I'm hoping for a computer-based training course or DVD that we can purchase and give to the engineers for a couple days to bring them up to speed with the basics.</p> <p>Unfortunately, my Google-fu is having a hard time cutting through the marketing sites to any obviously credible information. </p> <p>Any feedback on good (or bad) resources would be much appreciated.</p> <hr> <p><strong>Edit:</strong> the engineers will be applying their new VBA skills in non-Office products. </p> <p>While reference materials are useful, I really need something that guides them through the basics.</p>
[ { "answer_id": 334208, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 6, "selected": true, "text": "REGEDIT4\n[-HKEY_CURRENT_USER\\RemoveThisTree]\n[HKEY_CURRENT_USER\\RemoveValue]\n\"valueName\"=-\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29/" ]
334,256
<p>I would like to create a custom XmlDeclaration while using the XmlDocument/XmlDeclaration classes in c# .net 2 or 3. </p> <p>This is my desired output (it is an expected output by a 3rd party app):</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt; &lt;?MyCustomNameHere attribute1="val1" attribute2="val2" ?&gt; [ ...more xml... ] </code></pre> <p>Using the XmlDocument/XmlDeclaration classes, it appears I can only create a single XmlDeclaration with a defined set of parameters:</p> <pre><code>XmlDocument doc = new XmlDocument(); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null); doc.AppendChild(declaration); </code></pre> <p>Is there a class other than the XmlDocument/XmlDeclaration I should be looking at to create the custom XmlDeclaration? Or is there a way with the XmlDocument/XmlDeclaration classes itself?</p>
[ { "answer_id": 334291, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": true, "text": "XmlDocument doc = new XmlDocument();\nXmlDeclaration declaration = doc.CreateXmlDeclaration(\"1.0\", \"ISO-8859-1\", null);\ndoc.AppendChild(declaration);\nXmlProcessingInstruction pi = doc.CreateProcessingInstruction(\"MyCustomNameHere\", \"attribute1=\\\"val1\\\" attribute2=\\\"val2\\\"\");\ndoc.AppendChild(pi);\n" }, { "answer_id": 334306, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 3, "selected": false, "text": "XmlDocument document = new XmlDocument();\nXmlDeclaration declaration = document.CreateXmlDeclaration(\"1.0\", \"ISO-8859-1\", \"no\");\n\nstring data = String.Format(null, \"attribute1=\\\"{0}\\\" attribute2=\\\"{1}\\\"\", \"val1\", \"val2\");\nXmlProcessingInstruction pi = document.CreateProcessingInstruction(\"MyCustomNameHere\", data);\n\ndocument.AppendChild(declaration);\ndocument.AppendChild(pi);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9664/" ]
334,259
<p>I'm working on an useragent that logs into teamcity and I'm trying to move the password encryption from js to c#.</p> <p><a href="http://teamcity.jetbrains.com/res/-4045289697674020822.js" rel="nofollow noreferrer">this is the javascript</a> </p> <p>the section called rsa.js and encrypt.js are important. They make a function call with </p> <pre><code>rsa.setPublic(publicKey,"10001"); </code></pre> <p>The exponent looks like its a hex number x10001 which is 65537 base10 as far as I can tell</p> <p><a href="http://teamcity.jetbrains.com/login.html" rel="nofollow noreferrer">here is teamcity's demo site</a></p> <p><strong>Note the account below does not belong to teamcity's demo site</strong></p> <p>This test validates if the encrypted text is equal to the clear text being encrypted with the public key.</p> <pre><code>[Test] public void should_be_able_to_encode_a_string() { string public_key = "00b46e5cd2f8671ebf2705fd9553137da082b2dd3dbfa06f254cdfeb260fb21bc2c37a882de2924d7dd4c61eb81368216dfea7df718488b000afe7120f3bbbe5b276ac7f2dd52bd28445a9be065bd19dab1f177e0acc035be4c6ccd623c1de7724356f9d6e0b703d01583ebc4467d8454a97928b5c6d0ba3f09f2f8131cc7095d9"; string expected = "1ae1d5b745776f72172b5753665f5df65fc4baec5dd4ea17d43e11d07f10425b3e3164b0c2ba611c72559dc2b00149f4ff5a9649b1d050ca6a5e2ec5d96b787212874ab5790922528a9d7523ab4fe3a002e8f3b66cab6e935ad900805cf1a98dc6fcb5293c7f808917fd9015ba3fea1d59e533f2bdd10471732cccd87eda71b1"; string data = "scott.cowan"; string actual = new EncryptionHelper().Encrypt(public_key, data); Assert.AreEqual(expected,actual); } </code></pre> <p>so far the implementation looks like</p> <pre><code>public string Encrypt(string public_key, string data) { rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(String.Format("&lt;RSAKeyValue&gt;{0}&lt;/RSAKeyValue&gt;",public_key)); byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data); byte[] cipherbytes = rsa.Encrypt(plainbytes,false); return Convert.ToBase64String(cipherbytes); } </code></pre> <p>but this complains with</p> <pre><code>System.Security.Cryptography.CryptographicException Message: Input string does not contain a valid encoding of the 'RSA' 'Modulus' parameter. </code></pre> <p>Thank you any help will make this a very merry christmas</p> <p><strong>Edit: looks like my test is flawed since a different encryptedPassword is generated with each seeded time</strong></p> <p><strong>Answer: I turned on guest access, that bypasses this problem, but I'd still like to solve it</strong></p>
[ { "answer_id": 334291, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": true, "text": "XmlDocument doc = new XmlDocument();\nXmlDeclaration declaration = doc.CreateXmlDeclaration(\"1.0\", \"ISO-8859-1\", null);\ndoc.AppendChild(declaration);\nXmlProcessingInstruction pi = doc.CreateProcessingInstruction(\"MyCustomNameHere\", \"attribute1=\\\"val1\\\" attribute2=\\\"val2\\\"\");\ndoc.AppendChild(pi);\n" }, { "answer_id": 334306, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 3, "selected": false, "text": "XmlDocument document = new XmlDocument();\nXmlDeclaration declaration = document.CreateXmlDeclaration(\"1.0\", \"ISO-8859-1\", \"no\");\n\nstring data = String.Format(null, \"attribute1=\\\"{0}\\\" attribute2=\\\"{1}\\\"\", \"val1\", \"val2\");\nXmlProcessingInstruction pi = document.CreateProcessingInstruction(\"MyCustomNameHere\", data);\n\ndocument.AppendChild(declaration);\ndocument.AppendChild(pi);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253/" ]
334,277
<p>I'm building a c++ DLL in visual studio 2008.</p> <p>For some reason, even when I build in release mode, my dll still depends on msvcr90d.dll. I can see that using depends.exe</p> <p>Is there any way to figure out what is causing this dependency? My run-time library setting is /MD </p> <p>Thanks, Dan</p>
[ { "answer_id": 334470, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": true, "text": "\"Configuration Properties\"/Linker/General \"Show Progress\" \"Display All Progress Messages (/VERBOSE)\" msvcr90d.dll /VERBOSE" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4697/" ]
334,279
<p>Can anyone tell me how can I get the xpath of the name attribute from this file:</p> <pre><code>&lt;asmv1:assembly xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"&gt; &lt;assemblyIdentity name="MyName"/&gt; &lt;/asmv1:assembly&gt; </code></pre> <p>I'm trying to get it for nant xmlpoke task without success.</p> <p>Thanks.</p>
[ { "answer_id": 334310, "author": "joegtp", "author_id": 39431, "author_profile": "https://Stackoverflow.com/users/39431", "pm_score": 1, "selected": false, "text": "/*[local-name()='assembly']/assemblyIdentity/@name\n" }, { "answer_id": 334313, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": true, "text": "//asmv1:assembly/asmv1:assemblyIdentity/@name\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956/" ]
334,280
<p>Is there a way in MySQL 5 to show only the current user's processes(queries)?</p> <p>The user has the <code>PROCESS</code> privilege, therefore <code>SHOW PROCESSLIST</code> displays running processes of all users. According to the documentation, <code>SHOW PROCESSLIST</code> does not allow any kind of <code>WHERE</code> syntax, nor did I manage to make it into a subquery.</p> <p>Of course, I could simply send the query, e.g. in a PHP script, and go through the results in a loop, discarding everything that's not mine, but it seems rather inefficient. Changing the user privileges is not feasible.</p> <p>Are there any other ways? Thanks in advance.</p>
[ { "answer_id": 334315, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "SELECT WHERE" }, { "answer_id": 336325, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "PROCESS SHOW PROCESSLIST" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19746/" ]
334,292
<p>What is the preferred/easiest way to manipulate TDesC strings, for example to obtain a substring.</p> <p>I will give you an example of my scenario.</p> <pre><code>RBuf16 buf; ... CEikLabel label; ... label-&gt;SetTextL(buf); // (SetTextL takes a const TDesC&amp;) </code></pre> <p>I want to get a substring from buf. So do I want to manipulate the RBuf16 directly and if so what is the best way?</p> <p>Is there a way to convert to const char* so I can just use standard C string manipulation.</p> <p>Thanks in advance</p>
[ { "answer_id": 334384, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 2, "selected": false, "text": "TDes::LeftTPtr()\nTDes::MidTPtr()\nTDes::RightTPtr()\n TDesC::Left()\nTDesC::Mid()\nTDesC::Right()\n" }, { "answer_id": 334385, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 1, "selected": false, "text": "TDes16::MidTPtr TPtr8 narrowBuf;\n\n// Create a buffer with enough space to store every character, plus one for \n// a null terminator\nnarrowBuf.AllocL( buf.Length() + 1);\n\n// TPtr8::Copy accepts a TDesC16 \nnarrowBuf.Copy( buf );\n\n// Append a null terminator and return a pointer to the resultant data\nconst char* ptr = (const char*)narrowBuf.PtrZ();\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33604/" ]
334,305
<p>I have a custom renderer in a <code>JTable</code> to display <code>JCheckbox</code>es for <code>boolean</code>s. However, this causes a slight issue because when the user clicks in the table cell, but not in the checkbox, the checkbox is still checked.</p> <p>Is there a way I can return the bounds of the actual <code>JCheckbox</code> that is rendered by the <code>JTable</code> at a particular point so I can determine if the click is within the bounds of the <code>JCheckbox</code>?</p> <p>Thank you very much.</p>
[ { "answer_id": 334324, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 1, "selected": false, "text": "DefaultCellEditor Boolean.class TableModel" }, { "answer_id": 334353, "author": "Dan", "author_id": 9774, "author_profile": "https://Stackoverflow.com/users/9774", "pm_score": 0, "selected": false, "text": "JTree public void mouseClicked(MouseEvent e) {\n\nint x = e.getX();\nint y = e.getY();\nint row = getRowForLocation(x, y);\n\nRectangle rect = getRowBounds(row);\nRectangle rect2 = new Rectangle(rect.x, rect.y, rect.height + 2, rect.height);\nif (rect2.contains(x, y)) .... // The click is on the checkbox\n" }, { "answer_id": 335082, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "JCheckBox TableCellEditor JPanel LayoutManager" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
334,317
<p>I'm working on an ASP.NET page, using VB.NET and I have this hierarchy:</p> <p>Page A <br /> &nbsp;&nbsp;- Web User Control 1 <br /> &nbsp;&nbsp;&nbsp;&nbsp;- Web User Control A <br /> &nbsp;&nbsp;&nbsp;&nbsp;- Web User Control B <br /> &nbsp;&nbsp;&nbsp;&nbsp;- Web User Control C <br /></p> <p>I need to raise an event from Web User Control B that Page A will receive (the event flow will be Web User Control B -> Web User Control 1 -> Page A).</p> <p>My only approach so far has been this: 1) Add a custom event declaration to both Web User Control B and Web User Control 1 and simply RaiseEvent twice until it gets to Page A (this seems ugly and I don't particularly like it).</p> <p>My other idea was to create a custom Event class that inhertis from some magical base Event class and create an instance of it in both Web User Control B and Web User Control 1, but that is proving fruitless because I can't find any event base classes (maybe b/c they're aren't any, since it appears to be a keyword, not a class name).</p> <p>Any help would be appreciated! Thanks and happy coding!</p>
[ { "answer_id": 334454, "author": "Yona", "author_id": 40007, "author_profile": "https://Stackoverflow.com/users/40007", "pm_score": 0, "selected": false, "text": "Page A Web User Control B Public Partial Class TestPage\n Inherits Page\n\n Public Sub PerformAction()\n 'Whatever needs to be done on Page A\n End Sub\nEnd Class\n Public Partial Class TestControl\n Inherits UserControl\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n 'This will call the Page, obviously this will only\n 'work when the control is on TestPage\n CType(Page, TestPage).PerformAction()\n End Sub\nEnd Class\n" }, { "answer_id": 334793, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "Class UserControl1 ' Parent\n Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean\n Dim c as CommandEventArgs = TryCast(e, CommandEventArgs)\n If c IsNot Nothing Then\n RaiseEvent ItemEvent(sender, c)\n Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy\n End If\n Return False ' Couldn't handle, so let it bubble\n End Function\n\n Public Event ItemEvent as EventHandler(Of CommandEventArgs)\nEnd Class\n\nClass UserControlB ' Child\n Protected Sub OnClicked(e as EventArgs)\n ' Raise a direct event for any handlers attached directly\n RaiseEvent Clicked(Me, e)\n ' And raise a bubble event for parent control\n RaiseBubbleEvent(Me, New CommandEventArgs(\"Clicked\", Nothing))\n End Sub\n\n Protected Sub OnMoved(e as EventArgs)\n ' Raise a direct event for any handlers attached directly\n RaiseEvent Moved(Me, e)\n ' And raise a bubble event for parent control\n RaiseBubbleEvent(Me, New CommandEventArgs(\"Moved\", Nothing))\n End Sub\nEnd Class\n\nClass PageA\n Sub UserControl1_ItemEvent(sender as Object, e as CommandEventArgs) Handles UserControl1.ItemEvent\n Response.Write(sender.GetType().Name & \" was \" & e.CommandName)\n End Sub\nEnd Class\n Class PageA\n Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean\n If sender Is UserControlB Then\n Dim c as CommandEventArgs = TryCast(e, CommandEventArgs)\n If c IsNot Nothing Then\n Response.Write(sender.GetType().Name & \" was \" & c.CommandName)\n Else\n Response.Write(sender.GetType().Name & \" raised an event, with \" & e.GetType().Name & \" args)\n End If\n Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy\n End If\n Return False ' Not handled\n End Function\nEnd Class\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1530166/" ]
334,319
<p>I have been programming for the last 3 years. When I program, I use to handle all known exceptions and alert the user gracefully. I have seen some code recently which has almost all methods wrapped inside try/catch blocks. The author says it is part of defensive programming. I wonder, is this really defensive programming? Do you recommend putting all your code in try blocks?</p>
[ { "answer_id": 334329, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 6, "selected": false, "text": "catch {}" }, { "answer_id": 334358, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 4, "selected": false, "text": "private String name;\n\npublic void setName(String name) {\n}\n public boolean isXXX (String s) {\n}\n public String getName() {\n}\n" }, { "answer_id": 334412, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "(void)" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
334,326
<p>I am using a specific command in in my C# code, which works well. However, it is said to misbehave in "unmanaged" code.</p> <p>What is managed or unmanaged code?</p>
[ { "answer_id": 17837415, "author": "Ashok Narwal", "author_id": 2615126, "author_profile": "https://Stackoverflow.com/users/2615126", "pm_score": 1, "selected": false, "text": "CLR .net CLR CLR" }, { "answer_id": 32175443, "author": "Amnesh Goel", "author_id": 1882208, "author_profile": "https://Stackoverflow.com/users/1882208", "pm_score": 0, "selected": false, "text": ".NET framework Microsoft MFC (Visual C++), VB, FoxPro CLR memory mangement, garbage collection Managed code unmanaged code Garbage collection, Performance improvements, cross-language integration, memory management" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
334,334
<p>I have a need to allow for a user to download an event that has multiple meeting dates. To do this I have created a memorystream to be downloaded which produces a .ics file. For example:</p> <pre> BEGIN:VCALENDAR PRODID:-//Company//Product//EN VERSION:2.0 METHOD:PUBLISH BEGIN:VEVENT SUMMARY:Subject of Event LOCATION:Location of Event UID:1227559810-8527e2c-20847@domain.com DESCRIPTION:Some description DTEND:20081101T200000Z DTSTART:20081101T200000Z PRIORITY:3 END:VEVENT BEGIN:VEVENT ... END:VEVENT END:VCALENDAR </pre> <p>If I only include one VEVENT in this file it will save it to my existing Outlook calendar. However, when I have multiple VEVENTs it wants to open it as a new calendar and files it under "Other Calendars".</p> <p>Is there a way (without using File - Import from within Outlook) to specify that the calendar should be imported automatically into the existing calendar when opened?</p> <p>UPDATE: To clarify, each VEVENT is related to a single "Appointment". However there may or may not be a recurring pattern.</p> <p>-Mike</p>
[ { "answer_id": 538017, "author": "Michael DeLorenzo", "author_id": 1383003, "author_profile": "https://Stackoverflow.com/users/1383003", "pm_score": 2, "selected": false, "text": "BEGIN:VCALENDAR \nPRODID:-//XYZ Corp//My Product//EN \nVERSION:2.0 \nCALSCALE:GREGORIAN \nMETHOD:PUBLISH \nX-WR-CALNAME:My Calendar \nX-WR-TIMEZONE:(GMT-05:00) Eastern Time (US & Canada) \nBEGIN:VEVENT \nDTSTART:20061021T100000Z \nDTEND:20061021T130000Z \nDTSTAMP:20090211T175526Z \nUID:5f98dfd5-ac72-4ae1-b3c2-799a4e7c91f9 \nCLASS:PUBLIC \nCREATED:20071104T183833Z \nDESCRIPTION: My description text. \nLAST-MODIFIED:20071104T183833Z \nLOCATION: 123 Anywhere Street\\; Anyplace, NJ 12345\\; US \nSEQUENCE:0 \nSTATUS:CONFIRMED \nSUMMARY: My summary text. \nTRANSP:OPAQUE \nEND:VEVENT \nBEGIN:VEVENT \nDTSTART:20061101T170000Z \nDTEND:20061101T180000Z \nDTSTAMP:20090211T175526Z \nUID:6eaef015-eb90-4e94-8e6c-0003b928969a \nCLASS:PUBLIC \nCREATED:20071104T183833Z \nDESCRIPTION: My description for number 2. \nLAST-MODIFIED:20071104T183833Z \nLOCATION: 123 Anywhere Street\\; Anyplace, NJ 12345\\; US \nSEQUENCE:0 \nSTATUS:CONFIRMED \nSUMMARY: My summary for #2. \nTRANSP:OPAQUE \nEND:VEVENT \nEND:VCALENDAR\n" }, { "answer_id": 3006751, "author": "Angel Alzamora", "author_id": 362540, "author_profile": "https://Stackoverflow.com/users/362540", "pm_score": 1, "selected": false, "text": "BEGIN:VCALENDAR\n\nPRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN\n\nVERSION:2.0\n\nMETHOD:PUBLISH\n\nX-CALSTART:20100611T140000Z\n\nX-CALEND:20100711T201500Z\n\nX-WR-RELCALID:{0000002E-5A22-AA75-713B-5C3715764495}\n\nX-WR-CALNAME: World Cup Football Complete Match Schedule 2010 South Africa\n\nBEGIN:VEVENT\n\nCATEGORIES:World Cup Football Complete Match Schedule 2010 South Africa\n\nCLASS:PUBLIC\n\nCREATED:20100608T231102Z\n\nDESCRIPTION:Group A\\nFollow MarkThisDate on Twitter\n\n markthisdate \n\nDTEND:20100611T154500Z\n\nDTSTAMP:20100513T100200Z\n\nDTSTART:20100611T140000Z\n\nLAST-MODIFIED:20100608T231102Z\n\nLOCATION:Johannesburg \n\nPRIORITY:5\n\nSEQUENCE:0\n\nSUMMARY:South Africa - Mexico\n\nTRANSP:TRANSPARENT\n\nUID:005ef5a170ab453276aad021756e5fde@markthisdate.com\n\nX-MICROSOFT-CDO-BUSYSTATUS:FREE\n\nX-MICROSOFT-CDO-IMPORTANCE:1\n\nEND:VEVENT\n\nBEGIN:VEVENT\n\nCATEGORIES:World Cup Football Complete Match Schedule 2010 South Africa\n\nCLASS:PUBLIC\n\nCREATED:20100608T231102Z\n\nDESCRIPTION:Group A\\nFollow MarkThisDate on Twitter\n\n markthisdate \n\nDTEND:20100611T201500Z\n\nDTSTAMP:20100513T100200Z\n\nDTSTART:20100611T183000Z\n\nLAST-MODIFIED:20100608T231102Z\n\nLOCATION:Cape Town \n\nPRIORITY:5\n\nSEQUENCE:0\n\nSUMMARY:Uruguay - France\n\nTRANSP:TRANSPARENT\n\nUID:9660590c514358c5bceed9e75bed0222@markthisdate.com\n\nX-MICROSOFT-CDO-BUSYSTATUS:FREE\n\nX-MICROSOFT-CDO-IMPORTANCE:1\n\nEND:VEVENT\n\nBEGIN:VEVENT\n\nCATEGORIES:World Cup Football Complete Match Schedule 2010 South Africa\n\nCLASS:PUBLIC\n\nCREATED:20100608T231102Z\n\nDESCRIPTION:Group B\\nFollow MarkThisDate on Twitter\n\n markthisdate \n\nDTEND:20100612T131500Z\n\nDTSTAMP:20100513T100200Z\n\nDTSTART:20100612T113000Z\n\nLAST-MODIFIED:20100608T231102Z\n\nLOCATION:Nelson Mandela Bay/Port Elizabeth \n\nPRIORITY:5\n\nSEQUENCE:0\n\nSUMMARY:Korea Republic - Greece\n\nTRANSP:TRANSPARENT\n\nUID:5a9eaca2435fb52e1c95ddb786f82efa@markthisdate.com\n\nX-MICROSOFT-CDO-BUSYSTATUS:FREE\n\nX-MICROSOFT-CDO-IMPORTANCE:1\n\nEND:VEVENT\n\nEND:VCALENDAR\n" }, { "answer_id": 6784540, "author": "nzcoops", "author_id": 597925, "author_profile": "https://Stackoverflow.com/users/597925", "pm_score": 1, "selected": false, "text": "BEGIN:VCALENDAR\nPRODID:-//Google Inc//Google Calendar 70.9054//EN\nVERSION:2.0\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\nX-WR-CALNAME:Insert something\nX-WR-TIMEZONE:Insert something\nX-WR-CALDESC:\n\nBEGIN:VEVENT\nDTSTART:20110909T180000Z\nDTEND:20110909T200000Z\nDTSTAMP:20110722T004312Z\nUID:et53m4on1ii70en7uuv1thjr58@google.com\nCREATED:20110721T105553Z\nDESCRIPTION:\nLAST-MODIFIED:20110721T105554Z\nLOCATION:Insert something\nSEQUENCE:0\nSTATUS:CONFIRMED\nSUMMARY:Insert something\nTRANSP:OPAQUE\nBEGIN:VALARM\nACTION:DISPLAY\nDESCRIPTION:This is an event reminder\nTRIGGER:-P0DT0H10M0S\nEND:VALARM\nEND:VEVENT\n\nBEGIN:VEVENT\nDTSTART:20110909T083000Z\nDTEND:20110909T103000Z\nDTSTAMP:20110722T004312Z\nUID:e5fhdjff6vakjftnl3l9vjs64k@google.com\nCREATED:20110721T105410Z\nDESCRIPTION:\nLAST-MODIFIED:20110721T111008Z\nLOCATION:Auckland\nSEQUENCE:1\nSTATUS:CONFIRMED\nSUMMARY:Insert something\nTRANSP:OPAQUE\nBEGIN:VALARM\nACTION:DISPLAY\nDESCRIPTION:Insert something\nTRIGGER:-P0DT0H10M0S\nEND:VALARM\nEND:VEVENT\n\nEND:VCALENDAR\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19251/" ]
334,341
<p>Component Services -> Computers -> My Computer -> COM+ Applications</p> <p>Open a COM+ Application object.</p> <p>Open Components.</p> <p>Right-click on a class and select Properties.</p> <p>Under "Advanced" there is a check box for "Allow IIS intrinsic properties".</p> <p>How do I check this check box programmatically?</p> <p>I can create and delete COM+ Applications programmatically, but the ComApplication class doesn't seem to have ways to change settings in the created application.</p>
[ { "answer_id": 334726, "author": "Andrew J. Brehm", "author_id": 4886, "author_profile": "https://Stackoverflow.com/users/4886", "pm_score": 3, "selected": true, "text": " //get collection of applications\n COMAdminCatalog catalog = new COMAdminCatalog();\n\n catalog.Connect(\"127.0.0.1\");\n\n COMAdminCatalogCollection applications = (COMAdminCatalogCollection)catalog.GetCollection(\"Applications\");\n\n applications.Populate(); //no idea why that is necessary, seems to be\n\n // appId for the application we are looking for\n object appId = new object();\n\n int count = applications.Count;\n ICatalogObject item;\n\n if (count == 0) return;\n\n //search collection for item with name we are looking for\n for (int i = 0; i < count; i++)\n {\n\n item = (ICatalogObject)applications.get_Item(i);\n\n if (applicationName == (string)item.get_Value(\"Name\"))\n {\n\n appId = item.Key;\n\n Console.WriteLine(\"appId found for \" + applicationName + \": \" + appId.ToString());\n\n }\n\n }\n\n // get all components for the application\n COMAdminCatalogCollection components;\n\n components = (COMAdminCatalogCollection)applications.GetCollection(\"Components\", appId);\n components.Populate(); // again, no idea why this is necessary\n\n // set the attribute in all components\n\n foreach (COMAdminCatalogObject component in components)\n {\n\n Console.WriteLine(\"Setting IISIntrinsics attribute in \" + component.Name + \".\");\n component.set_Value(\"IISIntrinsics\", true);\n components.SaveChanges();\n\n }\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4886/" ]
334,342
<p>I'm looking for a good ssh console plugin for Eclipse, and can't find much at all. Would anyone have some good leads on one?</p>
[ { "answer_id": 5735278, "author": "TrinitronX", "author_id": 645491, "author_profile": "https://Stackoverflow.com/users/645491", "pm_score": 4, "selected": false, "text": "Shift+Alt+Q Q Terminal Terminal Terminal top Scroll Lock New Terminal Connection Settings Terminal Terminal Invert terminal colors Apply localhost" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812/" ]
334,345
<p>I have a table with a view_name field (varchar(256)) and I would like to use that field in an sql query.</p> <p>Example :</p> <p>TABLE university_members</p> <p><strong>id | type | view_name | count</strong></p> <p>1 | professors | view_professors | 0</p> <p>2 | students | view_students2 | 0</p> <p>3 | staff | view_staff4 | 0</p> <p>And I would like to update all rows with some aggregate calculated on the corresponding view (for instance <code>..SET count = SELECT count(*) FROM view_professors</code>).</p> <p>This is probably a newbie question, I'm guessing it's either obviously impossible or trivial. Comments on the design, i.e. the way one handle meta-data here (explicity storing DB object names as strings) would be appreciated. Although I have no control over that design (so I'll have to find out the answer anyway), I'm guessing it's not so clean although some external constraints dictated it so I would really appreciate the community's view on this for my personal benefit.</p> <p>I use SQL Server 2005 but cross-platform answers are welcome.</p>
[ { "answer_id": 334364, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "DECLARE @ViewName VARCHAR(500)\n\nSELECT @ViewName = view_name\nFROM University_Members\nWHERE Id = 1\n\nDECLARE @SQL VARCHAR(MAX)\n\nSET @SQL = '\nUPDATE YOURTABLE\nSET YOURVALUE = SELECT COUNT(*) FROM ' + @ViewName + '\nWHERE yourCriteria = YourValue'\n\nEXEC(@SQL)\n" }, { "answer_id": 334379, "author": "Sergiu Damian", "author_id": 41345, "author_profile": "https://Stackoverflow.com/users/41345", "pm_score": 0, "selected": false, "text": "DECLARE @SQL VARCHAR(MAX)\nSET @SQL = ''\nSELECT @SQL = @SQL + 'UPDATE university_members SET count = (SELECT COUNT(*) FROM ' + view_name + ') WHERE id = ' + id + CHAR(10) + CHAR(13) FROM university_members\n\nEXEC @SQL\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5788/" ]
334,354
<p>With the XML below, I would like to know how to get the value of text in the case_id node as an attribute for the hidden input tag in the xsl sheet below. Is this possible?</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;?xml-stylesheet type="text/xsl" href="data.xsl"?&gt; &lt;NewDataSet&gt; &lt;Cases&gt; &lt;Case&gt; &lt;case_id&gt;30&lt;/case_id&gt; ... ... &lt;/Case&gt; &lt;/Cases&gt; &lt;/NewDataset&gt; &lt;?xml version="1.0" encoding="iso-8859-1"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:template match="/"&gt; &lt;input type="hidden" name="case_num" value="?"/&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
[ { "answer_id": 334395, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "input case_id Case case_id Case <xsl:template match=\"/\">\n <xsl:apply-templates />\n </xsl:template>\n\n <xsl:template match=\"Case\">\n <xsl:element name=\"input\">\n <xsl:attribute name=\"type\">\n <xsl:text>hidden</xsl:text>\n </xsl:attribute>\n <xsl:attribute name=\"name\">\n <xsl:text>case_num</xsl:text>\n </xsl:attribute>\n <xsl:attribute name=\"value\">\n <xsl:value-of select=\"case_id\"/>\n </xsl:attribute>\n </xsl:element>\n </xsl:template>\n" }, { "answer_id": 334396, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": true, "text": "<input type=\"hidden\" name=\"case-num\">\n <xsl:attribute name=\"value\">\n <xsl:value-of select=\"/NewDataSet/Cases/Case/case_id\" />\n </xsl:attribute>\n</input>\n" }, { "answer_id": 334398, "author": "joegtp", "author_id": 39431, "author_profile": "https://Stackoverflow.com/users/39431", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"/\">\n <input type=\"hidden\" name=\"case_num\">\n <xsl:attribute name=\"value\">\n <xsl:value-of select=\"/NewDataSet/Cases/Case/case_id/text()\"/>\n </xsl:attribute>\n </input>\n </xsl:template>\n</xsl:stylesheet>\n <?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"/\">\n <input type=\"hidden\" name=\"case_num\" value=\"{/NewDataSet/Cases/Case/case_id/text()}\"/>\n </xsl:template>\n" }, { "answer_id": 334750, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<input type=\"hidden\" name=\"case-num\">\n <xsl:attribute name=\"value\">\n <xsl:value-of select=\"case_id\" />\n </xsl:attribute>\n</input>\n" }, { "answer_id": 335569, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 2, "selected": false, "text": "<input type=\"hidden\" name=\"case_num\" value=\"{*/*/*/case_id}\"/>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
334,360
<p>Whilst debugging my program in VS 2008 I have come across the following error:</p> <p>The CLR has been unable to transition from COM context 0x34fc1a0 to COM context 0x34fc258 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this </p> <p>It appears to be deadlocking even though the code only contains a simple C# timer: See Snippet Below:</p> <pre><code> private void RequestWork() { // The timer will be re-intialised if there are still no wating jobs in the database StopTimer(); // assign all the threads some work InitialiseTimer(); } /// &lt;summary&gt; /// Initialise a timer with a timer interval configured from app.config. Enable the timer and /// register an appropriate event handler /// &lt;/summary&gt; private void InitialiseTimer() { if (m_Timer == null) { // look up the default backoff time from the config string backOffInt = ConfigurationSettings.AppSettings["BackOffInterval"]; int backoffInterval = 1000; m_Timer = new System.Timers.Timer(); // set the timer interval to 5 seconds m_Timer.Interval = backoffInterval; m_Timer.Elapsed += new ElapsedEventHandler(m_Timer_Elapsed); } m_Timer.Enabled = true; } private void StopTimer() { if (m_Timer != null) { m_Timer.Enabled = false; } } void m_Timer_Elapsed(object p_Sender, ElapsedEventArgs p_E) { RequestWork(); } </code></pre> <p>As far as I know the timer should run, elapse and then initialise again, I can see no local reason for a deadlock.</p> <p>I am aware of how to turn this error msg off but feel that this is not a solution, instead it is masking the problem.</p>
[ { "answer_id": 489795, "author": "Craigger", "author_id": 18924, "author_profile": "https://Stackoverflow.com/users/18924", "pm_score": 0, "selected": false, "text": "RequestWork() RequestWork()" }, { "answer_id": 2227217, "author": "Thiruvarul", "author_id": 269269, "author_profile": "https://Stackoverflow.com/users/269269", "pm_score": 1, "selected": false, "text": "System.Windows.Forms.Application.DoEvents();\n DoEvents()\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
334,367
<p>Playing with log4net, I have seen the possibility to use a per-thread stack of context labels called the NDC. </p> <p>The labels pushed on this stack are displayed in a PatternLayout by specifying the <code>%x</code> or the <code>%ndc</code> format parameter.</p> <p>The usage is something like: </p> <pre><code>ILog log = log4net.LogManager.GetLogger(...) ; //pattern layout format: "[%ndc] - %message%newline" log.Info("message 1"); using(log4net.NDC.Push("context") { using(log4net.NDC.Push("inner_context") { log.Info("message 2"); } log.Info("message 3"); } log.Info("message 4"); </code></pre> <p>The output is something like:</p> <pre><code>null - message 1 context inner_context - message 2 context - message 3 null - message 4 </code></pre> <p>In your programming experience with log4net, when did you find this feature to be useful?</p>
[ { "answer_id": 17344012, "author": "Donal Lafferty", "author_id": 939250, "author_profile": "https://Stackoverflow.com/users/939250", "pm_score": 6, "selected": false, "text": "// GET api/HypervResource\npublic string Get()\n{\n logger.Debug(\"Start of service test\");\n System.Threading.Thread.Sleep(5000); // simulate work\n logger.Debug(\"End of service test\");\n return \"HypervResource controller running, use POST to send JSON encoded RPCs\";\n}\n 2013-06-27 13:28:11,967 [10] DEBUG HypervResource.WmiCalls [(null)] - Start of service test\n2013-06-27 13:28:12,976 [12] DEBUG HypervResource.WmiCalls [(null)] - Start of service test\n2013-06-27 13:28:14,116 [13] DEBUG HypervResource.WmiCalls [(null)] - Start of service test\n2013-06-27 13:28:16,971 [10] DEBUG HypervResource.WmiCalls [(null)] - End of service test\n2013-06-27 13:28:17,979 [12] DEBUG HypervResource.WmiCalls [(null)] - End of service test\n2013-06-27 13:28:19,119 [13] DEBUG HypervResource.WmiCalls [(null)] - End of service test\n // GET api/HypervResource\npublic string Get()\n{\n using(log4net.NDC.Push(Guid.NewGuid().ToString()))\n {\n logger.Debug(\"Start of service test\");\n System.Threading.Thread.Sleep(5000); // simulate work\n logger.Debug(\"End of service test\");\n return \"HypervResource controller running, use POST to send JSON encoded RPCs\";\n }\n}\n 2013-06-27 14:04:31,431 [11] DEBUG HypervResource.WmiCalls [525943cb-226a-43c2-8bd5-03c258d58a79] - Start of service test\n2013-06-27 14:04:32,322 [12] DEBUG HypervResource.WmiCalls [5a8941ee-6e26-4c1d-a1dc-b4d9b776630d] - Start of service test\n2013-06-27 14:04:34,450 [13] DEBUG HypervResource.WmiCalls [ff2246f1-04bc-4451-9e40-6aa1efb94073] - Start of service test\n2013-06-27 14:04:36,434 [11] DEBUG HypervResource.WmiCalls [525943cb-226a-43c2-8bd5-03c258d58a79] - End of service test\n2013-06-27 14:04:37,325 [12] DEBUG HypervResource.WmiCalls [5a8941ee-6e26-4c1d-a1dc-b4d9b776630d] - End of service test\n2013-06-27 14:04:39,453 [13] DEBUG HypervResource.WmiCalls [ff2246f1-04bc-4451-9e40-6aa1efb94073] - End of service test\n" }, { "answer_id": 48203102, "author": "Daniel Lidström", "author_id": 286406, "author_profile": "https://Stackoverflow.com/users/286406", "pm_score": 3, "selected": false, "text": "NDC.Push ThreadContext.Stacks[\"NDC\"] var disposable = ThreadContext.Stacks[\"NDC\"].Push(\"context\");\ntry\n{\n Log.Info(\"begin\"); // optional, but nice\n ...\n}\nfinally\n{\n Log.Info(\"end\"); // optional, but nice\n disposable.Dispose();\n}\n %property{NDC} <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern\n value=\"%date [%2thread] %-5level [%property{NDC}] - %.10240message%newline\" />\n</layout>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
334,370
<p>I've seen (and used) code to have a link spawn a javascript action many times in my life, but I've never come to a firm conclusion on if the href attribute should be blank or #. Do you have any preference one way or the other, and if so, why?</p> <pre><code>&lt;a href="" onclick="javascript: DoSomething();"&gt;linky&lt;/a&gt; </code></pre> <p>or</p> <pre><code>&lt;a href="#" onclick="javascript: DoSomething();"&gt;linky&lt;/a&gt; </code></pre>
[ { "answer_id": 334394, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "href" }, { "answer_id": 334413, "author": "adam", "author_id": 33604, "author_profile": "https://Stackoverflow.com/users/33604", "pm_score": 1, "selected": false, "text": "$(\".link\").click(function(e) {\n e.preventDefault();\n DoSomething();\n});\n" }, { "answer_id": 334437, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "href onclick onmouseover on... javascript: <a href=\"#\" onclick=\"DoSomething(); return false\">linky</a>\n" }, { "answer_id": 334822, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<a href=\"javascript:// open xxx widget\" onclick=\"DoSomething();\">linky</a>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
334,371
<p>What would the purpose of this construct in a c file be?: </p> <pre><code>#define _TIMERC #include "timer.h" #undef _TIMERC </code></pre> <p>I am aware of the guard for preventing multiple inclusion of a header file. This doesn't appear to be whats happening though.</p> <p>thanks!</p>
[ { "answer_id": 334495, "author": "JeffV", "author_id": 445087, "author_profile": "https://Stackoverflow.com/users/445087", "pm_score": 3, "selected": false, "text": "#define _TIMERA \n#include \"timer.h\" \n#undef _TIMERA \n #define _TIMERC \n#include \"timer.h\" \n#undef _TIMERC \n" }, { "answer_id": 334751, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "#ifndef header_name_h\n#define header_name_h\n #endif\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
334,373
<p>When debugging I need to start an external program from the target directory of a build and am wondering if it can be accomplished using relative paths.</p> <p>As a post-build event I have the following:</p> <pre> IF NOT "$(ConfigurationName)"=="Debug" GOTO End :CopyExecutable copy "$(SolutionDir)\Source\Lib\MyExecutable.exe" "$(TargetDir)" :End </pre> <p>I need to run MyExecutable.exe when I am debugging so in the debug tab for the project properties I set "Start external program" to MyExecutable.exe but get a failure when running the debug. It seems I need to put the full path for this to work. </p> <p>Is there a way to do this using relative paths?</p>
[ { "answer_id": 1141459, "author": "David Martin", "author_id": 34879, "author_profile": "https://Stackoverflow.com/users/34879", "pm_score": 3, "selected": false, "text": "Source\\Lib\\MyExecutable.exe\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32313/" ]
334,382
<p>I asked <a href="https://stackoverflow.com/questions/288409/how-do-i-get-the-html-output-of-a-usercontrol-in-net-c">how to render a UserControl's HTML</a> and got the code working for a dynamically generated UserControl.</p> <p>Now I'm trying to use LoadControl to load a previously generated Control and spit out its HTML, but it's giving me this:</p> <p><em>Control of type 'TextBox' must be placed inside a form tag with runat=server.</em></p> <p>I'm not actually adding the control to the page, I'm simply trying to grab its HTML. Any ideas?</p> <p>Here's some code I'm playing with:</p> <pre><code>TextWriter myTextWriter = new StringWriter(); HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter); UserControl myControl = (UserControl)LoadControl("newUserControl.ascx"); myControl.RenderControl(myWriter); return myTextWriter.ToString(); </code></pre>
[ { "answer_id": 334405, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 0, "selected": false, "text": " <input type=\"text\" />\n public static string RenderView<D>(string path, D dataToBind)\n {\n Page pageHolder = new Page();\n UserControl viewControl = (UserControl) pageHolder.LoadControl(path);\n if(viewControl is IRenderable<D>)\n {\n if (dataToBind != null)\n {\n ((IRenderable<D>) viewControl).PopulateData(dataToBind);\n }\n }\n pageHolder.Controls.Add(viewControl);\n StringWriter output = new StringWriter();\n HttpContext.Current.Server.Execute(pageHolder, output, false);\n\n return output.ToString();\n }\n" }, { "answer_id": 334442, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "Page tmpPage = new TempPage(); // temporary page\nControl tmpCtl = tmpPage.LoadControl( \"~/UDynamicLogin.ascx\" );\n//the Form is null that's throws an exception\ntmpPage.Form.Controls.Add( tmpCtl );\n\nStringBuilder html = new StringBuilder();\nusing ( System.IO.StringWriter swr = new System.IO.StringWriter( html ) ) {\n using ( HtmlTextWriter writer = new HtmlTextWriter( swr ) ) {\n tmpPage.RenderControl( writer );\n }\n}\n" }, { "answer_id": 337224, "author": "Jon Smock", "author_id": 25538, "author_profile": "https://Stackoverflow.com/users/25538", "pm_score": 1, "selected": false, "text": "TextWriter myTextWriter = new StringWriter();\nHtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);\n\nUserControl myDuplicate = new UserControl();\nTextBox blankTextBox;\n\nforeach (Control tmpControl in this.Controls)\n{\n switch (tmpControl.GetType().ToString())\n {\n case \"System.Web.UI.LiteralControl\":\n blankLiteral = new LiteralControl();\n blankLiteral.Text = ((LiteralControl)tmpControl).Text;\n myDuplicate.Controls.Add(blankLiteral);\n break;\n case \"System.Web.UI.WebControls.TextBox\":\n blankTextBox = new TextBox();\n blankTextBox.ID = ((TextBox)tmpControl).ID;\n blankTextBox.Text = ((TextBox)tmpControl).Text;\n myDuplicate.Controls.Add(blankTextBox);\n break;\n\n // ...other types of controls (ddls, checkboxes, etc.)\n\n }\n}\n\nmyDuplicate.RenderControl(myWriter);\nreturn myTextWriter.ToString();\n" }, { "answer_id": 338061, "author": "Tom Jelen", "author_id": 28399, "author_profile": "https://Stackoverflow.com/users/28399", "pm_score": 5, "selected": true, "text": "public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n string rawHtml = RenderUserControlToString();\n }\n\n private string RenderUserControlToString()\n {\n UserControl myControl = (UserControl)LoadControl(\"WebUserControl1.ascx\");\n\n using (TextWriter myTextWriter = new StringWriter())\n using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))\n {\n myControl.RenderControl(myWriter);\n\n return myTextWriter.ToString();\n }\n }\n\n public override void VerifyRenderingInServerForm(Control control)\n { /* Do nothing */ }\n\n public override bool EnableEventValidation\n {\n get { return false; }\n set { /* Do nothing */}\n }\n}\n" }, { "answer_id": 22836768, "author": "TechyGypo", "author_id": 880792, "author_profile": "https://Stackoverflow.com/users/880792", "pm_score": -1, "selected": false, "text": "LoadControl UserControl UserControl uc = new UserControl();\nControl c = uc.LoadControl(\"newUserControl.ascx\");\nc.RenderControl(myWriter);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
334,388
<p>thanks in advance for your help. I am wondering if there is a (design) pattern that can be applied to this problem. </p> <p><b>I am looking to parse, process, and extract out values from text files with similar, but differing formats.</b></p> <p>More specifically, I am building a processing engine that accepts Online Poker Hand History files from a multitude of different websites and parses out specific data fields (Hand #, DateTime, Players). I will need the logic to parse the files to be slightly different for each format, but the processing of the extracted values will be the same.</p> <p>My first thought would be to create just 1 class that accepts a "schema" for each file type and parses/processes accordingly. I am sure there is a better solution to this.</p> <p>Thanks! </p> <p><b>Bonus Point:</b> Any specific implementation hints in C#.</p>
[ { "answer_id": 334453, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 1, "selected": false, "text": "public interface IDataProvider\n{\n IOnlinePokerInfo ParseFileInformation(FileInfo input);\n}\n\npublic interface IOnlinePokerInfo\n{\n int Hand { get; set; }\n DateTime DateInfo { get; set; }\n List<IPlayer> Players { get; set; }\n void ProcessInformation();\n}\n\npublic interface IPlayer\n{\n string Name { get; set; }\n}\n\npublic class MyOnlinePokerInfo : IOnlinePokerInfo\n{\n private int hand;\n private DateTime date;\n private List<IPlayer> players;\n\n public int Hand { get { return hand; } set { hand = value; } }\n public DateTime DateInfo { get { return date; } set { date = value; } }\n public List<IPlayer> Players { get { return players; } set { players = value; } }\n\n public MyOnlinePokerInfo(int hand, DateTime date)\n {\n this.hand = hand;\n this.date = date;\n players = new List<IPlayer>();\n }\n\n public MyOnlinePokerInfo(int hand, DateTime date, List<IPlayer> players)\n : this(hand, date)\n {\n this.players = players;\n }\n\n public void AddPlayer(IPlayer player)\n {\n players.Add(player);\n }\n\n public void ProcessInformation()\n {\n Console.WriteLine(ToString());\n }\n\n public override string ToString()\n {\n StringBuilder info = new StringBuilder(\"Hand #: \" + hand + \" Date: \" + date.ToLongDateString());\n info.Append(\"\\nPlayers:\");\n foreach (var s in players)\n {\n info.Append(\"\\n\"); \n info.Append(s.Name);\n }\n return info.ToString();\n }\n}\n\npublic class MySampleProvider1 : IDataProvider\n{\n public IOnlinePokerInfo ParseFileInformation(FileInfo input)\n {\n MyOnlinePokerInfo info = new MyOnlinePokerInfo(1, DateTime.Now);\n IPlayer p = new MyPlayer(\"me\");\n info.AddPlayer(p);\n return info;\n }\n}\n\npublic class MySampleProvider2 : IDataProvider\n{\n public IOnlinePokerInfo ParseFileInformation(FileInfo input)\n {\n MyOnlinePokerInfo info = new MyOnlinePokerInfo(2, DateTime.Now);\n IPlayer p = new MyPlayer(\"you\");\n info.AddPlayer(p);\n return info;\n }\n}\n\npublic class MyPlayer : IPlayer\n{\n private string name;\n public string Name { get { return name; } set { name = value; } }\n\n public MyPlayer(string name)\n {\n this.name = name;\n }\n}\n\npublic class OnlinePokerInfoManager\n{\n static void Main(string[] args)\n {\n List<IOnlinePokerInfo> infos = new List<IOnlinePokerInfo>();\n\n MySampleProvider1 prov1 = new MySampleProvider1();\n infos.Add(prov1.ParseFileInformation(new FileInfo(@\"c:\\file1.txt\")));\n\n MySampleProvider2 prov2 = new MySampleProvider2();\n infos.Add(prov2.ParseFileInformation(new FileInfo(@\"c:\\file2.log\")));\n\n foreach (var m in infos)\n {\n m.ProcessInformation();\n }\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39365/" ]
334,404
<p>When I run <code>get-user|get-member</code> in powershell with the exchange add-in I noticed there is no description property.</p> <p>Does anyone know if it has been renamed to something else or another way of accessing it? </p>
[ { "answer_id": 334820, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 3, "selected": true, "text": "[PS] C:\\>$ANR = \"testuser@example.com\"\n[PS] C:\\>$foo = [adsi](\"LDAP://\" + (get-user $ANR).DistinguishedName)\n[PS] C:\\>$foo.description\nMy Description\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18853/" ]
334,415
<p>What would be the benefit of using decimal.compare vs. just using a > or &lt; to compare to variables? </p>
[ { "answer_id": 334451, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "Comparison<decimal> Comparison<decimal> foo = decimal.Compare;\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2636656/" ]
334,431
<p>I've recently started upgrading some applications to use Spring Webflow 2, and I want to make use of the new Ajax functionality that comes with Webflow 2. Can somebody please direct me to a tutorial for integrating Tiles 2 with Spring Webflow (since that's apparently what they recommend). I've found the documentation that comes with Webflow 2 in this regard to be absolutely useless.</p>
[ { "answer_id": 838242, "author": "TM.", "author_id": 12983, "author_profile": "https://Stackoverflow.com/users/12983", "pm_score": 2, "selected": false, "text": "<bean id=\"tilesViewResolver\" class=\"org.springframework.web.servlet.view.UrlBasedViewResolver\">\n <property name=\"viewClass\" value=\"org.springframework.web.servlet.view.tiles2.TilesView\" />\n</bean>\n<bean class=\"org.springframework.web.servlet.view.tiles2.TilesConfigurer\">\n <property name=\"definitions\" value=\"/WEB-INF/flows/main/main-tiles.xml\" />\n</bean>\n" }, { "answer_id": 1101321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<bean id=\"tilesConfigurer\"\n class=\"org.springframework.web.servlet.view.tiles2.TilesConfigurer\">\n <property name=\"definitions\">\n <list>\n <value>/WEB-INF/tiles-defs/templates.xml</value>\n </list>\n </property>\n</bean>\n\n<bean id=\"urlMapping\"\n class=\"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping\">\n <property name=\"mappings\">\n <props>\n <prop key=\"/flow/**/*.html\">\n flowController\n </prop>\n <prop key=\"/**/*.html\">viewController</prop>\n </props>\n </property>\n <property name=\"order\" value=\"1\" />\n</bean>\n\n<bean id=\"tilesViewResolver\"\n class=\"org.springframework.web.servlet.view.UrlBasedViewResolver\">\n <property name=\"viewClass\"\n value=\"org.springframework.web.servlet.view.tiles2.TilesView\" />\n</bean>\n\n<bean id=\"flowController\"\n class=\"org.springframework.webflow.mvc.servlet.FlowController\">\n <property name=\"flowExecutor\" ref=\"flowExecutor\" />\n</bean>\n\n<webflow:flow-executor id=\"flowExecutor\"\n flow-registry=\"flowRegistry\" />\n\n<webflow:flow-registry id=\"flowRegistry\" flow-builder-services=\"flowBuilderServices\"\n base-path=\"/WEB-INF/flow/user\">\n <webflow:flow-location path=\"/manage-users.xml\" />\n</webflow:flow-registry>\n\n\n<webflow:flow-builder-services id=\"flowBuilderServices\"\n view-factory-creator=\"viewFactoryCreator\" />\n\n<bean id=\"viewFactoryCreator\"\n class=\"org.springframework.webflow.mvc.builder.MvcViewFactoryCreator\">\n <property name=\"viewResolvers\" ref=\"tilesViewResolver\" />\n</bean>\n" }, { "answer_id": 1172699, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " <!-- Plugs in a custom creator for Web Flow views -->\n<webflow:flow-builder-services id=\"flowBuilderServices\" view-factory-creator=\"mvcViewFactoryCreator\" />\n\n<!-- Configures Web Flow to use Tiles to create views for rendering; Tiles allows for applying consistent layouts to your views -->\n<bean id=\"mvcViewFactoryCreator\" class=\"org.springframework.webflow.mvc.builder.MvcViewFactoryCreator\">\n <property name=\"viewResolvers\" ref=\"tilesViewResolver\" />\n</bean>\n <!-- Configures the Tiles layout system -->\n<bean class=\"org.springframework.web.servlet.view.tiles2.TilesConfigurer\">\n <property name=\"definitions\">\n <list>\n <value>/WEB-INF/views/layouts/page.xml</value>\n <value>/WEB-INF/views/layouts/table.xml</value>\n <value>/WEB-INF/views/globalViews.xml</value>\n <value>/WEB-INF/views/userViews.xml</value>\n </list>\n </property>\n</bean>\n <!--\n - This bean configures the UrlBasedViewResolver, which resolves logical view names \n - by delegating to the Tiles layout system. A view name to resolve is treated as\n - the name of a tiles definition.\n -->\n<bean id=\"tilesViewResolver\" class=\"org.springframework.js.ajax.AjaxUrlBasedViewResolver\">\n <property name=\"viewClass\" value=\"org.springframework.webflow.mvc.view.FlowAjaxTilesView\" />\n</bean>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32232/" ]
334,439
<p>We have recently been faced with the problem of porting our C++ framework to an ARM platform running uClinux where the only vendor supported compiler is GCC 2.95.3. The problem we have run into is that exceptions are extremely unreliable causing everything from not being caught at all to being caught by an unrelated thread(!). This seems to be a documented bug, i.e. <a href="http://gcc.gnu.org/ml/gcc/2003-08/msg01013.html" rel="noreferrer">here</a> and <a href="http://osdir.com/ml/lib.uclibc.general/2003-05/msg00121.html" rel="noreferrer">here</a>.</p> <p>After some deliberation we decided to eliminate exceptions altoghether as we have reached a point where exceptions do a lot of damage to running applications. The main concern now is how to manage cases where a constructor failed.</p> <p>We have tried <a href="http://www.informit.com/guides/content.aspx?g=cplusplus&amp;seqNum=264" rel="noreferrer">lazy evaluation</a>, where each method has the ability to instantiate dynamic resources and return a status value but that means that every class method has to return a return value which makes for a <strong>lot</strong> of ifs in the code and is very annoying in methods which generally would never cause an error.</p> <p>We looked into adding a static <em>create</em> method which returns a pointer to a created object or NULL if creation failed but that means we cannot store objects on the stack anymore, and there is still need to pass in a reference to a status value if you want to act on the actual error.</p> <p>According to Google's C++ Style Guide they <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Exceptions" rel="noreferrer">do not use exceptions</a> and only do trivial work in their constructors, using an init method for non-trivial work (<a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Doing_Work_in_Constructors" rel="noreferrer">Doing Work in Constructors</a>). I cannot however find anything about how they handle construction errors when using this approach.</p> <p>Has anyone here tried eliminating exceptions and come up with a good solution to handling construction failure?</p>
[ { "answer_id": 334484, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": true, "text": "MyClassWithNoThrowConstructor foo;\nif (foo.init(bar, baz, etc) != 0) {\n // error-handling code\n} else {\n // phew, we got away with it. Now for the next object...\n}\n MyClassWithNoThrowConstructor *foo = new MyClassWithNoThrowConstructor();\nif (foo == NULL) {\n // out of memory handling code\n} else if (foo->init(bar, baz, etc) != 0) {\n delete foo;\n // error-handling code\n} else {\n // success, we can use foo\n}\n" }, { "answer_id": 334637, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "struct error_type {\n explicit error_type(int code):code(code) { }\n\n operator bool() const {\n return code == 0;\n }\n\n int get_code() { return code; }\n int const code;\n};\n\n#define checked_construction(T, N, A) \\\n T N; \\\n if(error_type const& error = error_type(N.init A))\n else 0 struct i_can_fail {\n i_can_fail() {\n // constructor cannot fail\n } \n\n int init(std::string p1, bool p2) {\n // init using the given parameters\n return 0; // successful\n } \n};\n\nvoid do_something() {\n checked_construction(i_can_fail, name, (\"hello\", true)) {\n // alright. use it\n name.do_other_thing();\n } else {\n // handle failure\n std::cerr << \"failure. error: \" << error.get_code() << std::endl;\n }\n\n // name is still in scope. here is the common code\n}\n error_type" }, { "answer_id": 334811, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "class MyClass\n{\npublic:\n MyClass() : m_resource(NULL)\n {\n m_resource = GetResource();\n }\n bool IsValid() const\n {\n return m_resource != NULL;\n }\nprivate:\n Resource * m_resource;\n};\n\nMyClass myobj;\nif (!myobj.IsValid())\n{\n // error handling goes here\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22247/" ]
334,471
<p>Here is the situation:</p> <p>I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows services, but has no built-in method to query their states. Fortunately, it allows you to create custom actions in Java which can be called at any time during the installation process (by way of what I consider to be a rather convoluted API). </p> <p>I just need something that will tell me if a specific service is started or stopped.</p> <p>The IDE also allows calling batch scripts, so this is an option as well, although once the script is run, there is almost no way to verify that it succeeded, so I'm trying to avoid that.</p> <p>Any suggestions or criticisms are welcome.</p>
[ { "answer_id": 334632, "author": "Yuval", "author_id": 2819, "author_profile": "https://Stackoverflow.com/users/2819", "pm_score": 5, "selected": true, "text": "String STATE_PREFIX = \"STATE : \";\n\nString s = runProcess(\"sc query \\\"\"+serviceName+\"\\\"\");\n// check that the temp string contains the status prefix\nint ix = s.indexOf(STATE_PREFIX);\nif (ix >= 0) {\n // compare status number to one of the states\n String stateStr = s.substring(ix+STATE_PREFIX.length(), ix+STATE_PREFIX.length() + 1);\n int state = Integer.parseInt(stateStr);\n switch(state) {\n case (1): // service stopped\n break;\n case (4): // service started\n break;\n }\n}\n runProcess" }, { "answer_id": 335090, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "com.installshield.wizard.platform.win32\nInterface Win32Service\n\nAll Superinterfaces:\n Service \n public NTServiceStatus queryNTServiceStatus(String name)\n throws ServiceException\n\n Calls the Win32 QueryServiceStatus to retrieve the status of the specified service. See the Win32 documentation for this API for more information.\n\n Parameters:\n name - The internal name of the service. \n Throws:\n ServiceException\n" }, { "answer_id": 336949, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 3, "selected": false, "text": "import java.io.File;\nimport java.io.FileWriter;\n\npublic class VBSUtils {\n private VBSUtils() { }\n\n public static boolean isServiceRunning(String serviceName) {\n try {\n File file = File.createTempFile(\"realhowto\",\".vbs\");\n file.deleteOnExit();\n FileWriter fw = new java.io.FileWriter(file);\n\n String vbs = \"Set sh = CreateObject(\\\"Shell.Application\\\") \\n\"\n + \"If sh.IsServiceRunning(\\\"\"+ serviceName +\"\\\") Then \\n\"\n + \" wscript.Quit(1) \\n\"\n + \"End If \\n\"\n + \"wscript.Quit(0) \\n\";\n fw.write(vbs);\n fw.close();\n Process p = Runtime.getRuntime().exec(\"wscript \" + file.getPath());\n p.waitFor();\n return (p.exitValue() == 1);\n }\n catch(Exception e){\n e.printStackTrace();\n }\n return false;\n }\n\n\n public static void main(String[] args){\n //\n // DEMO\n //\n String result = \"\";\n msgBox(\"Check if service 'Themes' is running (should be yes)\");\n result = isServiceRunning(\"Themes\") ? \"\" : \" NOT \";\n msgBox(\"service 'Themes' is \" + result + \" running \");\n\n msgBox(\"Check if service 'foo' is running (should be no)\");\n result = isServiceRunning(\"foo\") ? \"\" : \" NOT \";\n msgBox(\"service 'foo' is \" + result + \" running \");\n }\n\n public static void msgBox(String msg) {\n javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)\n null, msg, \"VBSUtils\", javax.swing.JOptionPane.DEFAULT_OPTION);\n }\n}\n" }, { "answer_id": 3992927, "author": "Wil S", "author_id": 121421, "author_profile": "https://Stackoverflow.com/users/121421", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Returns true if the specified service is running, or false if it is not present or not running.\n /// </summary>\n /// <param name=\"serviceName\">Name of the service to check.</param>\n /// <returns>Returns true if the specified service is running, or false if it is not present or not running.</returns>\n static bool IsServiceRunning(string serviceName)\n {\n bool rVal = false;\n try\n {\n IntPtr smHandle = NativeMethods.OpenSCManager(null, null, NativeMethods.ServiceAccess.ENUMERATE_SERVICE);\n if (smHandle != IntPtr.Zero)\n {\n IntPtr svHandle = NativeMethods.OpenService(smHandle, serviceName, NativeMethods.ServiceAccess.ENUMERATE_SERVICE);\n if (svHandle != IntPtr.Zero)\n {\n NativeMethods.SERVICE_STATUS servStat = new NativeMethods.SERVICE_STATUS();\n if (NativeMethods.QueryServiceStatus(svHandle, servStat))\n {\n rVal = servStat.dwCurrentState == NativeMethods.ServiceState.Running;\n }\n NativeMethods.CloseServiceHandle(svHandle);\n }\n NativeMethods.CloseServiceHandle(smHandle);\n }\n }\n catch (System.Exception )\n {\n\n }\n return rVal;\n }\n\npublic static class NativeMethods\n{\n [DllImport(\"AdvApi32\")]\n public static extern IntPtr OpenSCManager(string machineName, string databaseName, ServiceAccess access);\n [DllImport(\"AdvApi32\")]\n public static extern IntPtr OpenService(IntPtr serviceManagerHandle, string serviceName, ServiceAccess access);\n [DllImport(\"AdvApi32\")]\n public static extern bool CloseServiceHandle(IntPtr serviceHandle);\n [DllImport(\"AdvApi32\")]\n public static extern bool QueryServiceStatus(IntPtr serviceHandle, [Out] SERVICE_STATUS status);\n\n [Flags]\n public enum ServiceAccess : uint\n {\n ALL_ACCESS = 0xF003F,\n CREATE_SERVICE = 0x2,\n CONNECT = 0x1,\n ENUMERATE_SERVICE = 0x4,\n LOCK = 0x8,\n MODIFY_BOOT_CONFIG = 0x20,\n QUERY_LOCK_STATUS = 0x10,\n GENERIC_READ = 0x80000000,\n GENERIC_WRITE = 0x40000000,\n GENERIC_EXECUTE = 0x20000000,\n GENERIC_ALL = 0x10000000\n }\n\n public enum ServiceState\n {\n Stopped = 1,\n StopPending = 3,\n StartPending = 2,\n Running = 4,\n Paused = 7,\n PausePending =6,\n ContinuePending=5\n }\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n public class SERVICE_STATUS\n {\n public int dwServiceType;\n public ServiceState dwCurrentState;\n public int dwControlsAccepted;\n public int dwWin32ExitCode;\n public int dwServiceSpecificExitCode;\n public int dwCheckPoint;\n public int dwWaitHint;\n };\n}\n" }, { "answer_id": 21281573, "author": "mms", "author_id": 1364048, "author_profile": "https://Stackoverflow.com/users/1364048", "pm_score": 3, "selected": false, "text": "public void checkService() {\n String serviceName = \"myService\"; \n\n try {\n Process process = new ProcessBuilder(\"C:\\\\Windows\\\\System32\\\\sc.exe\", \"query\" , serviceName ).start();\n InputStream is = process.getInputStream();\n InputStreamReader isr = new InputStreamReader(is);\n BufferedReader br = new BufferedReader(isr);\n\n String line;\n String scOutput = \"\";\n\n // Append the buffer lines into one string\n while ((line = br.readLine()) != null) {\n scOutput += line + \"\\n\" ;\n }\n\n if (scOutput.contains(\"STATE\")) {\n if (scOutput.contains(\"RUNNING\")) {\n System.out.println(\"Service running\");\n } else {\n System.out.println(\"Service stopped\");\n } \n } else {\n System.out.println(\"Unknown service\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n } \n}\n" }, { "answer_id": 63379279, "author": "Muhammad Aasharib Nawshad", "author_id": 7332002, "author_profile": "https://Stackoverflow.com/users/7332002", "pm_score": 0, "selected": false, "text": "public boolean checkIfServiceRunning(String serviceName) {\n Process process;\n try {\n process = Runtime.getRuntime().exec(\"sc query \" + serviceName);\n Scanner reader = new Scanner(process.getInputStream(), \"UTF-8\");\n while(reader.hasNextLine()) {\n if(reader.nextLine().contains(\"RUNNING\")) {\n return true;\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n } \n return false;\n}\n" }, { "answer_id": 70277801, "author": "Arun Sharma", "author_id": 5810983, "author_profile": "https://Stackoverflow.com/users/5810983", "pm_score": 1, "selected": false, "text": "[SC] OpenService FAILED 1060: The specified service does not exist as an installed service.\n ([SC] ControlService FAILED 1062: The service has not been started)\n TYPE : 10 WIN32_OWN_PROCESS\n STATE : 2 START_PENDING\n (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)\n WIN32_EXIT_CODE : 0 (0x0)\n SERVICE_EXIT_CODE : 0 (0x0)\n CHECKPOINT : 0x0\n WAIT_HINT : 0x7d0\n PID : 21100code here\n public static void checkBackgroundService(String serviceName) {\n Process process;\n try {\n process = Runtime.getRuntime().exec(\"sc interrogate \" + serviceName);\n Scanner reader = new Scanner(process.getInputStream(), \"UTF-8\");\n StringBuffer buffer = new StringBuffer();\n while (reader.hasNextLine()) {\n buffer.append(reader.nextLine());\n }\n System.out.println(buffer.toString());\n if (buffer.toString().contains(\"1060:\")) {\n System.out.println(\"Specified Service does not exist\");\n } else if (buffer.toString().contains(\"1062:\")) {\n System.out.println(\"Specified Service is not started (not running)\");\n } else {\n System.out.println(\"Specified Service is running\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42489/" ]
334,472
<p>Running a ServiceHost with a single contract is working fine like this:</p> <pre><code>servicehost = new ServiceHost(typeof(MyService1)); servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService1"); servicehost.Open(); </code></pre> <p>Now I'd like to add a second (3rd, 4th, ...) contract. My first guess would be to just add more endpoints like this:</p> <pre><code>servicehost = new ServiceHost(typeof(MyService1)); servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService1"); servicehost.AddServiceEndpoint(typeof(IMyService2), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService2"); servicehost.Open(); </code></pre> <p>But of course this does not work, since in the creation of ServiceHost I can either pass MyService1 as parameter or MyService2 - so I can add a lot of endpoints to my service, but all have to use the same contract, since I only can provide one implementation?<br> I got the feeling I'm missing the point, here. Sure there must be some way to provide an implementation for every endpoint-contract I add, or not?</p>
[ { "answer_id": 334554, "author": "chilltemp", "author_id": 28736, "author_profile": "https://Stackoverflow.com/users/28736", "pm_score": 7, "selected": true, "text": "servicehost = new ServiceHost(typeof(WcfEntryPoint));\nservicehost.Open(); \n\npublic class WcfEntryPoint : IMyService1, IMyService2\n{\n #region IMyService1\n #endregion\n\n #region IMyService2\n #endregion\n}\n // WcfEntryPoint.IMyService1.cs\npublic partial class WcfEntryPoint : IMyService1\n{\n // IMyService1 methods\n}\n\n// WcfEntryPoint.IMyService2.cs\npublic partial class WcfEntryPoint : IMyService2\n{\n // IMyService2 methods\n}\n" }, { "answer_id": 334641, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 3, "selected": false, "text": "host1 = new ServiceHost(typeof(MyService1));\nhost2 = new ServiceHost(typeof(MyService2));\n\nhost1.Open();\nhost2.Open();\n\npublic class MyService1 : IMyService1\n{\n #region IMyService1\n #endregion\n}\n\npublic class MyService2 : IMyService2\n{\n #region IMyService2\n #endregion\n}\n" }, { "answer_id": 338035, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 3, "selected": false, "text": "Add(x,y) Subtract(x,y) Multiply(x,y) Divide(x,y) PeformCalculation(obj) obj x, y action" }, { "answer_id": 1289064, "author": "Saajid Ismail", "author_id": 127488, "author_profile": "https://Stackoverflow.com/users/127488", "pm_score": 4, "selected": false, "text": "private void PublishWcfEndpoints()\n{\n var mappings = new Dictionary<Type, Type>\n {\n {typeof (IAuthenticationService), typeof (AuthenticationService)},\n {typeof(IUserService), typeof(UserService)},\n {typeof(IClientService), typeof(ClientService)}\n };\n\n\n foreach (var type in mappings)\n {\n Type contractType = type.Key;\n Type implementationType = type.Value;\n\n ServiceHost serviceHost = new ServiceHost(implementationType);\n ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(contractType, ServiceHelper.GetDefaultBinding(),\n Properties.Settings.Default.ServiceUrl + \"/\" + contractType.Name);\n endpoint.Behaviors.Add(new ServerSessionBehavior());\n\n ServiceDebugBehavior serviceDebugBehaviour =\n serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();\n serviceDebugBehaviour.IncludeExceptionDetailInFaults = true;\n\n log.DebugFormat(\"Published Service endpoint: {0}\", Properties.Settings.Default.ServiceUrl);\n\n serviceHost.Open();\n serviceHosts.Add(serviceHost);\n }\n\n}\n" }, { "answer_id": 1298840, "author": "Michel van Engelen", "author_id": 76068, "author_profile": "https://Stackoverflow.com/users/76068", "pm_score": 1, "selected": false, "text": "public class WcfEntryPoint : IMyService1, IMyService2 public partial class WcfEntryPoint : IMyService1 public partial class WcfEntryPoint : IMyService2" }, { "answer_id": 9508511, "author": "m0sa", "author_id": 155005, "author_profile": "https://Stackoverflow.com/users/155005", "pm_score": 3, "selected": false, "text": "ServiceHost RoutingService" }, { "answer_id": 32665830, "author": "Jacek Cz", "author_id": 794606, "author_profile": "https://Stackoverflow.com/users/794606", "pm_score": 2, "selected": false, "text": "servicehost = new ServiceHost(typeof(MyService1));\nservicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), \"net.tcp://127.0.0.1:800/MyApp/MyService1\");\nservicehost.AddServiceEndpoint(typeof(IMyService2), new NetTcpBinding(), \"net.tcp://127.0.0.1:800/MyApp/MyService2\");\nservicehost.Open();\n servicehost = new ServiceHost(typeof(MyService1));\n BasicHttpBinding binding = new BasicHttpBinding();\nservicehost.AddServiceEndpoint(typeof(IMyService1),binding , \"http://127.0.0.1:800/MyApp/MyService1\");\nservicehost.AddServiceEndpoint(typeof(IMyService2), binding, \"http://127.0.0.1:800/MyApp/MyService2\");\nservicehost.Open();\n" }, { "answer_id": 37841116, "author": "Rhyous", "author_id": 375727, "author_profile": "https://Stackoverflow.com/users/375727", "pm_score": 0, "selected": false, "text": "[ServiceContract]\npublic interface IMetaSomeObjectService : ISomeObjectService1, ISomeObjectService2\n{\n}\n [ServiceContract]\npublic interface ISomeOjectService1\n{\n [OperationContract]\n List<SomeOject> GetSomeObjects();\n}\n\n[ServiceContract]\npublic interface ISomeOjectService2\n{\n [OperationContract]\n void DoSomethingElse();\n}\n public class SomeObjectService : IMetaSomeObjectService\n{\n public List<SomeOject> GetSomeObjects()\n {\n // code here\n }\n\n public void DoSomethingElse()\n {\n // code here\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
334,479
<p>Is there a place I can find Backus–Naur Form or BNF grammars for popular languages? Whenever I do a search I don't turn up much, but I figure they must be published somewhere. I'm most interested in seeing one for Objective-C and maybe MySQL.</p>
[ { "answer_id": 334522, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "mysql-server/sql/sql_yacc.y" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
334,489
<p>Let’s say I have this markup:</p> <pre><code>&lt;div id="content"&gt; &lt;div id="firstP"&gt;&lt;p&gt;First paragraph&lt;/p&gt;&lt;/div&gt; &lt;div id="secondP"&gt;&lt;p&gt;Second paragraph&lt;/p&gt;&lt;/div&gt; &lt;div id="thirdP"&gt;&lt;p&gt;Third paragraph&lt;/p&gt;&lt;/div&gt; &lt;div id="fourthP"&gt;&lt;p&gt;Fourth paragraph&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to add a new <code>&lt;div&gt;</code> with jQuery and focus on this new element. <code>.focus</code> does not do anything.</p> <pre><code>function addParagraph() { var html = "&lt;div id=\"newP\"&gt;&lt;p&gt;New paragraph&lt;/p&gt;&lt;/div&gt;"; $("#content").append(html); $("#newP").focus(); } </code></pre> <p>Any idea why?</p>
[ { "answer_id": 334494, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": false, "text": "var html = \"<div id=\\\"newP\\\"><p>New paragraph</p></div>\";\n$(\"#content\").append(html);\n$(\"#newP p\").focus();\n\nvar html = \"<div id=\\\"newP\\\"><p>New paragraph</p></div>\";\n$(html)\n .appendTo('#content')\n .focus() // or scrollTo(), now...\n;\n" }, { "answer_id": 334497, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 2, "selected": false, "text": "$('div.pane').scrollTo(...);//all divs w/class pane\n $.scrollTo(...);//the plugin will take care of this\n" }, { "answer_id": 334513, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 3, "selected": false, "text": "http://localhost/mypage.html#fourthP\n" }, { "answer_id": 334529, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 1, "selected": false, "text": "$(\"#newP\").focus(); \n window.location.href=window.location.href + \"#newP\"; \n" }, { "answer_id": 1359549, "author": "Michal", "author_id": 166249, "author_profile": "https://Stackoverflow.com/users/166249", "pm_score": 6, "selected": false, "text": "<div class=\"someclass\" tabindex=\"100\">\n" }, { "answer_id": 3173350, "author": "User123342234", "author_id": 351625, "author_profile": "https://Stackoverflow.com/users/351625", "pm_score": 3, "selected": false, "text": "$('html, body').animate({ scrollTop: $(\"#newP\").offset().top }, 500);\n" }, { "answer_id": 14155220, "author": "Avinash", "author_id": 309003, "author_profile": "https://Stackoverflow.com/users/309003", "pm_score": 1, "selected": false, "text": "$('#table').attr(\"tabindex\",1).focus();\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
334,490
<p>I often get a problem with Windows Installer trying to uninstall a package, but it complains that:</p> <blockquote> <p>The feature you are trying to use is on a network resource that is unavailable.</p> </blockquote> <p>Is there a known means of uninstalling such packages when the original MSI is simply not available?</p>
[ { "answer_id": 334610, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 2, "selected": false, "text": "Office2010.msi" }, { "answer_id": 11004013, "author": "AnneTheAgile", "author_id": 242110, "author_profile": "https://Stackoverflow.com/users/242110", "pm_score": 3, "selected": false, "text": "msiexec.exe /x {your-product-code-guid}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
334,515
<p>This question regards unit testing in Visual Studio using MSTest (this is important, because of MSTest's <a href="http://blogs.msdn.com/nnaderi/archive/2007/02/17/explaining-execution-order.aspx" rel="noreferrer">execution order</a>). Both the method marked [TestInitialize] and the test class constructor will run before each test method.</p> <p>So, the question is, what do you tend to do in each of these areas? Do you avoid performing certain activities in either? What is your reason: style, technical, superstition?</p>
[ { "answer_id": 437008, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 2, "selected": false, "text": "[TestInitialize]" }, { "answer_id": 7079605, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 7, "selected": true, "text": "TestMethod public class TestsForWhatever\n{\n public TestsForWhatever()\n {\n // You get one of these per test method, yay!\n }\n\n [TestInitialize] \n public void Initialize() \n {\n // and one of these too! \n }\n\n [TestMethod]\n public void AssertItDoesSomething() { }\n\n [TestMethod]\n public void AssertItDoesSomethingElse() { }\n}\n Establish Because It [Subject(typeof(Whatever))]\npublic class When_doing_whatever\n{\n Establish context = () => \n { \n // one of these for all your Its\n };\n\n Because of = () => _subject.DoWhatever();\n\n It should_do_something;\n It should_do_something_else;\n}\n" }, { "answer_id": 45270180, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 3, "selected": false, "text": "TestContext readonly" }, { "answer_id": 56577294, "author": "sschoof", "author_id": 4319676, "author_profile": "https://Stackoverflow.com/users/4319676", "pm_score": 2, "selected": false, "text": "async [TestInitialize] async private string approver; \n\n [TestInitialize]\n public async Task Initialize()\n {\n approver = await File.ReadAllTextAsync(\"approver.json\");\n }\n" }, { "answer_id": 59503335, "author": "Jevgenij Kononov", "author_id": 6504460, "author_profile": "https://Stackoverflow.com/users/6504460", "pm_score": 0, "selected": false, "text": "private readonly IDebuggingService debuggingService;\n\npublic string StepName { get; set; }\n\npublic DebuggingStep(IDebuggingService _debuggingService)\n{\n _log.Starting();\n StepName = \"DebuggingStep\";\n\n debuggingService = _debuggingService \n ?? throw new ArgumentException(\"DebuggingStep init failure due to => IDebuggingService null\");\n}\n [Fact]\npublic void TestDebuggingStepConstructorWhen_InitServiceIsNull_ResultArgumentException() \n{\n //Arrange\n var arrange = new Action(() => \n {\n new DebuggingStep(null);\n });\n\n //Act\n\n //Arrange\n Assert.Throws<ArgumentException>(arrange);\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
334,518
<p>I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:</p> <pre><code>String s = new String("silly"); </code></pre> <p>Because it creates unnecessary <code>String</code> objects. But instead it should be written like this:</p> <pre><code>String s = "No longer silly"; </code></pre> <p>Ok fine so far...However, given this class:</p> <pre><code>public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); } this.s = s; } : : } CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish"; </code></pre> <ol> <li><p>Why is the first statement ok? Shouldn't it be </p> <p><code>CaseInsensitiveString cis = "Polish";</code></p></li> <li><p>How do I make <code>CaseInsensitiveString</code> behave like <code>String</code> so the above statement is OK (with and without extending <code>String</code>)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?</p></li> </ol>
[ { "answer_id": 334538, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "String String SomeStringClass cis = \"value\" String final" }, { "answer_id": 334540, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 3, "selected": false, "text": "java.lang.String final" }, { "answer_id": 334548, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 7, "selected": false, "text": "String String String s = new String(\"Polish\");\n \"Polish\" String CaseInsensitiveString cis = new CaseInsensitiveString(\"Polish\");\n" }, { "answer_id": 334550, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": false, "text": "CaseInsensitiveString cis = \"Polish\";\n" }, { "answer_id": 334562, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 0, "selected": false, "text": "String foo = \"text\";\n MyString bar = \"text\";\n" }, { "answer_id": 334569, "author": "Lucas Gabriel Sánchez", "author_id": 20601, "author_profile": "https://Stackoverflow.com/users/20601", "pm_score": 0, "selected": false, "text": "String s = \"Polish\";\n" }, { "answer_id": 334580, "author": "Leigh", "author_id": 26061, "author_profile": "https://Stackoverflow.com/users/26061", "pm_score": 6, "selected": false, "text": "System.out.println(\"foo\" == \"foo\");\nSystem.out.println(new String(\"bar\") == new String(\"bar\"));\n" }, { "answer_id": 334613, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 5, "selected": false, "text": "String s = \"Polish\";\nString t = \"Polish\";\n String s = new String(\"Polish\");\nString t = new String(\"Polish\");\n CaseInsensitiveString cis = \"Polish\";\n" }, { "answer_id": 334732, "author": "mson", "author_id": 36902, "author_profile": "https://Stackoverflow.com/users/36902", "pm_score": 3, "selected": false, "text": "String x = \"x\";\nx = \"Y\"; \n String a1 = new String(\"A\");\n\nString a2 = new String(\"A\");\n a1 a2 a1 a2 TextUtility.compare(string 1, string 2) \nTextUtility.compareIgnoreCase(string 1, string 2)\nTextUtility.camelHump(string 1)\n" }, { "answer_id": 336291, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": " // Lets test the insensitiveness\n CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf(\"sOmEtHiNg\");\n CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf(\"SoMeThInG\");\n\n assert cis5 == cis6;\n assert cis5.equals(cis6);\n C:\\oreyes\\samples\\java\\insensitive>type CaseInsensitiveString.java\nimport java.util.Map;\nimport java.util.HashMap;\n\npublic final class CaseInsensitiveString {\n\n\n private static final Map<String,CaseInsensitiveString> innerPool \n = new HashMap<String,CaseInsensitiveString>();\n\n private final String s;\n\n\n // Effective Java Item 1: Consider providing static factory methods instead of constructors\n public static CaseInsensitiveString valueOf( String s ) {\n\n if ( s == null ) {\n return null;\n }\n String value = s.toLowerCase();\n\n if ( !CaseInsensitiveString.innerPool.containsKey( value ) ) {\n CaseInsensitiveString.innerPool.put( value , new CaseInsensitiveString( value ) );\n }\n\n return CaseInsensitiveString.innerPool.get( value ); \n }\n\n // Class constructor: This creates a new instance each time it is invoked.\n public CaseInsensitiveString(String s){\n if (s == null) {\n throw new NullPointerException();\n } \n this.s = s.toLowerCase();\n }\n\n public boolean equals( Object other ) {\n if ( other instanceof CaseInsensitiveString ) {\n CaseInsensitiveString otherInstance = ( CaseInsensitiveString ) other;\n return this.s.equals( otherInstance.s );\n }\n\n return false;\n }\n\n\n public int hashCode(){\n return this.s.hashCode();\n }\n public static void main( String [] args ) {\n\n // Creating two different objects as in new String(\"Polish\") == new String(\"Polish\") is false\n CaseInsensitiveString cis1 = new CaseInsensitiveString(\"Polish\");\n CaseInsensitiveString cis2 = new CaseInsensitiveString(\"Polish\");\n\n // references cis1 and cis2 points to differents objects.\n // so the following is true\n assert cis1 != cis2; // Yes they're different\n assert cis1.equals(cis2); // Yes they're equals thanks to the equals method\n\n // Now let's try the valueOf idiom\n CaseInsensitiveString cis3 = CaseInsensitiveString.valueOf(\"Polish\");\n CaseInsensitiveString cis4 = CaseInsensitiveString.valueOf(\"Polish\");\n\n // References cis3 and cis4 points to same object.\n // so the following is true\n assert cis3 == cis4; // Yes they point to the same object\n assert cis3.equals(cis4); // and still equals.\n\n // Lets test the insensitiveness\n CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf(\"sOmEtHiNg\");\n CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf(\"SoMeThInG\");\n\n assert cis5 == cis6;\n assert cis5.equals(cis6);\n\n // Futhermore\n CaseInsensitiveString cis7 = CaseInsensitiveString.valueOf(\"SomethinG\");\n CaseInsensitiveString cis8 = CaseInsensitiveString.valueOf(\"someThing\");\n\n assert cis8 == cis5 && cis7 == cis6;\n assert cis7.equals(cis5) && cis6.equals(cis8);\n }\n\n}\n\nC:\\oreyes\\samples\\java\\insensitive>javac CaseInsensitiveString.java\n\n\nC:\\oreyes\\samples\\java\\insensitive>java -ea CaseInsensitiveString\n\nC:\\oreyes\\samples\\java\\insensitive>\n" }, { "answer_id": 2768998, "author": "javaguy", "author_id": 328323, "author_profile": "https://Stackoverflow.com/users/328323", "pm_score": 2, "selected": false, "text": "String String" }, { "answer_id": 4435721, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 2, "selected": false, "text": "CaseInsensitiveString String String String String" }, { "answer_id": 10528041, "author": "Surender Thakran", "author_id": 1376167, "author_profile": "https://Stackoverflow.com/users/1376167", "pm_score": 3, "selected": false, "text": "String s = \"Hello\";\n String s = new String(\"Hello\");\n" }, { "answer_id": 10662293, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "String s = \"Silly\";\n String s = new String(\"Silly\");\n CaseInsensitiveString cis = new CaseInsensitiveString(\"Polish\");\n" }, { "answer_id": 20797378, "author": "Akash5288", "author_id": 1901896, "author_profile": "https://Stackoverflow.com/users/1901896", "pm_score": 0, "selected": false, "text": " String str1 = \"foo\"; \n String str2 = \"foo\"; \n String str1 = new String(\"foo\"); \n String str2 = new String(\"foo\");\n" }, { "answer_id": 21208178, "author": "Vikas", "author_id": 1414800, "author_profile": "https://Stackoverflow.com/users/1414800", "pm_score": 4, "selected": false, "text": "String s1=\"foo\";\n String s2=\"foo\";\n String s3=new String(\"foo\");\n String s4=new String(\"foo\");\n System.out.println(s1==s2);// **true** due to literal comparison. System.out.println(s3==s4);// **false** due to object" }, { "answer_id": 30856029, "author": "Patrick Michaelsen", "author_id": 5013193, "author_profile": "https://Stackoverflow.com/users/5013193", "pm_score": -1, "selected": false, "text": "\"\" new String() 6, 6.0, 'c', \"text\" char[] value = {'t','e','x','t} new String(\"text\"); \n new String(new String(new char[]{'t','e','x','t'}));\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42496/" ]
334,519
<p>I've been attempting to hook a Rails application up to ActiveDirectory. I'll be synchronizing data about users between AD and a database, currently MySQL (but may turn into SQL Server or PostgreSQL).</p> <p>I've checked out activedirectory-ruby, and it looks really buggy (for a 1.0 release!?). It wraps Net::LDAP, so I tried using that instead, but it's really close to the actual syntax of LDAP, and I enjoyed the abstraction of ActiveDirectory-Ruby because of its ActiveRecord-like syntax.</p> <p>Is there an elegant ORM-type tool for a directory server? Better yet, if there were some kind of scaffolding tool for LDAP (CRUD for users, groups, organizational units, and so on). Then I could quickly integrate that with my existing authentication code though Authlogic, and keep all of the data synchronized.</p>
[ { "answer_id": 387304, "author": "Lolindrath", "author_id": 7985, "author_profile": "https://Stackoverflow.com/users/7985", "pm_score": 2, "selected": false, "text": "\"{MD5}\" + Base64.encode64(Digest::MD5.digest(pass))\n OpenSSL::Digest::MD4.hexdigest(Iconv.iconv(\"UCS-2\", \"UTF-8\", pass).join).upcase\n def authenticate(user, pass)" }, { "answer_id": 5684335, "author": "Phrogz", "author_id": 405017, "author_profile": "https://Stackoverflow.com/users/405017", "pm_score": 6, "selected": true, "text": "require 'net/ldap' # gem install net-ldap\n\ndef name_for_login( email, password )\n email = email[/\\A\\w+/].downcase # Throw out the domain, if it was there\n email << \"@mycompany.com\" # I only check people in my company\n ldap = Net::LDAP.new(\n host: 'ldap.mycompany.com', # Thankfully this is a standard name\n auth: { method: :simple, email: email, password:password }\n )\n if ldap.bind\n # Yay, the login credentials were valid!\n # Get the user's full name and return it\n ldap.search(\n base: \"OU=Users,OU=Accounts,DC=mycompany,DC=com\",\n filter: Net::LDAP::Filter.eq( \"mail\", email ),\n attributes: %w[ displayName ],\n return_result:true\n ).first.displayName.first\n end\nend\n first.displayName.first Net::LDAP#search first Net::LDAP::Entry some_entry.displayName some_entry['displayName'] Net::LDAP::Entry first" }, { "answer_id": 8946587, "author": "jordanpg", "author_id": 828638, "author_profile": "https://Stackoverflow.com/users/828638", "pm_score": 2, "selected": false, "text": "auth: { method: :simple, email: email, password:password }\n auth: { method: :simple, username: email, password:password }\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42486/" ]
334,532
<p>I'm generating a coupon based on dynamic input and a cropped image, and I'm displaying the coupon using ntml and css right now, the problem is, printing this has become an issue because of how backgrounds disappear when printing and other problems, so I think the best solution would be to be able to generate an image based on the html, or set up some kind of template that takes in strings and an image, and generates an image using the image fed in as a background and puts the coupon information on top.</p> <p>Is there anything that does this already?</p> <p>This is for an ASP.NET 3.5 C# website!</p> <p>Thanks in advance.</p> <p>edit: It'd be great if the output could be based on the HTML input, as the coupon is designed by manipulating the DOM using jQuery and dragging stuff around, it all works fine, it's just when it comes to the printing (to paper) it has z-indexing issues.</p>
[ { "answer_id": 334586, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 5, "selected": true, "text": "Bitmap FinalBitmap = new Bitmap();\nMemoryStream msStream = new MemoryStream();\n\nstrInputParameter == Request.Params(\"MagicParm\").ToString()\n\n// Magic code goes here to generate your bitmap image.\nFinalBitmap.Save(msStream, ImageFormat.Png);\n\nResponse.Clear();\nResponse.ContentType = \"image/png\";\n\nmsStream.WriteTo(Response.OutputStream);\n\nif ((FinalBitmap != null)) FinalBitmap.Dispose();\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29445/" ]
334,571
<p>I have a legacy MS Access 2007 table that contains 52 fields (1 field for each week of the year) representing historical sales data (plus one field for the year actually). I would like to convert this database into a more conventional Time/Value listing.</p> <p>Does anyone knows how to do that without writing queries with 52+ explicit parameters?</p> <p>(if a solution exists under MS SQL Server 2005, I can also export/import the table)</p>
[ { "answer_id": 334583, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": true, "text": "UNPIVOT PIVOT pvt Emp1 Emp2 Emp3 Emp4 Emp5 Emp1 Emp2 Employee --Create the table and insert values as portrayed in the previous example.\nCREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,\nEmp3 int, Emp4 int, Emp5 int)\nGO\nINSERT INTO pvt VALUES (1,4,3,5,4,4)\nINSERT INTO pvt VALUES (2,4,1,5,5,5)\nINSERT INTO pvt VALUES (3,4,3,5,4,4)\nINSERT INTO pvt VALUES (4,4,2,5,5,4)\nINSERT INTO pvt VALUES (5,5,1,5,5,5)\nGO\n--Unpivot the table.\nSELECT VendorID, Employee, Orders\nFROM \n (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5\n FROM pvt) p\nUNPIVOT\n (Orders FOR Employee IN \n (Emp1, Emp2, Emp3, Emp4, Emp5)\n)AS unpvt\nGO\n VendorID Employee Orders\n1 Emp1 4\n1 Emp2 3\n1 Emp3 5\n1 Emp4 4\n1 Emp5 4\n2 Emp1 4\n2 Emp2 1\n2 Emp3 5\n2 Emp4 5\n2 Emp5 5\n...\n" }, { "answer_id": 334588, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": " Select 1 as week, Week1Val as value from Table\n UNION\n Select 2 as week, Week2Val as value from Table\n UNION\n Select 3 as week, Week3Val as value from Table\n UNION\n ... \n UNION\n Select 52 as week, Week52Val as value from Table\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18858/" ]
334,579
<p>Do you have a default type that you prefer to use in your dealings with the results of LINQ queries?</p> <p>By default LINQ will return an <code>IEnumerable&lt;&gt;</code> or maybe an <code>IOrderedEnumerable&lt;&gt;</code>. We have found that a <code>List&lt;&gt;</code> is generally more useful to us, so have adopted a habit of <code>ToList()</code>ing our queries most of the time, and certainly using <code>List&lt;&gt;</code> in our function arguments and return values.</p> <p>The only exception to this has been in LINQ to SQL where calling <code>.ToList()</code> would enumerate the <code>IEnumerable</code> prematurely.</p> <p>We are also using WCF extensively, the default collection type of which is <code>System.Array</code>. We always change this to <code>System.Collections.Generic.List</code> in the Service Reference Settings dialog in VS2008 for consistency with the rest of our codebase.</p> <p>What do you do?</p>
[ { "answer_id": 334595, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "ToList List<T> IList<T> List<T>" }, { "answer_id": 337362, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 4, "selected": false, "text": "// This is just an example... imagine this is on the server only. It's the\n// basic method that gets the list of clients.\nprivate IEnumerable<Client> GetClients()\n{\n var result = MyDataContext.Clients; \n\n return result.AsEnumerable();\n}\n\n// This method here is actually called by the user...\npublic Client[] GetClientsForLoggedInUser()\n{\n var clients = GetClients().Where(client=> client.Owner == currentUser);\n\n return clients.ToArray();\n}\n private IQueryable<Client> GetClients()\n{\n var result = MyDataContext.Clients; \n\n return result.AsQueryable();\n}\n" }, { "answer_id": 337450, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 3, "selected": false, "text": "List<T> IList<T> yield return List<T> IList IEnumerable<T> ElementAt IList ToList yield return" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39709/" ]
334,625
<p>I'm using Hibernate 3.1 and Oracle 10 DB. The blob is defined as @Lob @Basic @Column in the Hibernate entity which corresponds to the relevant DB table. The error -java.sql.SQLException: Closed Connection- seem to appear once in while, not in every attempt to get the blob from the DB. This seems like a hibernate fetching issue, so I thought of specifying the type of fetch to be used - EAGER seems right in this case -but coudln't find any way to specify type of fetching for @Column type of object (there is a way to do that for collections / "one to many" relationships etc)</p> <p>Would appreciate your help, thanks.</p>
[ { "answer_id": 1437819, "author": "Flueras Bogdan", "author_id": 83843, "author_profile": "https://Stackoverflow.com/users/83843", "pm_score": 0, "selected": false, "text": "@Basic(fetch = FetchType.LAZY)\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42508/" ]
334,626
<p>When an item is clicked in the checkedlistbox, it gets highlighted. How can I prevent this highlighting effect? </p> <p>I can hook into the SelectedIndexChanged event and clear the selection, but the highlighting still happens and you see a blip. In fact, if you hold down the mouse click, never releasing it after you clicked on the checkbox area, the selection remains highlighted until you release the mouse button. I basically want to get rid of this highlighting effect altogether.</p>
[ { "answer_id": 334672, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 5, "selected": true, "text": "this.checkedListBox1.SelectionMode = System.Windows.Forms.SelectionMode.None;\n private void checkedListBox1_Click(object sender, EventArgs e)\n {\n for (int i = 0; i < checkedListBox1.Items.Count; i++)\n {\n\n\n if (checkedListBox1.GetItemRectangle(i).Contains(checkedListBox1.PointToClient(MousePosition)))\n {\n switch (checkedListBox1.GetItemCheckState(i))\n {\n case CheckState.Checked:\n checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);\n break;\n case CheckState.Indeterminate:\n case CheckState.Unchecked:\n checkedListBox1.SetItemCheckState(i, CheckState.Checked);\n break;\n } \n\n }\n\n }\n }\n" }, { "answer_id": 9144861, "author": "Mark", "author_id": 1189927, "author_profile": "https://Stackoverflow.com/users/1189927", "pm_score": 3, "selected": false, "text": "public partial class EnhancedCheckedListBox : CheckedListBox\n{\n /// <summary>Overrides the OnDrawItem for the CheckedListBox so that we can customize how the items are drawn.</summary>\n /// <param name=\"e\">The System.Windows.Forms.DrawItemEventArgs object with the details</param>\n /// <remarks>A CheckedListBox can only have one item selected at a time and it's always the item in focus.\n /// So, don't draw an item as selected since the selection colors are hideous. \n /// Just use the focus rect to indicate the selected item.</remarks>\n protected override void OnDrawItem(DrawItemEventArgs e)\n {\n Color foreColor = this.ForeColor;\n Color backColor = this.BackColor;\n\n DrawItemState s2 = e.State;\n\n //If the item is in focus, then it should always have the focus rect.\n //Sometimes it comes in with Focus and NoFocusRect.\n //This is annoying and the user can't tell where their focus is, so give it the rect.\n if ((s2 & DrawItemState.Focus) == DrawItemState.Focus)\n {\n s2 &= ~DrawItemState.NoFocusRect;\n }\n\n //Turn off the selected state. Note that the color has to be overridden as well, but I just did that for all drawing since I want them to match.\n if ((s2 & DrawItemState.Selected) == DrawItemState.Selected)\n {\n s2 &= ~DrawItemState.Selected;\n\n }\n\n //Console.WriteLine(\"Draw \" + e.Bounds + e.State + \" --> \" + s2);\n\n //Compile the new drawing args and let the base draw the item.\n DrawItemEventArgs e2 = new DrawItemEventArgs(e.Graphics, e.Font, e.Bounds, e.Index, s2, foreColor, backColor);\n base.OnDrawItem(e2);\n }\n}\n" }, { "answer_id": 10947014, "author": "victoria", "author_id": 1444300, "author_profile": "https://Stackoverflow.com/users/1444300", "pm_score": 5, "selected": false, "text": "private void checkedListBox1__SelectedIndexChanged(object sender, EventArgs e)\n {\n checkedListBox1.ClearSelected();\n }\n" }, { "answer_id": 24572511, "author": "Trilby_Rob", "author_id": 3805173, "author_profile": "https://Stackoverflow.com/users/3805173", "pm_score": 0, "selected": false, "text": " checkedListBox1_MouseMove(object sender, MouseEventArgs e)\n case CheckState.Checked:\n if (e.Button == MouseButtons.Right)\n {\n checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);\n } \n break;\n case CheckState.Unchecked:\n if (e.Button == MouseButtons.Left)\n {\n checkedListBox1.SetItemCheckState(i, CheckState.Checked);\n }\n break;\n" }, { "answer_id": 42327426, "author": "user3437460", "author_id": 3437460, "author_profile": "https://Stackoverflow.com/users/3437460", "pm_score": 0, "selected": false, "text": "foreach (int i in clb.CheckedIndices) //clb is your checkListBox\n clb.SetItemCheckState(i, CheckState.Unchecked);\nclb.SelectionMode = System.Windows.Forms.SelectionMode.None;\nclb.SelectionMode = System.Windows.Forms.SelectionMode.One;\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30581/" ]
334,628
<p>Using the <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow noreferrer">jQuery Validation</a> plugin and AJAX, how can I validate the contents of say an input (textbox) but pass more than one parameter to a controller action?</p> <p>A brilliant example of passing a single value via AJAX using the plugin can be found <a href="http://weblogs.asp.net/cibrax/archive/2008/08/01/combining-jquery-validation-with-asp-net-mvc.aspx" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 334657, "author": "adam", "author_id": 33604, "author_profile": "https://Stackoverflow.com/users/33604", "pm_score": 0, "selected": false, "text": "$(document).ready(function(){\n $(\"#form-sign-up\").validate( {\n rules: {\n email: {\n required: true,\n email: true\n },\n surname: {\n required: true,\n surname: true\n }\n },\n messages: {\n email: {\n required: \"Please provide an email\",\n email: \"Please provide a valid email\"\n },\n surname: {\n required: \"Please provide a surname\",\n surname: \"Please provide a valid surname\"\n }\n }\n });\n});\n" }, { "answer_id": 335568, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 3, "selected": true, "text": " <script type=\"text/javascript\">\n$(document).ready(function(){\n $(\"#form-sign-up\").validate(\n {\n var param1 = $('#mytextbox').val();\n\n rules:\n {\n login:\n {\n required: true,\n remote: '<%=Url.Action(\"IsLoginAvailable\", \"Accounts\") %>?param1=' + param1\n }\n } \n });\n\n});\n</script>\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791/" ]
334,630
<p>I'm trying to open a folder in explorer with a file selected.</p> <p>The following code produces a file not found exception: </p> <pre><code>System.Diagnostics.Process.Start( "explorer.exe /select," + listView1.SelectedItems[0].SubItems[1].Text + "\\" + listView1.SelectedItems[0].Text); </code></pre> <p>How can I get this command to execute in C#?</p>
[ { "answer_id": 334645, "author": "Tom Smykowski", "author_id": 38940, "author_profile": "https://Stackoverflow.com/users/38940", "pm_score": 7, "selected": true, "text": "Process.Start(String, String)\n explorer.exe -p\n Process.Start(\"explorer.exe\", \"-p\")\n" }, { "answer_id": 696144, "author": "Samuel Yang", "author_id": 84468, "author_profile": "https://Stackoverflow.com/users/84468", "pm_score": 9, "selected": false, "text": "// suppose that we have a test.txt at E:\\\nstring filePath = @\"E:\\test.txt\";\nif (!File.Exists(filePath))\n{\n return;\n}\n\n// combine the arguments together\n// it doesn't matter if there is a space after ','\nstring argument = \"/select, \\\"\" + filePath +\"\\\"\";\n\nSystem.Diagnostics.Process.Start(\"explorer.exe\", argument);\n" }, { "answer_id": 3851946, "author": "Adrian Hum", "author_id": 465428, "author_profile": "https://Stackoverflow.com/users/465428", "pm_score": 5, "selected": false, "text": "string argument = \"/select, \\\"\" + filePath +\"\\\"\";\n" }, { "answer_id": 9059842, "author": "BobWinters", "author_id": 1177401, "author_profile": "https://Stackoverflow.com/users/1177401", "pm_score": 4, "selected": false, "text": "string argument = \"/select, \\\"\" + filePath +\"\\\"\";\n" }, { "answer_id": 9571021, "author": "Corey", "author_id": 1250395, "author_profile": "https://Stackoverflow.com/users/1250395", "pm_score": 3, "selected": false, "text": "string windir = Environment.GetEnvironmentVariable(\"windir\");\nif (string.IsNullOrEmpty(windir.Trim())) {\n windir = \"C:\\\\Windows\\\\\";\n}\nif (!windir.EndsWith(\"\\\\\")) {\n windir += \"\\\\\";\n} \n\nFileInfo fileToLocate = null;\nfileToLocate = new FileInfo(\"C:\\\\Temp\\\\myfile.txt\");\n\nProcessStartInfo pi = new ProcessStartInfo(windir + \"explorer.exe\");\npi.Arguments = \"/select, \\\"\" + fileToLocate.FullName + \"\\\"\";\npi.WindowStyle = ProcessWindowStyle.Normal;\npi.WorkingDirectory = windir;\n\n//Start Process\nProcess.Start(pi)\n" }, { "answer_id": 9904834, "author": "Jan Croonen", "author_id": 1297721, "author_profile": "https://Stackoverflow.com/users/1297721", "pm_score": 6, "selected": false, "text": "string p = @\"C:\\tmp\\this path contains spaces, and,commas\\target.txt\";\nstring args = string.Format(\"/e, /select, \\\"{0}\\\"\", p);\n\nProcessStartInfo info = new ProcessStartInfo();\ninfo.FileName = \"explorer\";\ninfo.Arguments = args;\nProcess.Start(info);\n" }, { "answer_id": 39427395, "author": "RandomEngy", "author_id": 92371, "author_profile": "https://Stackoverflow.com/users/92371", "pm_score": 5, "selected": false, "text": "Process.Start explorer.exe /select [DllImport(\"shell32.dll\", SetLastError = true)]\npublic static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);\n\n[DllImport(\"shell32.dll\", SetLastError = true)]\npublic static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);\n\npublic static void OpenFolderAndSelectItem(string folderPath, string file)\n{\n IntPtr nativeFolder;\n uint psfgaoOut;\n SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);\n\n if (nativeFolder == IntPtr.Zero)\n {\n // Log error, can't find folder\n return;\n }\n\n IntPtr nativeFile;\n SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);\n\n IntPtr[] fileArray;\n if (nativeFile == IntPtr.Zero)\n {\n // Open the folder without the file selected if we can't find the file\n fileArray = new IntPtr[0];\n }\n else\n {\n fileArray = new IntPtr[] { nativeFile };\n }\n\n SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);\n\n Marshal.FreeCoTaskMem(nativeFolder);\n if (nativeFile != IntPtr.Zero)\n {\n Marshal.FreeCoTaskMem(nativeFile);\n }\n}\n" }, { "answer_id": 47182791, "author": "Zztri", "author_id": 8907541, "author_profile": "https://Stackoverflow.com/users/8907541", "pm_score": 3, "selected": false, "text": "explorer /select,\"c:\\space space\\space.txt\"\n System.Diagnostics.Process.Start(\"explorer.exe\",\"/select,\\\"c:\\space space\\space.txt\\\"\");\n" }, { "answer_id": 55816756, "author": "Bluescream", "author_id": 10881866, "author_profile": "https://Stackoverflow.com/users/10881866", "pm_score": 2, "selected": false, "text": " public static void ShowFileInExplorer(FileInfo file) {\n StartProcess(\"explorer.exe\", null, \"/select, \"+file.FullName.Quote());\n }\n public static Process StartProcess(FileInfo file, params string[] args) => StartProcess(file.FullName, file.DirectoryName, args);\n public static Process StartProcess(string file, string workDir = null, params string[] args) {\n ProcessStartInfo proc = new ProcessStartInfo();\n proc.FileName = file;\n proc.Arguments = string.Join(\" \", args);\n Logger.Debug(proc.FileName, proc.Arguments); // Replace with your logging function\n if (workDir != null) {\n proc.WorkingDirectory = workDir;\n Logger.Debug(\"WorkingDirectory:\", proc.WorkingDirectory); // Replace with your logging function\n }\n return Process.Start(proc);\n }\n static class Extensions\n{\n public static string Quote(this string text)\n {\n return SurroundWith(text, \"\\\"\");\n }\n public static string SurroundWith(this string text, string surrounds)\n {\n return surrounds + text + surrounds;\n }\n}\n" }, { "answer_id": 73406872, "author": "MensSana", "author_id": 1311370, "author_profile": "https://Stackoverflow.com/users/1311370", "pm_score": 1, "selected": false, "text": "private static void SelectFileInExplorer(string filePath)\n{\n Process.Start(new ProcessStartInfo()\n {\n FileName = \"explorer.exe\",\n Arguments = @$\"/select, \"\"{filePath}\"\"\"\n });\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41291/" ]
334,655
<p>I'd like to call a function in python using a dictionary with matching key-value pairs for the parameters.</p> <p>Here is some code:</p> <pre><code>d = dict(param='test') def f(param): print(param) f(d) </code></pre> <p>This prints <code>{'param': 'test'}</code> but I'd like it to just print <code>test</code>.</p> <p>I'd like it to work similarly for more parameters:</p> <pre><code>d = dict(p1=1, p2=2) def f2(p1, p2): print(p1, p2) f2(d) </code></pre> <p>Is this possible?</p>
[ { "answer_id": 334661, "author": "Patrick Harrington", "author_id": 41165, "author_profile": "https://Stackoverflow.com/users/41165", "pm_score": 3, "selected": false, "text": "d = {'param' : 'test'}\n\ndef f(dictionary):\n for key in dictionary:\n print key\n\nf(d)\n" }, { "answer_id": 334666, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 10, "selected": true, "text": "d = dict(p1=1, p2=2)\ndef f2(p1,p2):\n print p1, p2\nf2(**d)\n" }, { "answer_id": 43238973, "author": "David Parks", "author_id": 4790871, "author_profile": "https://Stackoverflow.com/users/4790871", "pm_score": 8, "selected": false, "text": "In[1]: def myfunc(a=1, b=2):\nIn[2]: print(a, b)\n\nIn[3]: mydict = {'a': 100, 'b': 200}\n\nIn[4]: myfunc(**mydict)\n100 200\n In[5]: mydict = {'a': 100}\nIn[6]: myfunc(**mydict)\n100 2\n In[7]: mydict = {'a': 100, 'b': 200}\nIn[8]: myfunc(a=3, **mydict)\n\nTypeError: myfunc() got multiple values for keyword argument 'a'\n In[9]: mydict = {'a': 100, 'b': 200, 'c': 300}\nIn[10]: myfunc(**mydict)\n\nTypeError: myfunc() got an unexpected keyword argument 'c'\n _ In[11]: def myfunc2(a=None, **_):\nIn[12]: print(a)\n\nIn[13]: mydict = {'a': 100, 'b': 200, 'c': 300}\n\nIn[14]: myfunc2(**mydict)\n100\n In[15]: import inspect\nIn[16]: mydict = {'a': 100, 'b': 200, 'c': 300}\nIn[17]: filtered_mydict = {k: v for k, v in mydict.items() if k in [p.name for p in inspect.signature(myfunc).parameters.values()]}\nIn[18]: myfunc(**filtered_mydict)\n100 200\n In[19]: def myfunc3(a, *posargs, b=2, **kwargs):\nIn[20]: print(a, b)\nIn[21]: print(posargs)\nIn[22]: print(kwargs)\n\nIn[23]: mylist = [10, 20, 30]\nIn[24]: mydict = {'b': 200, 'c': 300}\n\nIn[25]: myfunc3(*mylist, **mydict)\n10 200\n(20, 30)\n{'c': 300}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1575281/" ]
334,658
<p>Which would be quicker.</p> <p>1) Looping a datareader and creating a custom rows and columns based populated datatable</p> <p>2) Or creating a dataAdapter object and just (.Fill)ing a datatable.</p> <p>Does the performance of a datareader still hold true upon dynamic creation of a datatable? </p>
[ { "answer_id": 334680, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "DataTable dt = new DataTable();\n\nusing (SqlConnection conn = GetOpenSqlConnection())\nusing (SqlCommand cmd = new SqlCommand(\"SQL Query here\", conn)\nusing (IDataReader rdr = cmd.ExecuteReader())\n{\n dt.Load(rdr);\n}\n .Fill()" }, { "answer_id": 14869531, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 1, "selected": false, "text": "DataReader Read IDataAdapter.Fill DataTable.Load public DataTable Read1<T>(string query) where T : IDbConnection, new()\n{\n using (var conn = new T())\n {\n using (var cmd = conn.CreateCommand())\n {\n cmd.CommandText = query;\n cmd.Connection.ConnectionString = _connectionString;\n cmd.Connection.Open();\n var table = new DataTable();\n table.Load(cmd.ExecuteReader());\n return table;\n }\n }\n}\n\npublic DataTable Read2<S, T>(string query) where S : IDbConnection, new() \n where T : IDbDataAdapter, IDisposable, new()\n{\n using (var conn = new S())\n {\n using (var da = new T())\n {\n using (da.SelectCommand = conn.CreateCommand())\n {\n da.SelectCommand.CommandText = query;\n da.SelectCommand.Connection.ConnectionString = _connectionString;\n DataSet ds = new DataSet(); //conn is opened by dataadapter\n da.Fill(ds);\n return ds.Tables[0];\n }\n }\n }\n}\n Stopwatch sw = Stopwatch.StartNew();\nDataTable dt = null;\nfor (int i = 0; i < 100; i++)\n{\n dt = Read1<MySqlConnection>(query); // ~9800ms\n dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms\n\n dt = Read1<SQLiteConnection>(query); // ~4000ms\n dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms\n\n dt = Read1<SqlCeConnection>(query); // ~5700ms\n dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms\n\n dt = Read1<SqlConnection>(query); // ~850ms\n dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms\n\n dt = Read1<VistaDBConnection>(query); // ~3900ms\n dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms\n}\nsw.Stop();\nMessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());\n Read1 Load DataTable Fill" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42446/" ]
334,669
<p>When the command prompt opens and then just closes really fast (because there isn't a pause line) is there a way to see what it just showed you? </p>
[ { "answer_id": 334682, "author": "joegtp", "author_id": 39431, "author_profile": "https://Stackoverflow.com/users/39431", "pm_score": 3, "selected": false, "text": "something.exe > c:\\temp\\output.txt\n" }, { "answer_id": 334688, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 1, "selected": false, "text": "c:\\> ipconfig /all\n" }, { "answer_id": 334755, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": true, "text": "pause" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161710/" ]
334,671
<p>I need to create a trigger in every database on my sql 2005 instance. I'm setting up some auditing ddl triggers.</p> <p>I create a cursor with all database names and try to execute a USE statement. This doesn't seem to change the database - the CREATE TRIGGER statement just fires in adventureworks repeatedly. The other option would be to prefix the trigger object with databasename.dbo.triggername. This doesn't work either - some kind of limitation in creating triggers. Of course, I could do this manually, but I'd prefer to get it scripted for easy application and removal. I have other options if I can't do this in 1 sql script, but I'd like to keep it simple :)</p> <p>Here is what I have so far - hopefully you can find a bonehead mistake!</p> <pre><code>--setup stuff... CREATE DATABASE DBA_AUDIT GO USE DBA_AUDIT GO CREATE TABLE AuditLog (ID INT PRIMARY KEY IDENTITY(1,1), Command NVARCHAR(1000), PostTime DATETIME, HostName NVARCHAR(100), LoginName NVARCHAR(100) ) GO CREATE ROLE AUDITROLE GO sp_adduser 'guest','guest','AUDITROLE' GO GRANT INSERT ON SCHEMA::[dbo] TO AUDITROLE --CREATE TRIGGER IN ALL NON SYSTEM DATABASES DECLARE @dataname varchar(255), @dataname_header varchar(255), @command VARCHAR(MAX), @usecommand VARCHAR(100) SET @command = ''; --get the list of database names DECLARE datanames_cursor CURSOR FOR SELECT name FROM sys.databases WHERE name not in ('master', 'pubs', 'tempdb', 'model','msdb') OPEN datanames_cursor FETCH NEXT FROM datanames_cursor INTO @dataname WHILE (@@fetch_status = 0) BEGIN PRINT '----------BEGIN---------' PRINT 'DATANAME variable: ' + @dataname; EXEC ('USE ' + @dataname); PRINT 'CURRENT db: ' + db_name(); SELECT @command = 'CREATE TRIGGER DBA_Audit ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS AS DECLARE @data XML DECLARE @cmd NVARCHAR(1000) DECLARE @posttime NVARCHAR(24) DECLARE @spid NVARCHAR(6) DECLARE @loginname NVARCHAR(100) DECLARE @hostname NVARCHAR(100) SET @data = EVENTDATA() SET @cmd = @data.value(''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'', ''NVARCHAR(1000)'') SET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''',''''))) SET @posttime = @data.value(''(/EVENT_INSTANCE/PostTime)[1]'', ''DATETIME'') SET @spid = @data.value(''(/EVENT_INSTANCE/SPID)[1]'', ''nvarchar(6)'') SET @loginname = @data.value(''(/EVENT_INSTANCE/LoginName)[1]'', ''NVARCHAR(100)'') SET @hostname = HOST_NAME() INSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName) VALUES(@cmd, @posttime, @hostname, @loginname);' EXEC (@command); FETCH NEXT FROM datanames_cursor INTO @dataname; PRINT '----------END---------' END CLOSE datanames_cursor DEALLOCATE datanames_cursor OUTPUT: ----------BEGIN--------- DATANAME variable: adventureworks CURRENT db: master Msg 2714, Level 16, State 2, Procedure DBA_Audit, Line 18 There is already an object named 'DBA_Audit' in the database. ----------END--------- ----------BEGIN--------- DATANAME variable: SQL_DBA CURRENT db: master Msg 2714, Level 16, State 2, Procedure DBA_Audit, Line 18 There is already an object named 'DBA_Audit' in the database. ----------END--------- </code></pre> <p>EDIT: I've already tried the sp_msforeachdb approach</p> <pre><code>Msg 111, Level 15, State 1, Line 1 'CREATE TRIGGER' must be the first statement in a query batch. </code></pre> <p>EDIT:</p> <p>Here is my final code - this exact script has not been tested, but it IS in production on about 100 or so databases. Cheers!</p> <p><strong>One caveat</strong> - your databases need to be in compatibility mode of 90(in options for each db), otherwise you may start getting errors. The account in the EXECUTE AS part of the statement also needs access to insert into your admin table.</p> <pre><code>USE [SQL_DBA] GO /****** Object: Table [dbo].[DDL_Login_Log] Script Date: 03/03/2009 17:28:10 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[DDL_Login_Log]( [DDL_Id] [int] IDENTITY(1,1) NOT NULL, [PostTime] [datetime] NOT NULL, [DB_User] [nvarchar](100) NULL, [DBName] [nvarchar](100) NULL, [Event] [nvarchar](100) NULL, [TSQL] [nvarchar](2000) NULL, [Object] [nvarchar](1000) NULL, CONSTRAINT [PK_DDL_Login_Log] PRIMARY KEY CLUSTERED ( [DDL_Id] ASC, [PostTime] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --This creates the trigger on the model database so all new DBs get it USE [model] GO /****** Object: DdlTrigger [ddl_DB_User] Script Date: 03/03/2009 17:26:13 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [ddl_DB_User] ON DATABASE FOR DDL_DATABASE_SECURITY_EVENTS AS DECLARE @data XML declare @user nvarchar(100) SET @data = EVENTDATA() select @user = convert(nvarchar(100), SYSTEM_USER) execute as login='domain\sqlagent' INSERT sql_dba.dbo.DDL_Login_Log (PostTime, DB_User, DBName, Event, TSQL,Object) VALUES (@data.value('(/EVENT_INSTANCE/PostTime)[1]', 'nvarchar(100)'), @user, db_name(), @data.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'), @data.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)'), @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(1000)') ) GO SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER OFF GO -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --CREATE TRIGGER IN ALL NON SYSTEM DATABASES DECLARE @dataname varchar(255), @dataname_header varchar(255), @command VARCHAR(MAX), @usecommand VARCHAR(100) SET @command = ''; DECLARE datanames_cursor CURSOR FOR SELECT name FROM sys.databases WHERE name not in ('master', 'pubs', 'tempdb', 'model','msdb') OPEN datanames_cursor FETCH NEXT FROM datanames_cursor INTO @dataname WHILE (@@fetch_status = 0) BEGIN PRINT '----------BEGIN---------' PRINT 'DATANAME variable: ' + @dataname; EXEC ('USE ' + @dataname); PRINT 'CURRENT db: ' + db_name(); SELECT @command = 'CREATE TRIGGER DBA_Audit ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS AS DECLARE @data XML DECLARE @cmd NVARCHAR(1000) DECLARE @posttime NVARCHAR(24) DECLARE @spid NVARCHAR(6) DECLARE @loginname NVARCHAR(100) DECLARE @hostname NVARCHAR(100) SET @data = EVENTDATA() SET @cmd = @data.value(''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'', ''NVARCHAR(1000)'') SET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''',''''))) SET @posttime = @data.value(''(/EVENT_INSTANCE/PostTime)[1]'', ''DATETIME'') SET @spid = @data.value(''(/EVENT_INSTANCE/SPID)[1]'', ''nvarchar(6)'') SET @loginname = @data.value(''(/EVENT_INSTANCE/LoginName)[1]'', ''NVARCHAR(100)'') SET @hostname = HOST_NAME() INSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName) VALUES(@cmd, @posttime, @hostname, @loginname);' EXEC (@command); FETCH NEXT FROM datanames_cursor INTO @dataname; PRINT '----------END---------' END CLOSE datanames_cursor DEALLOCATE datanames_cursor -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- ----Disable all triggers when things go haywire sp_msforeachdb @command1='use [?]; IF EXISTS (SELECT * FROM sys.triggers WHERE name = N''ddl_DB_User'' AND parent_class=0)disable TRIGGER [ddl_DB_User] ON DATABASE' </code></pre>
[ { "answer_id": 334711, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "sp_msforeachdb 'USE ?; PRINT ''Hello ?'''\n" }, { "answer_id": 334775, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 3, "selected": true, "text": "DECLARE @cmd NVARCHAR(2000), @my_db VARCHAR(255)\n\nSET @my_db = 'MyDatabaseName'\n\nSET @cmd = 'DECLARE @my_cmd NVARCHAR(2000); SET @my_cmd = ''CREATE TRIGGER DBA_Audit ON DATABASE\nFOR DDL_DATABASE_LEVEL_EVENTS\nAS\nDECLARE @data XML\nDECLARE @cmd NVARCHAR(1000)\nDECLARE @posttime NVARCHAR(24)\nDECLARE @spid NVARCHAR(6)\nDECLARE @loginname NVARCHAR(100)\nDECLARE @hostname NVARCHAR(100)\nSET @data = EVENTDATA()\nSET @cmd = @data.value(''''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'''', ''''NVARCHAR(1000)'''')\nSET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''''''','''''''')))\nSET @posttime = @data.value(''''(/EVENT_INSTANCE/PostTime)[1]'''', ''''DATETIME'''')\nSET @spid = @data.value(''''(/EVENT_INSTANCE/SPID)[1]'''', ''''nvarchar(6)'''')\nSET @loginname = @data.value(''''(/EVENT_INSTANCE/LoginName)[1]'''',\n ''''NVARCHAR(100)'''')\nSET @hostname = HOST_NAME()\nINSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName)\n VALUES(@cmd, @posttime, @hostname, @loginname);''; EXEC ' + @my_db + '..sp_executesql @my_cmd'\n\nEXEC (@cmd)\n" }, { "answer_id": 31927566, "author": "DCaugs", "author_id": 1286369, "author_profile": "https://Stackoverflow.com/users/1286369", "pm_score": 0, "selected": false, "text": "select name \ninto #d \nfrom sys.databases \n DECLARE @dbname varchar(100)\nDECLARE @Trig VARCHAR(max)\nselect @dbname = (select top 1 name FROM #d order by name asc)\n\nWHILE @dbname IS NOT NULL\nBEGIN \nSET @Trig = 'USE ' + @dbname +'; \nGO\n\nCREATE TRIGGER [DBA_KillerTrigger]\nON DATABASE\nAFTER DDL_DATABASE_LEVEL_EVENTS\nAS\n/*...Trigger magic goes here...*/\nGO\n\nENABLE TRIGGER [DBA_KillerTrigger] ON DATABASE\nGO\n\n\nPRINT @Trig\n\nSELECT @dbname = (select top 1 name FROM #d where name > @dbname order by name asc)\n\nEND\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37379/" ]
334,674
<p>So I don't do a lot of Win32 calls, but recently I have had to use the <a href="http://msdn.microsoft.com/en-us/library/ms724320(VS.85).aspx" rel="nofollow noreferrer"><code>GetFileTime()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/ms724933(VS.85).aspx" rel="nofollow noreferrer"><code>SetFileTime()</code></a> functions. Now although Win98 and below are not officially supported in my program people do use it there anyway, and I try to keep it as usable as possible. I was just wondering what will happen as those functions do not exist in pre-NT systems, will they receive an error message of some sort for example because in that case I will add in an OS check? Thanks</p>
[ { "answer_id": 334690, "author": "Roland Rabien", "author_id": 39138, "author_profile": "https://Stackoverflow.com/users/39138", "pm_score": 4, "selected": true, "text": "LoadLibrary() GetProcAddress() GetFileTime() SetFileTime() typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);\n\nUpdateLayeredWinFunc updateLayeredWindow = 0;\nHMODULE user32Mod = GetModuleHandle (_T(\"user32.dll\"));\nupdateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, \"UpdateLayeredWindow\");\n" }, { "answer_id": 337322, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "FindFirstFile() GetFileTime() SetFileTime()" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913/" ]
334,686
<p>I have Perl on Mac, Windows and Ubuntu. How can I tell from within the script which one is which? Thanks in advance.</p> <p><strong>Edit:</strong> I was asked what I am doing. It is a script, part of our cross-platform build system. The script recurses directories and figures out what files to build. Some files are platform-specific, and thus, on Linux I don't want to build the files ending with _win.cpp, etc.</p>
[ { "answer_id": 334700, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 7, "selected": true, "text": "$^O print \"$^O\\n\";\n linux MSWin32 $OSNAME use English qw' -no_match_vars ';\nprint \"$OSNAME\\n\";\n $^O darwin use Config;\n\nprint \"$Config{osname}\\n\";\nprint \"$Config{archname}\\n\";\n linux\ni486-linux-gnu-thread-multi\n $^O $OSNAME" }, { "answer_id": 336174, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "File::Spec File::Spec File::Spec::Win32 File::Spec::OS2 .pm # From the source code of File::Spec\nmy %module = (\n MSWin32 => 'Win32',\n os2 => 'OS2',\n VMS => 'VMS',\n NetWare => 'Win32', # Yes, File::Spec::Win32 works on NetWare.\n symbian => 'Win32', # Yes, File::Spec::Win32 works on symbian.\n dos => 'OS2', # Yes, File::Spec::OS2 works on DJGPP.\n cygwin => 'Cygwin',\n amigaos => 'AmigaOS');\n\n\nmy $module = $module{$^O} || 'Unix';\n\nrequire \"File/Spec/$module.pm\";\nour @ISA = (\"File::Spec::$module\");\n" }, { "answer_id": 337597, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 4, "selected": false, "text": "my $osname = $^O;\n\n\nif( $osname eq 'MSWin32' ){{\n eval { require Win32; } or last;\n $osname = Win32::GetOSName();\n\n # work around for historical reasons\n $osname = 'WinXP' if $osname =~ /^WinXP/;\n}}\n my ( $osvername, $major, $minor, $id ) = Win32::GetOSVersion();\n" }, { "answer_id": 8672463, "author": "Hawk", "author_id": 1038583, "author_profile": "https://Stackoverflow.com/users/1038583", "pm_score": 2, "selected": false, "text": "my $windows=($^O=~/Win/)?1:0;# Are we running on windows?\n" }, { "answer_id": 17814659, "author": "bcarroll", "author_id": 2611164, "author_profile": "https://Stackoverflow.com/users/2611164", "pm_score": 0, "selected": false, "text": "#Assign the $home_directory variable the path of the user's home directory\nmy $home_directory = ($^O eq /Win/) ? $ENV{HOMEPATH} : $ENV{HOME};\n#Then you can read/write to files in the home directory\nopen(FILE, \">$home_directory/my_tmp_file\");\nprint FILE \"This is a test\\n\";\nclose FILE;\n#And/or read the contents of the file\nopen(FILE, \"<$home_directory/my_tmp_file\");\nwhile (<FILE>){\n print $_;\n}\nclose FILE;\n" }, { "answer_id": 18569561, "author": "GC 13", "author_id": 1503750, "author_profile": "https://Stackoverflow.com/users/1503750", "pm_score": -1, "selected": false, "text": "NAME=\"UBUNTU\"\nVERSION=\"12.0.2 LTS, Precise Pangolin\"\nID=\"UBUNTU\"\nID_LIKE=debian\nPRETTY_NAME=\"Ubuntu precise (12.0.2 LTS)\"\nVERSION_ID=\"12.04\"\n" }, { "answer_id": 52863893, "author": "Randall", "author_id": 584940, "author_profile": "https://Stackoverflow.com/users/584940", "pm_score": 1, "selected": false, "text": "Perl::OSType Module::Build $^O Unix\nWindows\nEBCDIC\nMacOS\nVMS\nVOS\nRiscOS\nAmiga\nMPEiX\n @brian-d-foy File::Spec" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6444/" ]
334,691
<p>I need the tool for graphical representing of work flow in a program (like electronic circuits are described with graphical representation). The representation has to be like the following: functions are boxes and arrows between boxes are "messages". Like this:</p> <p><a href="http://img372.imageshack.us/img372/8471/functionsqv0.png" rel="nofollow noreferrer">alt text http://img372.imageshack.us/img372/8471/functionsqv0.png</a></p> <p>This picture shows the following: (c (a) (b))<br> Where parameters of c() are named as d and e. On C it would be </p> <pre><code>void c( someType1 d, someType2 e ); someType1 a( void ); someType2 b( void ); .... c( a(), b() ); </code></pre> <p>So I think that I need the tool for manipulation and visual representation of s-expressions like these: </p> <pre><code>(a (b c d) e) </code></pre> <p>or </p> <pre><code>f(g(z(x,y))+5) </code></pre> <p>It is not about linked lists, it is about logical connections between functions.<br> The tool has only to generate the textual representation from graphical one.<br> Well, I've found a lot of stuff on the Wiki page about the "Visual programming" and "Graphical programming" and so on. Mostly all described tools are cool, but somewhat complicated. And the list is pretty long, so it would take a lot of time to test all of them. So I need an opinion of real, alive people.</p> <p>Requirements are:</p> <ul> <li>Free</li> <li>Simple</li> <li>Can export to at least one real language like XML or C++ or LISP or any other.</li> </ul> <p>And it would be really good if this tool were configurable.</p> <p>I like the FlowDesigner tool: it seems to be almost the thing I need, but it cannot export to any language... Alas.</p> <p><strong>UPD</strong>: The wiki page I mentioned: <a href="http://en.wikipedia.org/wiki/Graphical_programming" rel="nofollow noreferrer">Graphical Programming</a><br> <strong>UPD2</strong>: well, I decided to write my own tool...</p>
[ { "answer_id": 340694, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\n/* there are 8 blocks */\nint running;\n/* there are 1 out blocks */\nint state_curr_1;\nint state_next_1;\n\nint main(int argc, char *argv[]) {\n running = 1;\n state_curr_1 = 0;\n while (running) {\n state_next_1 = (state_curr_1 + 19);\n running = (state_curr_1 != (19 * 12));\n state_curr_1 = state_next_1;\n printf(\"out = %d\\n\", state_curr_1);\n }\n return 0;\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20514/" ]
334,698
<p>Is it possible to create a MySQL select statement that uses an expression as x then checks if the value for x is under a certain amount?</p> <pre><code>SELECT (mytable.field1 + 10) AS x FROM `mytable` WHERE x &lt; 50; </code></pre>
[ { "answer_id": 334704, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 4, "selected": true, "text": "SELECT (mytable.field1 + 10) AS x FROM `mytable` WHERE (mytable.field1 + 10) < 50;\n" }, { "answer_id": 334715, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "SELECT *\nFROM (\n SELECT (mytable.field1 + 10) AS X\n FROM `MyTable`\n) t\nWHERE X < 50\n" }, { "answer_id": 336371, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "$x_sql = '(mytable.field1 + 10)';\n$SQL = \"SELECT $x_sql AS x FROM mytable WHERE $x_sql < 50\";\n SELECT (mytable.field1 + 10) as x FROM mytable HAVING x < 50;\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
334,702
<p>I'm trying to get an object element from my webpage using getElementById (ultimately so I can replace it with a dynamically created object element) but it is returning <code>null</code> in IE6.</p> <p>In the following code, the <code>byId()</code> function returns <code>null</code> in IE but an <code>[object HTMLObjectElement]</code> in Firefox 3 and the <code>lengthOfByTagName()</code> function returns <code>0</code> in IE but <code>1</code> in Firefox.</p> <p>Is there something I am doing wrong?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;IE doesn't see Object element?&lt;/title&gt; &lt;script type="text/javascript"&gt; function byId() { var video = document.getElementById("VideoPlayer"); alert(video); } function lengthOfByTagName() { var length = document.getElementsByTagName("object").length; alert(length); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;object type="" id="VideoPlayer"&gt; &lt;param name="allowScriptAcess" value="always" /&gt; &lt;param name="allowfullscreen" value="true" /&gt; VideoPlayer element &lt;/object&gt; &lt;br&gt; &lt;br&gt; &lt;a href="#" onclick="javascript:byId()"&gt;getElementById("VideoPlayer")&lt;/a&gt; &lt;br&gt; &lt;a href="#" onclick="javascript:lengthOfByTagName()"&gt;getElementsByTagName("object").length&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 334790, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 2, "selected": false, "text": "<object> <object type=\"\" id=\"VideoPlayer\">\n <param name=\"allowScriptAcess\" value=\"always\" />\n <param name=\"allowfullscreen\" value=\"true\" />\n</object>\n" }, { "answer_id": 28982545, "author": "HTML5 developer", "author_id": 4656706, "author_profile": "https://Stackoverflow.com/users/4656706", "pm_score": 0, "selected": false, "text": "jQuery\n\nvar video = $(\"#VideoPlayer\");\n\nalert(video);\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40443/" ]
334,705
<p>I'm trying to create a css reset that targets only my control. So the HTML will look something like this:</p> <pre><code>&lt;body&gt; &lt;img class="outterImg" src="sadkitty.gif" /&gt; &lt;div id="container" class="container"&gt; &lt;img class="innerImg" src="sadkitty.gif" /&gt; &lt;div class="subContainer"&gt; &lt;img class="innerImg" src="sadkitty.gif" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;img class="outterImg" src="sadkitty.gif" /&gt; &lt;/body&gt; </code></pre> <p>The CSS is what I'm having trouble with, but I'm currently working with this:</p> <pre><code>img { // Bad style declarations for the entire page border: solid 3px red; width: 50px; } .container img, .container div, .container etc. { // Style reset for specific elements within my control "container" border: solid 3px blue; width: 100px; } .innerImg img { // The target style for the specific class/element within the control border: solid 3px green; width: 200px; } </code></pre> <p>The problem is that ".innerImg img" does not override ".container img" as I would expect. So, what would be the best method for resetting the style of all elements within the "container" element, and then placing styles on classes within that element?</p>
[ { "answer_id": 334763, "author": "Joel Meador", "author_id": 1976, "author_profile": "https://Stackoverflow.com/users/1976", "pm_score": 0, "selected": false, "text": "img \n{ \n border: solid 3px red; \n width: 50px; \n} \n.container .innerImg, .container div \n{ \n border: solid 3px blue; \n width: 100px; \n} \n.container .subContainer \n{ \n border: none; \n} \n.subContainer .innerImg \n{ \n border: solid 3px green; \n width: 200px; \n}\n" }, { "answer_id": 334777, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 3, "selected": true, "text": ".innerImg img img.innerImg" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7423/" ]
334,708
<p>I know that codeIgniter turns off GET parameters by default. </p> <p>But by having everything done in POST, don't you get annoyed by the re-send data requests if ever you press back after a form submission?</p> <p>It annoys me, but I'm not sure if I want to allow GET purely for this reason.</p> <p>Is it such a big security issue to allow GET parameters too?</p>
[ { "answer_id": 334787, "author": "Jelani Harris", "author_id": 42538, "author_profile": "https://Stackoverflow.com/users/42538", "pm_score": 7, "selected": true, "text": "parse_str($_SERVER['QUERY_STRING'], $_GET); \n" }, { "answer_id": 1250535, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "curl -X POST -d \"param=value&param2=value\" http://example.com/form.cgi\n" }, { "answer_id": 3112890, "author": "Benjamin Sussman", "author_id": 150031, "author_profile": "https://Stackoverflow.com/users/150031", "pm_score": 3, "selected": false, "text": "parse_str($_SERVER['QUERY_STRING'],$_GET); $config['uri_protocol'] = \"PATH_INFO\";" }, { "answer_id": 3379244, "author": "Brian Temecula", "author_id": 407590, "author_profile": "https://Stackoverflow.com/users/407590", "pm_score": 1, "selected": false, "text": "<?php\n// this class extension allows for $_GET access\nclass MY_Input extends CI_input {\n\n function _sanitize_globals()\n {\n // setting allow_get_array to true is the only real modification\n $this->allow_get_array = TRUE;\n\n parent::_sanitize_globals();\n }\n\n}\n/* End of file MY_Input.php */\n/* Location: .application/libraries/MY_Input.php */\n <?php\n/*\n | this class extension allows for $_GET access by retaining the\n | standard functionality of allowing query strings to build the \n | URI String, but checks if enable_query_strings is TRUE\n*/\nclass MY_URI extends CI_URI{\n\n function _fetch_uri_string()\n {\n if (strtoupper($this->config->item('uri_protocol')) == 'AUTO')\n {\n // If the URL has a question mark then it's simplest to just\n // build the URI string from the zero index of the $_GET array.\n // This avoids having to deal with $_SERVER variables, which\n // can be unreliable in some environments\n //\n // *** THE ONLY MODIFICATION (EXTENSION) TO THIS METHOD IS TO CHECK \n // IF enable_query_strings IS TRUE IN THE LINE BELOW ***\n if ($this->config->item('enable_query_strings') === TRUE && is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '')\n {\n $this->uri_string = key($_GET);\n return;\n }\n\n // Is there a PATH_INFO variable?\n // Note: some servers seem to have trouble with getenv() so we'll test it two ways\n $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');\n if (trim($path, '/') != '' && $path != \"/\".SELF)\n {\n $this->uri_string = $path;\n return;\n }\n\n // No PATH_INFO?... What about QUERY_STRING?\n $path = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');\n if (trim($path, '/') != '')\n {\n $this->uri_string = $path;\n return;\n }\n\n // No QUERY_STRING?... Maybe the ORIG_PATH_INFO variable exists?\n $path = str_replace($_SERVER['SCRIPT_NAME'], '', (isset($_SERVER['ORIG_PATH_INFO'])) ? $_SERVER['ORIG_PATH_INFO'] : @getenv('ORIG_PATH_INFO'));\n if (trim($path, '/') != '' && $path != \"/\".SELF)\n {\n // remove path and script information so we have good URI data\n $this->uri_string = $path;\n return;\n }\n\n // We've exhausted all our options...\n $this->uri_string = '';\n }\n else\n {\n $uri = strtoupper($this->config->item('uri_protocol'));\n\n if ($uri == 'REQUEST_URI')\n {\n $this->uri_string = $this->_parse_request_uri();\n return;\n }\n\n $this->uri_string = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);\n }\n\n // If the URI contains only a slash we'll kill it\n if ($this->uri_string == '/')\n {\n $this->uri_string = '';\n }\n }\n\n}\n/* End of file MY_URI.php */\n/* Location: .application/libraries/MY_URI.php */\n" }, { "answer_id": 3978300, "author": "Roberto Gerola", "author_id": 481738, "author_profile": "https://Stackoverflow.com/users/481738", "pm_score": 4, "selected": false, "text": "<?php\n$url = parse_url($_SERVER['REQUEST_URI']);\nparse_str($url['query'], $params);\n?>\n $params" }, { "answer_id": 8289316, "author": "Tomas", "author_id": 863085, "author_profile": "https://Stackoverflow.com/users/863085", "pm_score": 2, "selected": false, "text": "$config['enable_query_strings'] = TRUE;\n" }, { "answer_id": 11765603, "author": "almix", "author_id": 1265899, "author_profile": "https://Stackoverflow.com/users/1265899", "pm_score": 3, "selected": false, "text": " //By default CodeIgniter enables access to the $_GET array. If for some\n //reason you would like to disable it, set 'allow_get_array' to FALSE.\n\n$config['allow_get_array'] = TRUE; \n" }, { "answer_id": 13303577, "author": "Sumit", "author_id": 1752372, "author_profile": "https://Stackoverflow.com/users/1752372", "pm_score": 3, "selected": false, "text": "$this->input->get('param_name');" }, { "answer_id": 17491202, "author": "Murtaza Baig", "author_id": 1697315, "author_profile": "https://Stackoverflow.com/users/1697315", "pm_score": 4, "selected": false, "text": "$this->input->get()\n" }, { "answer_id": 26124948, "author": "Inspire Shahin", "author_id": 3474982, "author_profile": "https://Stackoverflow.com/users/3474982", "pm_score": 0, "selected": false, "text": "$this->uri->segment('');\n" }, { "answer_id": 30570440, "author": "Md.Jewel Mia", "author_id": 4148384, "author_profile": "https://Stackoverflow.com/users/4148384", "pm_score": 3, "selected": false, "text": "$this->uri->segment('3');\n $this->uri->segment('4');\n" }, { "answer_id": 37398606, "author": "Ks Sjkjs", "author_id": 5346399, "author_profile": "https://Stackoverflow.com/users/5346399", "pm_score": 2, "selected": false, "text": "$this->uid = $this->input->get('uid', TRUE);\n echo $this->uid;\n" }, { "answer_id": 56626458, "author": "JD_bravo", "author_id": 3689967, "author_profile": "https://Stackoverflow.com/users/3689967", "pm_score": 0, "selected": false, "text": "//Search Form\n$(document).ready (function($){\n $(\"#searchbtn\").click(function showAlert(e){\n e.preventDefault();\n var cat = $('#category').val();\n var srch = $('#srch').val();\n\n if(srch==\"\"){\n alert(\"Search is empty :(\");\n }\n else{\n var url = baseurl+'categories/search/'+cat+'/'+srch; \n window.location.href=url;\n }\n });\n});\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42106/" ]
334,748
<p>If I give the input from Text Box like</p> <blockquote> <p>AaBbcdCDEb</p> </blockquote> <p>the output should be</p> <blockquote> <p>ABCDE or abcde</p> </blockquote> <p>only unique characters should be there, no repeated characters.</p> <p>How do I do this?</p>
[ { "answer_id": 334761, "author": "joegtp", "author_id": 39431, "author_profile": "https://Stackoverflow.com/users/39431", "pm_score": 2, "selected": false, "text": "new string(\"AaBbcdCDEb\".ToLower().Distinct().ToArray());\n" }, { "answer_id": 334986, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 1, "selected": false, "text": "string input = \"AABBCCDD\";\nstring output = string.empty; \nforeach(char c in input)\n if (!output.Contains(c))\n output += c;\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/334748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42532/" ]