source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
101,294
I am toying with the idea of creating an completely new operating system and would like to hear what everyone on this forums take is on that? First is it too late are the big boys so entrenched in our lives that we will never be able to switch (wow - what a terrible thought...). But if this is not the case, what should a operating system do for you? What features are the most important? Should all the components be separate installations (in other words - should the base OS really have no user functionality and that gets added on by creating "plug-ins" kind of like a good flexible tool?) Why do I want to do this... I am more curious about whether there is a demand and I am wondering, since the OSes we use most today (Linux, Windows, Mac OS X (Free BSD)) were actually written more than 20 years ago (and I am being generous - I mean dual and quad cores did not exist back then, buses were much slower, hardware was much more expensive, etc,...), I was just curious with the new technology if we would do anything differently? I am anxious to read your comments.
To answer the first question: It's never too late. Especially when it comes to niche market segments and stuff like that. Second though, before you start down the path of creating a new OS, you should understand the kind of undertaking it is: it'd be a massive project. Is it just a normal programmer "scratch the itch" kind of project? If so, then by all means go ahead -- you might learn alot of things by doing it. But if you're doing it for the resulting product, then you shouldn't start down that path until you've looked at all the current OSes under development (there are alot more than you'd think at first) and figured out what you'd like to change in them. Quite possibly the effort would be better spent improving/changing an existing open source system. Even for your own experimentation, it may be easier to get the results you want if you start out with something already in development.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6788/" ] }
101,301
For IronPython there is a project - IronClad , that aims to transparently run C extensions in it. Is there a similiar project for Jython?
To answer the first question: It's never too late. Especially when it comes to niche market segments and stuff like that. Second though, before you start down the path of creating a new OS, you should understand the kind of undertaking it is: it'd be a massive project. Is it just a normal programmer "scratch the itch" kind of project? If so, then by all means go ahead -- you might learn alot of things by doing it. But if you're doing it for the resulting product, then you shouldn't start down that path until you've looked at all the current OSes under development (there are alot more than you'd think at first) and figured out what you'd like to change in them. Quite possibly the effort would be better spent improving/changing an existing open source system. Even for your own experimentation, it may be easier to get the results you want if you start out with something already in development.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439/" ] }
101,329
In particular, wouldn't there have to be some kind of function pointer in place anyway?
Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter. struct A { void foo (); void bar () const;}; is basically the same as: struct A {};void foo (A * this);void bar (A const * this); The vtable is needed so that we call the right function for our specific object instance. For example, if we have: struct A { virtual void foo ();}; The implementation of 'foo' might approximate to something like: void foo (A * this) { void (*realFoo)(A *) = lookupVtable (this->vtable, "foo"); (realFoo)(this); // Make the call to the most derived version of 'foo'}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
101,337
As the title says: What is the difference between a non-secure random number generator and a secure random number generator?
No computationally feasible algorithm should: recover the seed, or predict the "next bit" for a secure random number generator. Example: a linear feedback shift register produces lots of random numbers out there, but given enough output, the seed can be discovered and all subsequent numbers predicted.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12178/" ] }
101,362
How do you generate passwords? Random Characters? Passphrases? High Ascii? Something like this? cat /dev/urandom | strings
Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/101362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18769/" ] }
101,363
I'm using Castle Windsor for dependency injection in my test project. I'm trying to create an instance one of my 'Repository' classes. "It works fine on my machine", but when I run a nightly build in TFS, my tests are not able to load said classes. private static readonly WindsorContainer _container = new WindsorContainer(new XmlInterpreter()); public void MyTestInitialize() { var testRepository = (IBogusRepository)_container[typeof(IBogusRepository)]; } xml configuration: <castle> <components> <component id="primaryBogusRepository" type="Example2008.Repository.LALALALALA, Example2008.Repository" service="Example2008.Domain.Repository.IBogusRepository, Example2008.Domain" /> <component id="primaryProductRepository" type="Example2008.Repository.ProductRepository, Example2008.Repository" service="Example2008.Domain.Repository.IProductRepository, Example2008.Domain" /> </components> </castle> When I queue a new build it producesthe following message: Unable to create instance of class Example2008.Test.ActiveProductRepositoryTest. Error: System.Configuration.ConfigurationException: The type name Example2008.Repository.LALALALALA, Example2008.Repository could not be located. Castle.Windsor.Installer.DefaultComponentInstaller.ObtainType(String typeName) Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[] configurations, IWindsorContainer container) Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer container, IConfigurationStore store) Castle.Windsor.WindsorContainer.RunInstaller() Castle.Windsor.WindsorContainer..ctor(IConfigurationInterpreter interpreter) Example2008.Test.ActiveProductRepositoryTest..cctor() in d:\Code_Temp\Example Project Nightly\Sources\Example2008.Test\ProductRepositoryTest.cs: line 19 From this message, it seems that my configuration is correct (it can see that I want to instantiate the concrete class 'LALALALALA', so the xml configuration has obviously been red correctly) I think I have my dependencies set up correctly as well (because it works locally, even if I clean the solution and rebuild). Any thoughts? (using VS2008, TFS 2008.Net 3.5, Castle 1.03, by the way)
Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/101363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12756/" ] }
101,386
Does PHP have a method of having auto-generated class variables? I think I've seen something like this before but I'm not certain. public class TestClass { private $data = array(); public function TestClass() { $this->data['firstValue'] = "cheese"; }} The $this->data array is always an associative array but they keys change from class to class. Is there any viable way to access $this->data['firstValue'] from $this->firstValue without having to define the link? And if it is, are there any downsides to it? Or is there a static method of defining the link in a way which won't explode if the $this->data array doesn't contain that key?
See here: http://www.php.net/manual/en/language.oop5.overloading.php What you want is the "__get" method. There is an example for what you need on the link.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ] }
101,439
What is the most efficient way given to raise an integer to the power of another integer in C? // 2^3pow(2,3) == 8// 5^5pow(5,5) == 3125
Exponentiation by squaring. int ipow(int base, int exp){ int result = 1; for (;;) { if (exp & 1) result *= base; exp >>= 1; if (!exp) break; base *= base; } return result;} This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/101439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ] }
101,449
I'm guessing I need to implement an NVelocityViewEngine and NVelocityView - but before I do I wanted to check to see if anyone has already done this. I can't see anything in the trunk for MVCContrib . I've already seen the post below - I'm looking specifically for something which works with Preview 5: Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity) Otherwise I'll start writing one :)
Exponentiation by squaring. int ipow(int base, int exp){ int result = 1; for (;;) { if (exp & 1) result *= base; exp >>= 1; if (!exp) break; base *= base; } return result;} This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/101449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8542/" ] }
101,461
Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as 96 . Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as 0140 . Hexadecimal based numbers are usually prefixed by 0x : 96 would be written as 0x60 . The question is: can I write numbers as binary literals in Ruby? How?
use 0b prefix >> 0b100=> 4
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/101461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17801/" ] }
101,532
When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working. So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch.
There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if they plan on creating a workaround. The only solution as it stands is to put try/catch in logical places and make sure you are listening to the ERROR (or FAULT for webservices) event for anything that dispatches them. Edit: Furthermore, it's actually impossible to catch an error thrown from an event handler. I have logged a bug on the Adobe Bug System. Update 2010-01-12: Global error handling is now supported in Flash 10.1 and AIR 2.0 (both in beta), and is achieved by subscribing the UNCAUGHT_ERROR event of LoaderInfo.uncaughtErrorEvents . The following code is taken from the code sample on livedocs : public class UncaughtErrorEventExample extends Sprite{ public function UncaughtErrorEventExample() { loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); } private function uncaughtErrorHandler(event:UncaughtErrorEvent):void { if (event.error is Error) { var error:Error = event.error as Error; // do something with the error } else if (event.error is ErrorEvent) { var errorEvent:ErrorEvent = event.error as ErrorEvent; // do something with the error } else { // a non-Error, non-ErrorEvent type was thrown and uncaught } }
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/101532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7524/" ] }
101,533
I have created a C# class file by using a XSD-file as an input. One of my properties look like this: private System.DateTime timeField; [System.Xml.Serialization.XmlElementAttribute(DataType="time")] public System.DateTime Time { get { return this.timeField; } set { this.timeField = value; } } When serialized, the contents of the file now looks like this: <Time>14:04:02.1661975+02:00</Time> Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this? <Time>14:04:02</Time> Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized? It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method. The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.
You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257/" ] }
101,536
I am looking for a drop-down JavaScript menu. It should be the simplest and most elegant accessible menu that works in IE6 and Firefox 2 also.It would be fine if it worked on an unnumbered list ( ul ) so the user can use the page without JavaScript support. Which one do you recommend and where can I find the code to such a menu?
I think the jquery superfish menu is fantastic and easy to use: http://users.tpg.com.au/j_birch/plugins/superfish/ Javascript is not required , and it is based on simple valid ul unorder lists.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18631/" ] }
101,574
I want a list of hyperlinks on a basic html page, which point to files on our corporate intranet. When a user clicks the link, I want the file to open.They are excel spreadsheets, and this is an intranet environment, so I can count on everyone having Excel installed. I've tried two things: The obvious and simple thing: <a href="file://server/directory/file.xlsx">Click me!</a> A vbscript option that I found in a Google search: <HTML><HEAD> <SCRIPT LANGUAGE=VBScript> Dim objExcel Sub Btn1_onclick() call OpenWorkbook("\\server\directory\file.xlsx") End Sub Sub OpenWorkbook(strLocation) Set objExcel = CreateObject("Excel.Application") objExcel.Visible = true objExcel.Workbooks.Open strLocation objExcel.UserControl = true End Sub </SCRIPT> <TITLE>Launch Excel</Title></HEAD><BODY> <INPUT TYPE=BUTTON NAME=Btn1 VALUE="Open Excel File"></BODY></HTML> I know this is a very basic question, but I would appreciate any help I can get. Edit: Any suggestions that work in both IE and Firefox?
Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) : <a href="file://///SERVER/directory/file.ext">file.ext</a>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ] }
101,579
I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer. I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file. Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are: Is my presumption correct? Is there a real reason to use a servlet over a JSP? What are those reasons?
A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them. However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete. If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12361/" ] }
101,647
How do you schedule a task in Windows XP to run when you shutdown windows. Such that I want to run a simple command line program I wrote in c# everytime I shut down windows. There doesn't seem to be an option in scheduled tasks to perform this task when my computer shuts down.
Execute gpedit.msc (local Policies) Computer Configuration -> Windows settings -> Scripts -> Shutdown -> Properties -> Add
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/101647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204/" ] }
101,664
Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a using block, or omit the proper Dispose call in a finally block?
Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly passed), the tool should analyse if Dispose is not called within, or that object is not stored somewhere for later disposal. That said, naive implementation of checking if disposable object is in fact disposed with "using" construct or in any other way would yield too much false positives, and render analysis useless.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ] }
101,693
I get an error everytime I upload my webapp to the provider. Because of the customErrors mode, all I see is the default "Runtime error" message, instructing me to turn off customErrors to view more about the error. Exasperated, I've set my web.config to look like this: <?xml version="1.0"?><configuration> <system.web> <customErrors mode="Off"/> </system.web></configuration> And still, all I get is the stupid remote errors page with no useful info on it.What else can I do to turn customErrors OFF ?!
This has been driving me insane for the past few days and couldn't get around it but have finally figured it out: In my machine.config file I had an entry under <system.web> : <deployment retail="true" /> This seems to override any other customError settings that you have specified in a web.config file, so setting the above entry to: <deployment retail="false" /> now means that I can once again see the detailed error messages that I need to. The machine.config is located at 32-bit %windir%\Microsoft.NET\Framework\[version]\config\machine.config 64-bit %windir%\Microsoft.NET\Framework64\[version]\config\machine.config Hope that helps someone out there and saves a few hours of hair-pulling.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/101693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ] }
101,742
I have a Google App Engine app - http://mylovelyapp.appspot.com/ It has a page - mylovelypage For the moment, the page just does self.response.out.write('OK') If I run the following Python at my computer: import urllib2f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage")s = f.read()print sf.close() it prints "OK" the problem is if I add login:required to this page in the app's yaml then this prints out the HTML of the Google Accounts login page I've tried "normal" authentication approaches. e.g. passman = urllib2.HTTPPasswordMgrWithDefaultRealm()auth_handler = urllib2.HTTPBasicAuthHandler()auth_handler.add_password(None, uri='http://mylovelyapp.appspot.com/mylovelypage', user='[email protected]', passwd='billybobspasswd')opener = urllib2.build_opener(auth_handler)urllib2.install_opener(opener) But it makes no difference - I still get the login page's HTML back. I've tried Google's ClientLogin auth API , but I can't get it to work. h = httplib2.Http()auth_uri = 'https://www.google.com/accounts/ClientLogin'headers = {'Content-Type': 'application/x-www-form-urlencoded'}myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("[email protected]", "billybobspassword")response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers)if response['status'] == '200': authtok = re.search('Auth=(\S*)', content).group(1) headers = {} headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip() headers['Content-Length'] = '0' response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage", 'POST', body="", headers=headers) while response['status'] == "302": response, content = h.request(response['location'], 'POST', body="", headers=headers) print content I do seem to be able to get some token correctly, but attempts to use it in the header when I call 'mylovelypage' still just return me the login page's HTML. :-( Can anyone help, please? Could I use the GData client library to do this sort of thing? Fromwhat I've read, I think it should be able to access App Engine apps,but I haven't been any more successful at getting the authentication working for App Engine stuff there either Any pointers to samples, articles, or even just keywords I should besearching for to get me started, would be very much appreciated. Thanks!
appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine_rpc.py. In a nutshell, the solution is: Use the Google ClientLogin API to obtain an authentication token. appengine_rpc.py does this in _GetAuthToken Send the auth token to a special URL on your App Engine app. That page then returns a cookie and a 302 redirect. Ignore the redirect and store the cookie. appcfg.py does this in _GetAuthCookie Use the returned cookie in all future requests. You may also want to look at _Authenticate , to see how appcfg handles the various return codes from ClientLogin, and _GetOpener , to see how appcfg creates a urllib2 OpenerDirector that doesn't follow HTTP redirects. Or you could, in fact, just use the AbstractRpcServer and HttpRpcServer classes wholesale, since they do pretty much everything you need.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477/" ] }
101,745
I've got 2 monitors, and most of the time I've got some reference material open on one screen, and Visual Studio on the other. To really get in the zone, though, I need my code to be the only thing I see. Does anyone know if it's possible to have multiple code windows in Visual Studio? So far the best I can do is put debugger output and the solution explorer on my left monitor, and the rest of VS on the right. I would love to have code on both windows, however.
If you right click on the file tabs, there's an option for "New Vertical Tab group" Just maximize across both monitors and put the divider on the monitor divide and I think that's what you're after.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12624/" ] }
101,752
I used git pull and had a merge conflict: unmerged: some_file.txtYou are in the middle of a conflicted merge. How do I abandon my changes to the file and keep only the pulled changes?
Since your pull was unsuccessful then HEAD (not HEAD^ ) is the last "valid" commit on your branch: git reset --hard HEAD The other piece you want is to let their changes over-ride your changes. Older versions of git allowed you to use the "theirs" merge strategy: git pull --strategy=theirs remote_branch But this has since been removed, as explained in this message by Junio Hamano (the Git maintainer). As noted in the link , instead you would do this: git fetch origingit reset --hard origin
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/101752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ] }
101,754
We are working on an S60 version and this platform has a nice Python API.. However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together??
One way is to use Kivy : Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms. Kivy Showcase app
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/101754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ] }
101,779
I am using Microsoft Access 2007 to move and massage some data between two SQL Servers. Yesterday everything was working correctly, I was able to run queries, update data, and delete data. Today I opened up the Access database to finish my data migration and am now receiving the following message when I try to run some update queries: The action or event has been blocked by Disabled Mode. Any ideas what this is talking about?
Try and see if this works: Click on 'External Data' tab There should be a Security Warning that states "Certain content in the database has been disabled" Click the 'Options' button Select 'Enable this content' and click the OK button
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ] }
101,786
What are the best continuous integration frameworks/projects for Perl and why?
The only one I've seen in action is Smolder (it is used for parrot ). It is TAP based and therefore integrates well with standard perl testing structures. See also this presentation .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ] }
101,806
I am working on an application that installs a system wide keyboardhook. I do not want to install this hook when I am running a debugbuild from inside the visual studio (or else it would hang the studioand eventually the system), and I can avoid this by checking if theDEBUG symbol is defined. However, when I debug the release version of the application, isthere a way to detect that it has been started from inside visualstudio to avoid the same problem? It is very annoying to have torestart the studio/the computer, just because I had been working onthe release build, and want to fix some bugs using the debugger havingforgotten to switch back to the debug build. Currently I use something like this to check for this scenario: System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();string moduleName = currentProcess.MainModule.ModuleName;bool launchedFromStudio = moduleName.Contains(".vshost"); I would call this the "brute force way", which works in my setting, but I would like to know whether there's another (better) way of detecting this scenario.
Try: System.Diagnostics.Debugger.IsAttached
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/101806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17378/" ] }
101,834
I've worked on a variety of systems as a programmer, some with Oracle, some with MySQL. I keep hearing people say that Oracle is more stable, more robust, and more secure. Is this the case? If so in what ways and why? For the purposes of this question, consider a small-medium sized production DB, perhaps 500,000 records or so.
Yes. Oracle is enterprise grade software. I'm not sure if its really any more stable that mysql, I haven't used mysql that much, but I dont ever remember having mysql crash on me. I've had oracle crash, but when it does, it gives me more information about why it crashed than I could possibly want, and Oracle support is always there to help ( for a fee ). Its very very robust, Oracle DB will do virtually everything it can before breaking your data, I've had mysql servers do really weird things when they run out of disk space, Oracle will just halt all transactions, and eventually shutdown if it can't write the files it needs. I've never lost data in oracle, even when I do stupid things like forget the where clause and update every row rather than a single row, its very easy to get the database back to how it was before screwing up. Not sure about security, certainly Oracle gives you lots of options for how you are going to connect to the DB and authenticate. It gives lots of options regarding which users have access to what, etc. But as with most things, if you want to take security seriously, then you need an expert to do it. Oracle certainly has a lot more to lose if they don't get security right. But, as with all things there has been exploits. If nothing else, just consider this... When Oracle stuffs up, they have customers who are paying $40k per CPU (if they are suckers and pay list price) license + yearly maintenance fees.. This gives them a very strong intensive to make sure the customers are happy with the product. For a small database, I'd seriously recommend Oracle XE well before mysql. It has the important features of mysql (Free), its dead easy to install, comes with a nice web interface and application framework (Application Express), if you DB will happy run on a single cpu, 1gb ram and 4gb data, then XE is the way to go IMHO. Mysql has its uses, many many people have shown that you can build great things with it, but its far behind oracle (and SQL Server, and DB2) in terms of features... But then, its also free and very easy to learn, which for many people is the most important feature.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153/" ] }
101,850
Take this code: <?phpif (isset($_POST['action']) && !empty($_POST['action'])) { $action = $_POST['action'];}if ($action) { echo $action;}else { echo 'No variable';}?> And then access the file with ?action=testIs there any way of preventing $action from automatically being declared by the GET? Other than of course adding && !isset($_GET['action']) Why would I want the variable to be declared for me?
Check your php.ini for the register_globals setting. It is probably on, you want it off. Why would I want the variable to be declared for me? You don't. It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global (PHP manual) . These are a handful of reserved variables in PHP.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ] }
101,868
Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.
Just use ActiveRecord and a simple Rakefile. For example, if you put your migrations in a db/migrate directory and have a database.yml file that has your db config, this simple Rakefile should work: Rakefile: require 'active_record'require 'yaml'desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x"task :migrate => :environment do ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)endtask :environment do ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml'))) ActiveRecord::Base.logger = Logger.new(STDOUT)end database.yml : adapter: mysqlencoding: utf8database: test_databaseusername: rootpassword:host: localhost Afterwards, you'll be able to run rake migrate and have all the migration goodness without a surrounding rails app. Alternatively, I have a set of bash scripts that perform a very similar function to ActiveRecord migrations, but they only work with Oracle. I used to use them before switching to Ruby and Rails. They are somewhat complicated and I provide no support for them, but if you are interested, feel free to contact me.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ] }
101,918
I am a little curious about the cute little kaleidoscopic images associated with each user on this site.How are those generated? Possibilities are: A list of images is already there in some folder and it is chosen randomly. The image is generated whenever a user registers. In any case, I am more interested in what kind of algorithm is used to generate such images.
It's called an Identicon . If you entered and e-mail, it's a based on a hash of your e-mail address. If you didn't enter an e-mail, it's based on your IP address. Jeff posted some .NET code to generate IP based Identicons.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ] }
101,958
I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing: foo = 1;foobar = 2;bar = 3; Or this: if ( test_one ) return 1;else if ( longer_test ) return 2;else if ( shorter ) return 3;else return 4; Or this: thing foo_table[] ={ { "aaaaa", 0 }, { "aa", 1 }, // ...} The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs. I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read. What's your view on this?
I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read. Well, since making code understandable is more important than making diffs understandable, you should not be torn. IMHO lining up similar lines does greatly improve readability. Moreover, it allows easier cut-n-pasting with editors that permit vertical selection.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105/" ] }
102,009
In C++, when is it best to use the stack? When is it best to use the heap?
Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75350/" ] }
102,049
For example: me$ FOO="BAR * BAR"me$ echo $FOOBAR file1 file2 file3 file4 BAR and using the \ escape character: me$ FOO="BAR \* BAR"me$ echo $FOOBAR \* BAR I'm obviously doing something stupid. How do I get the output BAR * BAR ?
Quoting when setting $FOO is not enough. You need to quote the variable reference as well: me$ FOO="BAR * BAR"me$ echo "$FOO"BAR * BAR
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/102049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108/" ] }
102,056
"The Google" is very helpful... unless your language is called "R," in which case it spits out tons of irrelevant stuff. Anyone have any search engine tricks for "R"? There are some specialized websites, like those below, but how can you tell Google you mean "R" the language? If I'm searching for something specific, I'll use an R-specific term, like "cbind." Are there other such tricks? rweb.stat.umn.edu www.rseek.org search.r-project.org www.dangoldstein.com/search_r.html
http://rseek.org is a great search engine for R manuals, mailing lists, and various websites. It's a Google syndicated search app with specialized UI. I always use it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
102,083
Preferably free tools if possible. Also, the option of searching for multiple regular expressions and each replacing with different strings would be a bonus.
Perl. Seriously, it makes sysadmin stuff so much easier. Here's an example: perl -pi -e 's/something/somethingelse/g' *.log
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13967/" ] }
102,084
I have learned quite a bit browsing through Hidden Featuresof C# and was surprised when I couldn't find somethingsimilar for VB.NET. So what are some of its hidden or lesser known features?
The Exception When clause is largely unknown. Consider this: Public Sub Login(host as string, user as String, password as string, _ Optional bRetry as Boolean = False)Try ssh.Connect(host, user, password)Catch ex as TimeoutException When Not bRetry ''//Try again, but only once. Login(host, user, password, True)Catch ex as TimeoutException ''//Log exceptionEnd TryEnd Sub
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ] }
102,128
Sorry, I'm new to SVN and I looked around a little for this. How do you mark a major version in SVN, kind of like set up a restore point. Right now I just setup my server and added all my files- I've been intermittently committing different changes. When I have something in a stable state is there a way to mark this so I can easily revert back to it if necessary?
Sounds like you're looking for tags. Tags in the Subversion book "A tag is just a “snapshot” of a project in time"
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17614/" ] }
102,271
More information from the Perl 6 Wikipedia entry Junctions Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design. In their simplest form, junctions are created by combining a set of values with junctive operators: my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8)my $all_odd_digits = 1&3&5&7&9; # all(1, 3, 5, 7, 9) | indicates a value which is equal to either its left or right-hand arguments. & indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction. Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types: sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... }sub store_record (Record&Storable $rec) { ... }
How many days are in a given month? given( $month ){ when any(qw'1 3 5 7 8 10 12') { $day = 31 } when any(qw'4 6 9 11') { $day = 30 } when 2 { $day = 29 }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ] }
102,278
OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column). For example, if I had a list of people CREATE TABLE people ( id INTEGER PRIMARY KEY, name VARCHAR(100), active BOOLEAN, ...); That means to get a list of active people, you need to use SELECT * FROM people WHERE active=True; Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two? Curiosity striking... EDIT: I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT * FROM people it would make sense to me that those entries are in a sense "active" Thanks
You partition the table on the active flag, so that active records are in one partition, and inactive records are in the other partition. Then you create an active view for each table which automatically has the active filter on it. The database query engine automatically restricts the query to the partition that has the active records in it, which is much faster than even using an index on that flag. Here is an example of how to create a partitioned table in Oracle. Oracle doesn't have boolean column types, so I've modified your table structure for Oracle purposes. CREATE TABLE people( id NUMBER(10), name VARCHAR2(100), active NUMBER(1))PARTITION BY LIST(active)( PARTITION active_records VALUES (0) PARTITION inactive_records VALUES (1)); If you wanted to you could put each partition in different tablespaces. You can also partition your indexes as well. Incidentally, this seems a repeat of this question, as a newbie I need to ask, what's the procedure on dealing with unintended duplicates? Edit: As requested in comments, provided an example for creating a partitioned table in Oracle
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087/" ] }
102,317
I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want: Org_ID Org_Address Org_OtherDetails Employess1 132A B Road List of details Emp1, Emp2, Emp3.....
The original question was database specific, but perhaps this is a good place to include a more generic answer. It's a common question. The concept that you are describing is often referred to as 'Group Concatenation'. There's no standard solution in SQL-92 or SQL-99. So you'll need a vendor-specific solution. MySQL - Use the built-in GROUP_CONCAT function. In your example you would want something like this: select o.ID, o.Address, o.OtherDetails, GROUP_CONCAT( concat(e.firstname, ' ', e.lastname) ) as Employeesfrom employees e inner join organization o on o.org_id=e.org_idgroup by o.org_id PostgreSQL - PostgreSQL 9.0 is equally simple now that string_agg(expression, delimiter) is built-in. Here it is with 'comma-space' between elements: select o.ID, o.Address, o.OtherDetails, STRING_AGG( (e.firstname || ' ' || e.lastname), ', ' ) as Employeesfrom employees e inner join organization o on o.org_id=e.org_idgroup by o.org_id PostgreSQL before 9.0 allows you to define your own aggregate functions with CREATE AGGREGATE. Slightly more work than MySQL, but much more flexible. See this other post for more details. (Of course PostgreSQL 9.0 and later have this option as well.) Oracle - same idea using LISTAGG . MS SQL Server - same idea using STRING_AGG Fallback solution - in other database technologies or in very very old versions of the technologies listed above you don't have these group concatenation functions. In that case create a stored procedure that takes the org_id as its input and outputs the concatenated employee names. Then use this stored procedure in your query. Some of the other responses here include some details about how to write stored procedures like these. select o.ID, o.Address, o.OtherDetails, MY_CUSTOM_GROUP_CONCAT_PROCEDURE( o.ID ) as Employeesfrom organization o
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
102,343
I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this: <asp:Button ID="btnShowDetails" runat="server" CausesValidation="false" CommandName="Details" Text="Order Details" onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>', '','scrollbars=yes,resizable=yes, width=350, height=550');" Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable. Any suggestions? Or is there a far better way of achieving the same result?
I believe the way to do it is onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12253/" ] }
102,384
I have looked at the ability to use tabs in Vim (with :tabe , :tabnew , etc.) as a replacement for my current practice of having many files open in the same window in hidden buffers. I would like every distinct file that I have open to always be in its own tab. However, there are some things that get in the way of this. How do I fix these: When commands like gf and ^] jump to a location in another file, the file opens in a new buffer in the current tab. Is there a way to have all of these sorts of commands open the file in a new tab, or switch to the existing tab with the file if it is already open? When switching buffers I can use :b <part of filename><tab> and it will complete the names of files in existing buffers. <part of filename> can even be the middle of a filename instead of the beginning. Is there an equivalent for switching tabs?
Stop, stop, stop. This is not how Vim's tabs are designed to be used. In fact, they're misnamed. A better name would be "viewport" or "layout", because that's what a tab is—it's a different layout of windows of all of your existing buffers. Trying to beat Vim into 1 tab == 1 buffer is an exercise in futility. Vim doesn't know or care and it will not respect it on all commands—in particular, anything that uses the quickfix buffer ( :make , :grep , and :helpgrep are the ones that spring to mind) will happily ignore tabs and there's nothing you can do to stop that. Instead: :set hidden If you don't have this set already, then do so. It makes vim work like every other multiple-file editor on the planet. You can have edited buffers that aren't visible in a window somewhere. Use :bn , :bp , :b # , :b name , and ctrl-6 to switch between buffers. I like ctrl-6 myself (alone it switches to the previously used buffer, or #ctrl-6 switches to buffer number # ). Use :ls to list buffers, or a plugin like MiniBufExpl or BufExplorer .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/102384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7706/" ] }
102,398
I am looking for a .NET implementation of a priority queue or heap data structure Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival. The basic priority queue supports three primary operations: Insert(Q,x). Given an item x with key k, insert it into the priority queue Q. Find-Minimum(Q). Return a pointer to the item whose key value is smaller than any other key in the priority queue Q. Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum Unless I am looking in the wrong place, there isn't one in the framework. Is anyone aware of a good one, or should I roll my own?
I like using the OrderedBag and OrderedSet classes in PowerCollections as priority queues.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11173/" ] }
102,457
Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information? This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.
<svg> <text id="thingyouhoverover" x="50" y="35" font-size="14">Mouse over me!</text> <text id="thepopup" x="250" y="100" font-size="30" fill="black" visibility="hidden">Change me <set attributeName="visibility" from="hidden" to="visible" begin="thingyouhoverover.mouseover" end="thingyouhoverover.mouseout"/> </text></svg> Further explanation can be found here .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846/" ] }
102,459
Since the only operations required for a container to be used in a stack are: back() push_back() pop_back() Why is the default container for it a deque instead of a vector? Don't deque reallocations give a buffer of elements before front() so that push_front() is an efficient operation? Aren't these elements wasted since they will never ever be used in the context of a stack? If there is no overhead for using a deque this way instead of a vector, why is the default for priority_queue a vector not a deque also? (priority_queue requires front(), push_back(), and pop_back() - essentially the same as for stack) Updated based on the Answers below: It appears that the way deque is usually implemented is a variable size array of fixed size arrays. This makes growing faster than a vector (which requires reallocation and copying), so for something like a stack which is all about adding and removing elements, deque is likely a better choice. priority_queue requires indexing heavily, as every removal and insertion requires you to run pop_heap() or push_heap(). This probably makes vector a better choice there since adding an element is still amortized constant anyways.
As the container grows, a reallocation for a vector requires copying all the elements into the new block of memory. Growing a deque allocates a new block and links it to the list of blocks - no copies are required. Of course you can specify that a different backing container be used if you like. So if you have a stack that you know is not going to grow much, tell it to use a vector instead of a deque if that's your preference.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ] }
102,472
When a branch is reintegrated to the trunk, is that branch effectively dead? Can you make modifications to the branch after the reintegration and merge those back into the trunk at a later date?
You can do it technically, you branch is not dead nor disabled, but it is not recommended to merge from branch to trunk after reintegration. You can find a full discussion about the reason for that, here: Subversion merge reintegrate Basically, it says, that it is possible to merge your changes again to the trunk, but since reintegration forces you to merge from trunk to branch prior to the reintegrate operation you'll be facing Reflective/Cyclic Merge which is very problematic in Subversion 1.5. According to the article, it is recommended to delete your reintegrated branch immediately after reintegration and create a new one with the same (or different) name instead. This is a known Subversion behavior which will be addressed in future version (probably in 1.6)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12969/" ] }
102,535
I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.
Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested. Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses another generator, or consumes some other resource, and it's more convenient if that happened as late as possible. Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator. For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result. If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach: big_list = list(the_generator)
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/102535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834/" ] }
102,558
What are some of the advantages of using one over the other?
The main advantages of ASP.net MVC are: Enables the full control over the rendered HTML. Provides clean separation of concerns(SoC). Enables Test Driven Development (TDD) . Easy integration with JavaScript frameworks. Following the design of stateless nature of the web. RESTful urls that enables SEO. No ViewState and PostBack events The main advantage of ASP.net Web Form are: It provides RAD development Easy development model for developers those coming from winform development.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/102558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ] }
102,567
What's the best way to shut down the computer from a C# program? I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
Works starting with windows XP, not available in win 2000 or lower: This is the quickest way to do it: Process.Start("shutdown","/s /t 0"); Otherwise use P/Invoke or WMI like others have said. Edit: how to avoid creating a window var psi = new ProcessStartInfo("shutdown","/s /t 0");psi.CreateNoWindow = true;psi.UseShellExecute = false;Process.Start(psi);
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/102567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ] }
102,568
I'm trying to understand someone else's Perl code without knowing much Perl myself. I would appreciate your help. I've encountered a Perl function along these lines: MyFunction($arg1,$arg2__size,$arg3) Is there a meaning to the double-underscore syntax in $arg2 , or is it just part of the name of the second argument?
There is no specific meaning to the use of a __ inside of a perl variable name. It's likely programmer preference, especially in the case that you've cited in your question. You can see more information about perl variable naming here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10261/" ] }
102,605
I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client's computer. Is that possible?
There's no notion of hosts or ip-addresses in the javascript standard library. So you'll have to access some external service to look up hostnames for you. I recommend hosting a cgi-bin which looks up the ip-address of a hostname and access that via javascript.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13172/" ] }
102,631
I have had thoughts of trying to write a simple crawler that might crawl and produce a list of its findings for our NPO's websites and content. Does anybody have any thoughts on how to do this? Where do you point the crawler to get started? How does it send back its findings and still keep crawling? How does it know what it finds, etc,etc.
You'll be reinventing the wheel, to be sure. But here's the basics: A list of unvisited URLs - seed this with one or more starting pages A list of visited URLs - so you don't go around in circles A set of rules for URLs you're not interested in - so you don't index the whole Internet Put these in persistent storage, so you can stop and start the crawler without losing state. Algorithm is: while(list of unvisited URLs is not empty) { take URL from list remove it from the unvisited list and add it to the visited list fetch content record whatever it is you want to about the content if content is HTML { parse out URLs from links foreach URL { if it matches your rules and it's not already in either the visited or unvisited list add it to the unvisited list } }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
102,640
So essentially does margin collapsing occur when you don't set any margin or padding or border to a given div element?
No. When you have two adjacent vertical margins, the greater of the two is used and the other is ignored. So, for instance, if you have two block-display elements, A, followed by B beneath it, and A has a bottom-margin of 3em, while B has a top-margin of 2em, then the distance between them will be 3em. If you set a border or padding, this prevents the collapsing from occurring. In the above example, the distance between the two elements will then be 5em. If you don't set any margins, then there won't be any margins to collapse. It has nothing whatsoever to do with the element type in use - it is applicable to all element types, not just <div> elements. Read the CSS 2.1 specification for more details.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ] }
102,742
Like many of you, I use ReSharper to speed up the development process. When you use it to override the equality members of a class, the code-gen it produces for GetHashCode() looks like: public override int GetHashCode() { unchecked { int result = (Key != null ? Key.GetHashCode() : 0); result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0); result = (result * 397) ^ ObjectId; return result; } } Of course I have some of my own members in there, but what I am wanting to know is why 397? EDIT: So my question would be better worded as, is there something 'special' about the 397 prime number outside of it being a prime number?
Probably because 397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. There's nothing particularly special about 397 that distinguishes it from other primes of the same magnitude.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/102742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5289/" ] }
102,829
I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
glogg could also be considered, for a different usage: Caveat (reported by Simon Tewsi in the comments , Feb. 2013) One caveat - has two search functions, Main Search and Quick Find . The lower one, which I assume is Quick Find , is at least an order of magnitude slower than the upper one, which is fast.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/102829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14728/" ] }
102,881
I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.
select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual; Give the time in 24 hour format. More options are described here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ] }
102,894
Is anyone writing applications specifically to take advantage of google chrome? Are there any enterprise users who are considering using it as the standard browser?
Yes, I have started to pay very good attention to Google Chrome for my applications. Recent analytics show that between 6%-15% of my users are accessing my applications (varies between 6 to 15 in different applications) on Chrome. And, this number looks on an upward trend. Thus, I can't really ignore it for testing right now. As far as taking it as a standard goes, thats a long way off. I still have to test for IE6! :( Though, we have been planning to start using features like Gears (inbuilt in Chrome - downloadable elsewhere) once Chrome crosses the 25% mark. Thats when I believe that we will be looking at Chrome to be our preferred browser. I hope that we have Chrome 1.0+ by then! ;)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ] }
102,902
What constitutes a good CI build-process? We use CI, but is deployment to production even a realistic CI goal when you have dependencies on several services that should be deployed too and other apps may depend on these too. Is a good good CI build process good enough when its automated to QA and manual from there?
Well "it depends" :) We use our CI system to: build & unit test deploy to single box, run intergration tests and code analisys deploy to lab environment run acceptance tests in prod-like system drop builds that pass to code drop for prod deployment This is for a greenfield project of about a dozen services and databases deployed to 20+ servers, that also had dependencies on half a dozen other 'external' services. Using a CI tool to deploy your product to a production environment as a realistic goal? again... "it depends" Why would you want to do this? if you have the process you can roll changes (and roll back) faster and more often less chance for human error you can test the same deployment strategy in a test environment before going to production and catch issues earlier Some technical things you have to address before you can answer this: what is the uptime requirements for your system -- Are you allowed to have downtime or does it need to be up 24/7? do you have change control processes in place that require human intervention/approval? is your deployment robust enough for any component to roll back to a known-good state if a deployment fails? is your system designed to handle different versions of services or clients in case one or several component deployments fails (and you have the above rollback to last known good)? does the process have the smarts to handle a partial deployment where a component cannot handle mixed versions of its dependencies/clients? how are you handing database deployment/upgrades? do you have monitoring in place so you know when something goes wrong? Here are a couple of recent related links about automation and building the tools you need . When it comes down to it the more complex your system the more difficult it is do automate everything, but that does not mean it is not a worthy goal, it just takes a lot more effort and willpower to get it done -- everything from knowing the difficulties you're going to face, the problems you have to account for (failure will happen), the political challenges of building infrastructure (vs. more product features). Now heres the big secret... the technical challenges are challenging but not impossible... the political challenges may be insurmountable. Everything about this costs money whether its dev time or buying 3rd party solutions. So really, can you build the $1K, $10K, $100K, or $1M solution? Whatever solution you go for make sure the automation is robust first, complete second... i.e. make sure you have as robust a solution as you can for getting deployment to a test environment rather than a fragile solution that deploys to production.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/102902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15555/" ] }
102,913
I have an MVC-based site, which is using a Repository/Service pattern for data access.The Services are written to be using in a majority of applications (console, winform, and web). Currently, the controllers communicate directly to the services. This has limited the ability to apply proper caching. I see my options as the following: Write a wrapper for the web app, which implements the IWhatEverService which does caching. Apply caching in each controller by cache the ViewData for each Action. Don't worry about data caching and just implement OutputCaching for each Action. I can see the pros and cons of each. What is/should the best practice be for caching with Repository/Service
The easiest way would be to handle caching in your repository provider. That way you don't have to change out any code in the rest of your app; it will be oblivious to the fact that the data was served out of a cache rather than the repository. So, I'd create an interface that the controllers use to communicate with the backend, and in the implementation of this I'd add the caching logic. Wrap it all up in a nice bow with some DI, and your app will be set for easy testing.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1296/" ] }
102,964
I have a Java bean like this: class Person { int age; String name;} I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages. The code to generate the table rows will look something like this: <c:forEach var="person" items="${personList}"> <tr><td>${person.name}<td><td>${person.age}</td></tr></c:forEach> However, I'm struggling to find a way to calculate the age total that will be shown in the final row without resorting to scriptlet code , any suggestions?
Note: I tried combining answers to make a comprehensive list. I mentioned names where appropriate to give credit where it is due. There are many ways to solve this problem, with pros/cons associated with each: Pure JSP Solution As ScArcher2 mentioned above, a very easy and simple solution to the problem is to implement it directly in the JSP as so: <c:set var="ageTotal" value="${0}" /><c:forEach var="person" items="${personList}"> <c:set var="ageTotal" value="${ageTotal + person.age}" /> <tr><td>${person.name}<td><td>${person.age}</td></tr></c:forEach>${ageTotal} The problem with this solution is that the JSP becomes confusing to the point where you might as well have introduced scriplets. If you anticipate that everyone looking at the page will be able to follow the rudimentary logic present it is a fine choice. Pure EL solution If you're already on EL 3.0 (Java EE 7 / Servlet 3.1), use new support for streams and lambdas : <c:forEach var="person" items="${personList}"> <tr><td>${person.name}<td><td>${person.age}</td></tr></c:forEach>${personList.stream().map(person -> person.age).sum()} JSP EL Functions Another way to output the total without introducing scriplet code into your JSP is to use an EL function. EL functions allow you to call a public static method in a public class. For example, if you would like to iterate over your collection and sum the values you could define a public static method called sum(List people) in a public class, perhaps called PersonUtils. In your tld file you would place the following declaration: <function> <name>sum</name> <function-class>com.example.PersonUtils</function-class> <function-signature>int sum(java.util.List people)</function-signature></function> Within your JSP you would write: <%@ taglib prefix="f" uri="/your-tld-uri"%>...<c:out value="${f:sum(personList)}"/> JSP EL Functions have a few benefits. They allow you to use existing Java methods without the need to code to a specific UI (Custom Tag Libraries). They are also compact and will not confuse a non-programming oriented person. Custom Tag Yet another option is to roll your own custom tag. This option will involve the most setup but will give you what I think you are esentially looking for, absolutly no scriptlets. A nice tutorial for using simple custom tags can be found at http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701 The steps involved include subclassing TagSupport: public PersonSumTag extends TagSupport { private List personList; public List getPersonList(){ return personList; } public void setPersonList(List personList){ this.personList = personList; } public int doStartTag() throws JspException { try { int sum = 0; for(Iterator it = personList.iterator(); it.hasNext()){ Person p = (Person)it.next(); sum+=p.getAge(); } pageContext.getOut().print(""+sum); } catch (Exception ex) { throw new JspTagException("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; }} Define the tag in a tld file: <tag> <name>personSum</name> <tag-class>example.PersonSumTag</tag-class> <body-content>empty</body-content> ... <attribute> <name>personList</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <type>java.util.List</type> </attribute> ...</tag> Declare the taglib on the top of your JSP: <%@ taglib uri="/you-taglib-uri" prefix="p" %> and use the tag: <c:forEach var="person" items="${personList}"> <tr><td>${person.name}<td><td>${person.age}</td></tr></c:forEach><p:personSum personList="${personList}"/> Display Tag As zmf mentioned earlier, you could also use the display tag, although you will need to include the appropriate libraries: http://displaytag.sourceforge.net/11/tut_basic.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/102964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ] }
103,006
I've got a CSV file containing latitude and longitude values, such as: "25°36'55.57""E","45°39'12.52""N" Anyone have a quick and simple piece of C# code to convert this to double values? Thanks
If you mean C# code to do this: result = 25 + (36 / 60) + (55.57 / 3600) First you'll need to parse the expression with Regex or some other mechanism and split it into the individual parts. Then: String hour = "25";String minute = "36";String second = "55.57";Double result = (hour) + (minute) / 60 + (second) / 3600; And of course a switch to flip sign depending on N/S or E/S. Wikipedia has a little on that: For calculations, the West/East suffix is replaced by a negative sign in the western hemisphere. Confusingly, the convention of negative for East is also sometimes seen. The preferred convention -- that East be positive -- is consistent with a right-handed Cartesian coordinate system with the North Pole up. A specific longitude may then be combined with a specific latitude (usually positive in the northern hemisphere) to give a precise position on the Earth's surface. ( http://en.wikipedia.org/wiki/Longitude )
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ] }
103,059
Anyone have any suggestions on where to start for a newbie wanting to try out some sort of source-control along with a new journey into ASP.NET? SVN, VSS, CVS...I dont even know where to start!
Lots of people here have suggested introductions and comprehensive how-tos, which are all good for telling you how to do what you want. In addition, I'd give three pieces of advice for the novice on how to know what you want: 1) Version-control EVERYTHING (that is, everything you write). Version-control the project files. Version-control your test cases. Version-control any little scripts you use to copy things around. Version-control your todo list. Definitely version control your design notes. Once you're familiar with the commands it costs nothing, and some day you'll be glad of the history of a file you'd never imagined needing to roll back. 2) When you're happy with a change, check it in immediately. And check it all in. If you work in sequential steps (and that doesn't always happen - you can get distracted - but it's good practice), then at the start of each new step you should have 0 modified files in your checkout. You may even want to check in unfinished non-working code, depending on what suits you. 3) When you reach a milestone, tag it. Even your own personal goals (inch-pebbles). If you can't be bothered with tagging, just make a note of the date and time (in, you guessed it, a version-controlled file). If a particular version is memorable for some reason ("I finished the back-end", "I sent it to someone else to look at"), you want to know exactly what was in it. And diffing against the repository diagnoses some kinds of bugs faster than the debugger.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18953/" ] }
103,167
I was reading a MS Excel help article about pivotcache and wonder what they mean by OLE DB and ODBC sources ...You should use the CommandText property instead of the SQL property, which now exists primarily for compatibility with earlier versions of Microsoft Excel. If you use both properties, the CommandText property’s value takes precedence. For OLE DB sources , the CommandType property describes the value of the CommandText property. For ODBC sources , the CommandText property functions exactly like the SQL property, and setting the property causes the data to be refreshed... I really appreciate your short answers.
According to ADO: ActiveX Data Objects , a book by Jason T. Roff, published by O'Reilly Media in 2001 (excellent diagram here), he says precisely what MOZILLA said. (directly from page 7 of that book) ODBC provides access only to relational databases OLE DB provides the following features Access to data regardless of its format or location Full access to ODBC data sources and ODBC drivers So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer. I'm not 100% sure this image is correct. The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in this diagram the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/103167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ] }
103,202
Is there a good Eclipse plugin for recording and playing back macros? I've tried this one , but it didn't do me any good- it seemed like it wasn't ready for prime time. I know about editor templates, but I'm looking for something that I can use to record my keystrokes and then apply multiple times against a wad of text. This seems like a strange hole in an IDE. Am I missing some built-in facility for this?
I put something together over the last month or so that you may find useful. It has limitations since the Eclipse editor/commands weren't designed with macro support in mind, but I think it works reasonably well. I just posted Practical Macro at SourceForge a couple of days ago. It requires Eclipse 3.4.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4276/" ] }
103,280
If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught. Today our signal handler looks as follows: void catchSignal (int reason) { std :: cerr << "Caught a signal: " << reason << std::endl; exit (1);} I can hear the screams of horror with the above, as I have read from this thread that it is evil to call a non-reentrant function from a signal handler. Is there a portable way to handle the signal and provide information to users? EDIT: Or at least portable within the POSIX framework?
This table lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler. By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick: #include <csignal>#ifdef _WINDOWS_#define _exit _Exit#else#include <unistd.h>#endif#define PRINT_SIGNAL(X) case X: \ write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \ break;void catchSignal (int reason) { char s[] = "Caught signal: ("; write (STDERR_FILENO, s, sizeof(s) - 1); switch (reason) { // These are the handlers that we catch PRINT_SIGNAL(SIGUSR1); PRINT_SIGNAL(SIGHUP); PRINT_SIGNAL(SIGINT); PRINT_SIGNAL(SIGQUIT); PRINT_SIGNAL(SIGABRT); PRINT_SIGNAL(SIGILL); PRINT_SIGNAL(SIGFPE); PRINT_SIGNAL(SIGBUS); PRINT_SIGNAL(SIGSEGV); PRINT_SIGNAL(SIGTERM); } _Exit (1); // 'exit' is not async-signal-safe} EDIT: Building on windows. After trying to build this one windows, it appears that 'STDERR_FILENO' is not defined. From the documentation however its value appears to be '2'. #include <io.h>#define STDIO_FILENO 2 EDIT: 'exit' should not be called from the signal handler either! As pointed out by fizzer , calling _Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig_atomic_t" type can be used to notify the main program that it should exit. The following I found useful in my searches. Introduction To Unix Signals Programming Extending Traditional Signals
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11698/" ] }
103,281
At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP? $mysqli = new mysqli("localhost", "root", "", "test");...do stuff, perhaps redirect to another page...$mysqli->close();
From: http://us3.php.net/manual/en/mysqli.close.php "Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ] }
103,325
Given this XML, what XPath returns all elements whose prop attribute contains Foo (the first three nodes): <bla> <a prop="Foo1"/> <a prop="Foo2"/> <a prop="3Foo"/> <a prop="Bar"/></bla>
//a[contains(@prop,'Foo')] Works if I use this XML to get results back. <bla> <a prop="Foo1">a</a> <a prop="Foo2">b</a> <a prop="3Foo">c</a> <a prop="Bar">a</a></bla> Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use /bla/a[contains(@prop,'Foo')] This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element //a[contains(@prop,'Foo')] I added this for the sake of thoroughness and in the spirit of stackoverflow. :)
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/103325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ] }
103,358
I'm still trying to decide whether my (home) project should use UTF-8 strings (implemented in terms of std::string with additional UTF-8-specific functions when necessary) or some 16-bit string (implemented as std::wstring). The project is a programming language and environment (like VB, it's a combination of both). There are a few wishes/constraints: It would be cool if it could run on limited hardware, such as computers with limited memory. I want the code to run on Windows, Mac and (if resources allow) Linux. I'll be using wxWidgets as my GUI layer, but I want the code that interacts with that toolkit confined in a corner of the codebase (I will have non-GUI executables). I would like to avoid working with two different kinds of strings when working with user-visible text and with the application's data. Currently, I'm working with std::string, with the intent of using UTF-8 manipulation functions only when necessary. It requires less memory, and seems to be the direction many applications are going anyway. If you recommend a 16-bit encoding, which one: UTF-16 ? UCS-2 ? Another one?
UTF-16 is still a variable length character encoding (there are more than 2^16 unicode codepoints), so you can't do O(1) string indexing operations. If you're doing lots of that sort of thing, you're not saving anything in speed over UTF-8. On the other hand, if your text includes a lot of codepoints in the 256-65535 range, UTF-16 can be a substantial improvement in size. UCS-2 is a variation on UTF-16 that is fixed length, at the cost of prohibiting any codepoints greater than 2^16. Without knowing more about your requirements, I would personally go for UTF-8. It's the easiest to deal with for all the reasons others have already listed.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ] }
103,395
I've got an open-source app that is hosted at code.google.com. It is cross platform ( Linux / Windows / Mac ). I uploaded the code initially from a WinXP machine using TortoiseSVN and it seems that none of the "configure" batch files that are used for the linux build have their "execute" bits set. What would be the easiest way to set these for the files that need them? Using TortoiseSVN would be easier, I suppose, but if that can't be used, then I could also use the command line SVN on my linux machine.
Here's how to do it on the command line: for file in `find . -name configure`; do svn ps svn:executable yes ${file}done Or for just one file ( configure is the filename here): svn ps svn:executable yes configure
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ] }
103,422
A lot of contact management programs do this - you type in a name ( e.g. , "John W. Smith") and it automatically breaks it up internally into: First name: John Middle name: W. Last name: Smith Likewise, it figures out things like "Mrs. Jane W. Smith" and "Dr. John Doe, Jr." correctly as well (assuming you allow for fields like "prefix" and "suffix" in names). I assume this is a fairly common things that people would want to do... so the question is... how would you do it? Is there a simple algorithm for this? Maybe a regular expression? I'm after a .NET solution, but I'm not picky. Update: I appreciate that there is no simple solution for this that covers ALL edge cases and cultures... but let's say for the sake of argument that you need the name in pieces (filling out forms - as in, say, tax or other government forms - is one case where you are bound to enter the name into fixed fields, whether you like it or not), but you don't necessarily want to force the user to enter their name into discrete fields (less typing = easier for novice users). You'd want to have the program "guess" (as best it can) on what's first, middle, last, etc. If you can, look at how Microsoft Outlook does this for contacts - it lets you type in the name, but if you need to clarify, there's an extra little window you can open. I'd do the same thing - give the user the window in case they want to enter the name in discrete pieces - but allow for entering the name in one box and doing a "best guess" that covers most common names.
If you must do this parsing, I'm sure you'll get lots of good suggestions here. My suggestion is - don't do this parsing . Instead, create your input fields so that the information is already separated out. Have separate fields for title, first name, middle initial, last name, suffix, etc.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5956/" ] }
103,423
I've always taken the approach of first deploying the database with a minimal set of indexes and then adding/changing indexes as performance dictates. This approach works reasonably well. However, it still doesn't tell me where I could improve performance. It only tells me where performance is so bad that users complain about it. Currently, I'm in the process of refactoring database objects on a lot of our applications. So should I not bother to look for performance improvements since "premature optimization is the root of all evil"? When refactoring application code, the developer is constantly looking for ways to improve the code quality. Is there a way to constantly be looking for improvements in database performance as well? If so, what tools and techniques have you found to be most helpful? I've briefly played around with the "Database engine tuning advisor" but didn't find it to be helpful at all. Maybe I just need more experience interpreting the results.
My approach is to gather commands against the server or database into a table using SQL Server Profiler. Once you have that, you can query based on the max and avg execution times, max and avg cpu times, and (also very important) the number of times that the query was run. Since I try to put all database access code in stored procedures it's easy for me to break out queries. If you use inline SQL it might be harder, since a change to a value in the query would make it look like a different query. You can try to work around this using the LIKE operator to put the same types of queries into the same buckets for calculating the aggregates (max, avg, count). Once you have a "top 10" list of potential problems you can start looking at them individually to see if either the query can be reworked, an index might help, or making a minor architecture change is in order. To come up with the top 10, try looking at the data in different ways: avg * count for total cost during the period, max for worst offender, just plain avg, etc. Finally, be sure to monitor over different time periods if necessary. The database usage might be different in the morning when everyone is getting in and running their daily reports than it is at midday when users are entering new data. You may also decide that even though some nightly process takes longer than any other query it doesn't matter since it's run during off hours. Good luck!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5458/" ] }
103,489
Below is the code I use to build an HTML table on the fly (using JSON data received from the server). I display an animated pleasewait (.gif) graphic while the data is loading. However, the graphic freezes while the JavaScript function is building the table. At first, I was just happy to make this happen (display the table), I guess now I need to work on efficiency. At the very least I need to stop the animated graphic from freezing. I can go to a static "Loading" display, but I would rather make this method work. Suggestions for my pleasewait display? And efficiency? Possibly a better way to build the table? Or maybe not a table, but some other "table" like display var t = eval( "(" + request + ")" ) ;var myTable = '' ;myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;myTable += "<thead>" ;myTable += "<tr>";for (var i = 0; i < t.hdrs.length; i++) { myTable += "<th>" + header + "</th>";}myTable += "</tr>" ;myTable += "</thead>" ;myTable += "<tbody>" ;for (var i = 0; i < t.data.length; i++) { myTable += '<tr>'; for (var j = 0; j < t.hdrs.length; j++) { myTable += '<td>'; if (t.data[i][t.hdrs[j]] == "") { myTable += "&nbsp;" ; } else { myTable += t.data[i][t.hdrs[j]] ; } myTable += "</td>"; } myTable += "</tr>";}myTable += "</tbody>" ;myTable += "</table>" ;$("#result").append(myTable) ;$("#PleaseWaitGraphic").addClass("hide");$(".rslt").removeClass("hide") ;
You basically want to set up your loops so they yield to other threads every so often. Here is some example code from this article on the topic of running CPU intensive operations without freezing your UI: function doSomething (progressFn [, additional arguments]) { // Initialize a few things here... (function () { // Do a little bit of work here... if (continuation condition) { // Inform the application of the progress progressFn(value, total); // Process next chunk setTimeout(arguments.callee, 0); } })();} As far as simplifying the production of HTML in your script, if you're using jQuery, you might give my Simple Templates plug-in a try. It tidies up the process by cutting down drastically on the number of concatenations you have to do. It performs pretty well, too after I recently did some refactoring that resulted in a pretty big speed increase . Here's an example (without doing all of the work for you!): var t = eval('(' + request + ')') ;var templates = { tr : '<tr>#{row}</tr>', th : '<th>#{header}</th>', td : '<td>#{cell}</td>'};var table = '<table><thead><tr>';$.each(t.hdrs, function (key, val) { table += $.tmpl(templates.th, {header: val});});...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ] }
103,512
I've heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?
The main reason is that classic C casts make no distinction between what we call static_cast<>() , reinterpret_cast<>() , const_cast<>() , and dynamic_cast<>() . These four things are completely different. A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A dynamic_cast<>() is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference). A reinterpret_cast<>() (or a const_cast<>() ) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a foo (this looks as if it isn't mutable), but it is". The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules. Let's assume these: class CDerivedClass : public CMyBase {...};class CMyOtherStuff {...} ;CMyBase *pSomething; // filled somewhere Now, these two are compiled the same way: CDerivedClass *pMyObject;pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checkedpMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<> // Safe; as long as we checked // but harder to read However, let's see this almost identical code: CMyOtherStuff *pOther;pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convertpOther = (CMyOtherStuff*)(pSomething); // No compiler error. // Same as reinterpret_cast<> // and it's wrong!!! As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved. The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast<" or "reinterpret_cast<". pOther = reinterpret_cast<CMyOtherStuff*>(pSomething); // No compiler error. // but the presence of a reinterpret_cast<> is // like a Siren with Red Flashing Lights in your code. // The mere typing of it should cause you to feel VERY uncomfortable. That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/103512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ] }
103,564
I am working on an application and one design approach involves extremely heavy use of the instanceof operator. While I know that OO design generally tries to avoid using instanceof , that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as == ? For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine. One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category. Is instanceof somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?
Modern JVM/JIT compilers have removed the performance hit of most of the traditionally "slow" operations, including instanceof, exception handling, reflection, etc. As Donald Knuth wrote, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." The performance of instanceof probably won't be an issue, so don't waste your time coming up with exotic workarounds until you're sure that's the problem.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/103564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204759/" ] }
103,575
I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired. Here is the Customer.cs class: public class Customer : IDataErrorInfo { public string FirstName { get; set; } public string LastName { get; set; } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { string result = null; if (columnName.Equals("FirstName")) { if (String.IsNullOrEmpty(FirstName)) { result = "FirstName cannot be null or empty"; } } else if (columnName.Equals("LastName")) { if (String.IsNullOrEmpty(LastName)) { result = "LastName cannot be null or empty"; } } return result; } } } And here is the WPF code: <TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock><TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1"> <Binding Source="{StaticResource CustomerKey}" Path="LastName" ValidatesOnExceptions="True" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus"/> </TextBox>
If you're not adverse to putting a bit of logic in your code behind, you can handle the actual LostFocus event with something like this: .xaml <TextBox LostFocus="TextBox_LostFocus" .... .xaml.cs private void TextBox_LostFocus(object sender, RoutedEventArgs e){ ((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ] }
103,576
I'm trying a very basic XPath on this xml (same as below), and it doesn't find anything.I'm trying both .NET and this website , and XPaths such as //PropertyGroup , /PropertyGroup and //MSBuildCommunityTasksPath are simply not working for me (they compiled but return zero results). Source XML: <?xml version="1.0" encoding="utf-8"?><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ --> <PropertyGroup> <MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\bin\Debug</MSBuildCommunityTasksPath> </PropertyGroup> <Import Project="$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\MSBuild.Community.Tasks.Targets" /> <Target Name="DoFxCop"> <FxCop TargetAssemblies="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll" RuleLibraries="@(FxCopRuleAssemblies)" AnalysisReportFileName="Test.html" DependencyDirectories="$(MSBuildCommunityTasksPath)" FailOnError="True" ApplyOutXsl="True" OutputXslFileName="C:\Program Files\Microsoft FxCop 1.32\Xml\FxCopReport.xsl" /> </Target></Project>
You can add namespaces in your code and all that, but you can effectively wildcard the namespace. Try the following XPath idiom. //*[local-name()='PropertyGroup']//*[local-name()='MSBuildCommunityTasksPath'] name() usually works as well, as in: //*[name()='PropertyGroup']//*[name()='MSBuildCommunityTasksPath'] EDIT: Namespaces are great and i'm not suggesting they're not important, but wildcarding them comes in handy when cobbling together prototype code, one-off desktop tools, experimenting with XSLT, and so forth. Balance your need for convenience against acceptable risk for the task at hand. FYI, if need be, you can also strip or reassign namespaces.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ] }
103,593
I have: <?php$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");if ($_POST["lastname"] <> ""){ fwrite($file,$_POST["lastname"]."\n");}fclose($file);?> but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it? To insert text without over-writing the beginning of the file , you'll have to open it for appending ( a+ rather than r+ ) $file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");if ($_POST["lastname"] <> ""){ fwrite($file,$_POST["lastname"]."\n");}fclose($file); If you're trying to write to the start of the file , you'll have to read in the file contents (see file_get_contents ) first, then write your new string followed by file contents to the output file. $old_content = file_get_contents($file);fwrite($file, $new_content."\n".$old_content); The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents . In this case, consider using rewind($file) , which sets the file position indicator for handle to the beginning of the file stream. Note when using rewind() , not to open the file with the a (or a+ ) options, as: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
103,598
Why was the arguments.callee.caller property deprecated in JavaScript? It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable. Is there a good reason to put this valuable functionality in limbo? (Or alternately, is there a better way to grab a handle on the calling function?)
Early versions of JavaScript did not allow named function expressions, and because of that we could not make a recursive function expression: // This snippet will work: function factorial(n) { return (!(n>1))? 1 : factorial(n-1)*n; } [1,2,3,4,5].map(factorial); // But this snippet will not: [1,2,3,4,5].map(function(n) { return (!(n>1))? 1 : /* what goes here? */ (n-1)*n; }); To get around this, arguments.callee was added so we could do: [1,2,3,4,5].map(function(n) { return (!(n>1))? 1 : arguments.callee(n-1)*n; }); However this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing etc, but even the best code is sub optimal due to checks that would not otherwise be necessary). The other major issue is that the recursive call will get a different this value, for example: var global = this;var sillyFunction = function (recursed) { if (!recursed) return arguments.callee(true); if (this !== global) alert("This is: " + this); else alert("This is the global");}sillyFunction(); Anyhow, EcmaScript 3 resolved these issues by allowing named function expressions, e.g.: [1,2,3,4,5].map(function factorial(n) { return (!(n>1))? 1 : factorial(n-1)*n; }); This has numerous benefits: The function can be called like any other from inside your code. It does not pollute the namespace. The value of this does not change. It's more performant (accessing the arguments object is expensive). Whoops, Just realised that in addition to everything else the question was about arguments.callee.caller , or more specifically Function.caller . At any point in time you can find the deepest caller of any function on the stack, and as I said above, looking at the call stack has one single major effect: It makes a large number of optimizations impossible, or much much more difficult. Eg. if we can't guarantee that a function f will not call an unknown function, then it is not possible to inline f . Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards, take: function f(a, b, c, d, e) { return a ? b * c : d * e; } If the js interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/103598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15992/" ] }
103,630
Is it possible to use an ASP.NET web.sitemap with a jQuery Superfish menu? If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?
I found this question while looking for the same answer... everyone says it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings... Things I needed: Superfish which also includes a version of jQuery CSS Friendly Control Adaptors download DLL and .browsers file (into /bin and /App_Browsers folders respectively) ASP.NET SiteMap (a .sitemap XML file and siteMap provider entry in web.config) My finished Masterpage.master has the following head tag: <head runat="server"> <script type="text/javascript" src="/script/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/script/superfish.js"></script> <link href="~/css/superfish.css" type="text/css" rel="stylesheet" media="screen" runat="server" /> <script type="text/javascript"> $(document).ready(function() { $('ul.AspNet-Menu').superfish(); }); </script></head> Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on these instructions ): <asp:SiteMapDataSource ID="SiteMapDataSource" runat="server" ShowStartingNode="false" /><asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource" Orientation="Horizontal" CssClass="sf-menu"></asp:Menu> Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the CssClass="sf-menu" gets overwritten when the Menu is rendered and the <ul> tag gets a class="AspNet-Menu" . I thought the line $('ul.AspNet-Menu').superfish(); would help, but it didn't. ONE MORE THING Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the superfish.css file and search and replacing sf-menu with AspNet-Menu ... and voila! the menu appeared. I thought there would be some configuration setting in the asp:Menu control where I could set the <ul> class but didn't find any hints via google.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ] }
103,654
In several modern programming languages (including C++, Java, and C#), the language allows integer overflow to occur at runtime without raising any kind of error condition. For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.) //Returns the sum of the values in the specified list.private static int sumList(List<int> list){ int sum = 0; foreach (int listItem in list) { sum += listItem; } return sum;} If this method is called as follows: List<int> list = new List<int>();list.Add(2000000000);list.Add(2000000000);int sum = sumList(list); An overflow will occur in the sumList() method (because the int type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended. Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's BigInteger , or the checked keyword and /checked compiler switch in C#. However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually does have this .) Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs? Are there other reasons for this language design decision as well, other than performance considerations?
In C#, it was a question of performance. Specifically, out-of-box benchmarking. When C# was new, Microsoft was hoping a lot of C++ developers would switch to it. They knew that many C++ folks thought of C++ as being fast, especially faster than languages that "wasted" time on automatic memory management and the like. Both potential adopters and magazine reviewers are likely to get a copy of the new C#, install it, build a trivial app that no one would ever write in the real world, run it in a tight loop, and measure how long it took. Then they'd make a decision for their company or publish an article based on that result. The fact that their test showed C# to be slower than natively compiled C++ is the kind of thing that would turn people off C# quickly. The fact that your C# app is going to catch overflow/underflow automatically is the kind of thing that they might miss. So, it's off by default. I think it's obvious that 99% of the time we want /checked to be on. It's an unfortunate compromise.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12484/" ] }
103,669
I attended a job fair yesterday and a developer asked me how I would rank my proficiency in C. I then realized that this is incredibly arbitrary and almost impossible to nail down, so my question is what knowledge makes you an expert in programming C? Edit: or what would the breakdown be? what makes you good, decent, proficient, etc. Edit again: I was looking more for like a list of skills or some other constructive measure by which to judge one's own proficiency in C, as that's hard to do. List so far: Experience in large projects Mastery of Pointers (and memory management, I'd assume) Mastery of a debugger (gdb, ...) Mastery of a profiler (gprof,...) Mastery of a memory profiler (valgrind, ...) Knowledge of the fundamental standards
Experience is key, knowing the "rules" and syntax of the of the language is of course a must, but it is only a base. Learning the common pitfalls and idioms for doing things right is key. Knowing what if any resources exist to get help from while your programing, and of course, knowing you're tool chain. I've known many C++ "experts" who had never used a debugger, or a memory tracker. If you ask me, being an expert in something is different from being proficient in something in you knowing all aspects of it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10307/" ] }
103,707
For an image hosting web application: For my stored images, is it feasible to create thumbnails on the fly using PHP (or whatever), or should I save 1 or more different sized thumbnails to disk and just load those? Any help is appreciated.
Save thumbnails to disk. Image processing takes a lot of resources and, depending on the size of the image, might exceed the default allowed memory limit for php. It is less of a concern if you have your own server with only your application running but it still takes a lot of cpu power and memory to resize images. If you're considering creating thumbnails on the fly anyway, you don't have to change much - upon the first request, create the thumbnail from the source file, save it to disk and upon subsequent requests just read it off the disk.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
103,727
As an example, Google App Engine uses Google Datastore, not a standard database, to store data. Does anybody have any tips for using Google Datastore instead of databases? It seems I've trained my mind to think 100% in object relationships that map directly to table structures, and now it's hard to see anything differently. I can understand some of the benefits of Google Datastore (e.g. performance and the ability to distribute data), but some good database functionality is sacrificed (e.g. joins). Does anybody who has worked with Google Datastore or BigTable have any good advice to working with them?
There's two main things to get used to about the App Engine datastore when compared to 'traditional' relational databases: The datastore makes no distinction between inserts and updates. When you call put() on an entity, that entity gets stored to the datastore with its unique key, and anything that has that key gets overwritten. Basically, each entity kind in the datastore acts like an enormous map or sorted list. Querying, as you alluded to, is much more limited. No joins, for a start. The key thing to realise - and the reason behind both these differences - is that Bigtable basically acts like an enormous ordered dictionary. Thus, a put operation just sets the value for a given key - regardless of any previous value for that key, and fetch operations are limited to fetching single keys or contiguous ranges of keys. More sophisticated queries are made possible with indexes, which are basically just tables of their own, allowing you to implement more complex queries as scans on contiguous ranges. Once you've absorbed that, you have the basic knowledge needed to understand the capabilities and limitations of the datastore. Restrictions that may have seemed arbitrary probably make more sense. The key thing here is that although these are restrictions over what you can do in a relational database, these same restrictions are what make it practical to scale up to the sort of magnitude that Bigtable is designed to handle. You simply can't execute the sort of query that looks good on paper but is atrociously slow in an SQL database. In terms of how to change how you represent data, the most important thing is precalculation. Instead of doing joins at query time, precalculate data and store it in the datastore wherever possible. If you want to pick a random record, generate a random number and store it with each record. There's a whole cookbook of this sort of tips and tricks here .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/103727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ] }
103,766
I need to store user entered changes to a particular table, but not show those changes until they have been viewed and approved by an administrative user. While those changes are still in a pending state, I would still display the old version of the data. What would be the best way of storing these changes waiting for approval? I have thought of several ways, but can't figure out what is the best method. This is a very small web app. One way would be to have a PendingChanges table that mimics the other table's schema, and then once the change is approved, I could update the real table with the information. Another approach would be to do some sort of record versioning where I store multiple versions of the data in the table and then always pull the record with the highest version number that has been marked approved. That would limit the number of extra tables (I need to do this for multiple tables), but would require me to do extra processing every time I pull out a set of records to make sure I get the right ones. Any personal experiences with these methods or others that might be good? Update: Just to clarify, in this particular situation I am not interested so much in historical data. I just need some way of approving any changes that are made by a user before they go live on the site. So, a user will edit their "profile" and then an administrator will look at that modification and approve it. Once approved, that will become the displayed value and the old version does not need to be kept. Anybody tried the solution below where you store pending changes from any table that needs to track them as XML in a special PendingChanges table? Each record would have a column that said which table the changes were for, a column that maybe stored the id of the record that would be changed (null if it's a new record), a datetime column to store when the change was made, and a column to store the xml of the changed record (could maybe serialize my data object). Since I don't need history, after a change was approved, the real table would be updated and the PendingChange record could be deleted. Any thoughts about that method?
Size is your enemy. If you are dealing with lots of data and large numbers of rows, then having the historical mixed in with the current will hammer you. You'll also have problems if you join out to other data with making sure you've got the right rows. If you need to save the historical data to show changes over time, I would go with the separate historical, table that updates the live, real data once it's approved. It's just all-around cleaner. If you have a lot of datatypes that will have this mechanism but don't need to keep a historical record, I would suggest a common queue talbe for reviewing pending items, say stored as xml. This would allow just one table to be read by administrators and would enable you to add this functionality to any table in you system fairly easily.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/103766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19090/" ] }
103,785
I've found that on some occasions I can edit the source while debugging. Are there any other advantages of using the Visual Studio built-in webserver instead of a virtual directory in IIS? I'm using Windows XP on my development environment, and a local instance of IIS 5. I work on several projects, so I use multiple virtual directories to manage all the different sites. Are there any disadvantages?
The built-in web server for Visual Studio is called Cassini and here are a few of its limitations... It can host only one ASP.NETapplication per port. It does not support HTTPS. It does not support authentication. It responds only to localhostrequests. It is slow startup compared to IIS
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/103785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018/" ] }
103,844
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: li = [[0,1,2],[3,4,5],[6,7,8]] I would like to merge this either into one long list li2 = [0,1,2,3,4,5,6,7,8] or into a string with separators: s = "0,1,2,3,4,5,6,7,8" Really, I'd like to know how to do both.
Like so: [ item for innerlist in outerlist for item in innerlist ] Turning that directly into a string with separators: ','.join(str(item) for innerlist in outerlist for item in innerlist) Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out: for innerlist in outerlist: for item in innerlist: ...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/103844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ] }
103,938
I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode): Connection conn = dataSource.getConnection();try{ PreparedStatement stmt = conn.prepareStatement(); //initialize the statement stmt.execute(); ResultSet rs = stmt.getResultSet(); //get data}finally{ conn.close();} The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally: finally{ try{ rs.close() }catch(SqlException se){ //log it } try{ stmt.close(); }catch(SqlException se){ //log it } conn.close();} But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements. Did you have troubles with ResultSets and Statements not being closed when the Connection is closed? I found only this and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.
One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the connection.close() would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/103938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7918/" ] }
104,022
I'm currently using .resx files to manage my server side resources for .NET. the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings? Ideally, I would like to store the strings in the .resx files to keep them with the rest of the localized resources. I'm open to suggestions.
A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using JSON , you could create an object for each string to be localized like this: var localizedStrings={ confirmMessage:{ 'en/US':'Are you sure?', 'fr/FR':'Est-ce que vous êtes certain?', ... }, ...} Then you could get the locale version of each string like this: var locale='en/US';var confirm=localizedStrings['confirmMessage'][locale];
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ] }
104,055
I know how to use rpm to list the contents of a package ( rpm -qpil package.rpm ). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this?
There is a package called yum-utils that builds on YUM and contains a tool called repoquery that can do this. $ repoquery --help | grep -E "list\ files" -l, --list list files in this package/group Combined into one example: $ repoquery -l time/usr/bin/time/usr/share/doc/time-1.7/usr/share/doc/time-1.7/COPYING/usr/share/doc/time-1.7/NEWS/usr/share/doc/time-1.7/README/usr/share/info/time.info.gz On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, repoquery -l rpm prints nothing. If you are having this issue, try adding the --installed flag: repoquery --installed -l rpm . DNF Update: To use dnf instead of yum-utils , use the following command: $ dnf repoquery -l time/usr/bin/time/usr/share/doc/time-1.7/usr/share/doc/time-1.7/COPYING/usr/share/doc/time-1.7/NEWS/usr/share/doc/time-1.7/README/usr/share/info/time.info.gz
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/104055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ] }
104,063
I noticed in another post, someone had done something like: double d = 3.1415;int i = Convert.ToInt32(Math.Floor(d)); Why did they use the convert function, rather than: double d = 3.1415;int i = (int)d; which has an implicit floor and convert. Also, more concerning, I noticed in some production code I was reading: double d = 3.1415;float f = Convert.ToSingle(d); Is that the same as: float f = (float)d; Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.
Casting to int is implicit truncation, not implicit flooring: double d = -3.14;int i = (int)d;// i == -3 I choose Math.Floor or Math.Round to make my intentions more explicit.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15261/" ] }
104,099
Some things are easier to implement just by hand (code), but some are easier through WF. It looks like WF can be used to create (almost) any kind of algorithm. So (theoretically) I can do all my logic in WF, but it's probably a bad idea to do it for all projects. In what situations is it a good idea to use WF and when will it make things harder then they have to be? What are pros and cons/cost of WF vs. coding by hand?
You may need WF only if any of the following are true: You have a long-running process. You have a process that changes frequently. You want a visual model of the process. For more details, see Paul Andrew's post: What to use Windows Workflow Foundation for? Please do not confuse or relate WF with visual programming of any kind. It is wrong and can lead to very bad architecture/design decisions.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124/" ] }
104,158
I came across this recently, up until now I have been happily overriding the equality operator ( == ) and/or Equals method in order to see if two references types actually contained the same data (i.e. two different instances that look the same). I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned). While looking over some of the coding standards guidelines in MSDN I came across an article that advises against it. Now I understand why the article is saying this (because they are not the same instance ) but it does not answer the question: What is the best way to compare two reference types? Should we implement IComparable ? (I have also seen mention that this should be reserved for value types only). Is there some interface I don't know about? Should we just roll our own?! Many Thanks ^_^ Update Looks like I had mis-read some of the documentation (it's been a long day) and overriding Equals may be the way to go.. If you are implementing referencetypes, you should consider overridingthe Equals method on a reference typeif your type looks like a base typesuch as a Point, String, BigNumber,and so on. Most reference types shouldnot overload the equality operator,even if they override Equals . However,if you are implementing a referencetype that is intended to have valuesemantics, such as a complex numbertype, you should override the equalityoperator.
It looks like you're coding in C#, which has a method called Equals that your class should implement, should you want to compare two objects using some other metric than "are these two pointers (because object handles are just that, pointers) to the same memory address?". I grabbed some sample code from here : class TwoDPoint : System.Object{ public readonly int x, y; public TwoDPoint(int x, int y) //constructor { this.x = x; this.y = y; } public override bool Equals(System.Object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; if ((System.Object)p == null) { return false; } // Return true if the fields match: return (x == p.x) && (y == p.y); } public bool Equals(TwoDPoint p) { // If parameter is null return false: if ((object)p == null) { return false; } // Return true if the fields match: return (x == p.x) && (y == p.y); } public override int GetHashCode() { return x ^ y; }} Java has very similar mechanisms. The equals() method is part of the Object class, and your class overloads it if you want this type of functionality. The reason overloading '==' can be a bad idea for objects is that, usually, you still want to be able to do the "are these the same pointer" comparisons. These are usually relied upon for, for instance, inserting an element into a list where no duplicates are allowed, and some of your framework stuff may not work if this operator is overloaded in a non-standard way.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/104158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ] }
104,184
There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a java.util.HashMap in this way? (Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap , and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice. Hence, this question is not "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")
Your idiom is safe if and only if the reference to the HashMap is safely published . Rather than anything relating the internals of HashMap itself, safe publication deals with how the constructing thread makes the reference to the map visible to other threads. Basically, the only possible race here is between the construction of the HashMap and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the HashMap reference is published. For example, imagine you publish the map like this: class SomeClass { public static HashMap<Object, Object> MAP; public synchronized static setMap(HashMap<Object, Object> m) { MAP = m; }} ... and at some point setMap() is called with a map, and other threads are using SomeClass.MAP to access the map, and check for null like this: HashMap<Object,Object> map = SomeClass.MAP;if (map != null) { .. use the map} else { .. some default behavior} This is not safe even though it probably appears as though it is. The problem is that there is no happens-before relationship between the set of SomeObject.MAP and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do anything and even in practice it does things like put the reading thread into an infinite loop . To safely publish the map, you need to establish a happens-before relationship between the writing of the reference to the HashMap (i.e., the publication ) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to accomplish that [1] : Exchange the reference through a properly locked field ( JLS 17.4.5 ) Use static initializer to do the initializing stores ( JLS 12.4 ) Exchange the reference via a volatile field ( JLS 17.4.5 ), or as the consequence of this rule, via the AtomicX classes Initialize the value into a final field ( JLS 17.5 ). The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of MAP to: public static volatile HashMap<Object, Object> MAP; then everything is kosher: readers who see a non-null value necessarily have a happens-before relationship with the store to MAP and hence see all the stores associated with the map initialization. The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using final ) imply that you cannot set MAP dynamically at runtime. If you don't need to do that, then just declare MAP as a static final HashMap<> and you are guaranteed safe publication. In practice, the rules are simple for safe access to "never-modified objects": If you are publishing an object which is not inherently immutable (as in all fields declared final ) and: You already can create the object that will be assigned at the moment of declaration a : just use a final field (including static final for static members). You want to assign the object later, after the reference is already visible: use a volatile field b . That's it! In practice, it is very efficient. The use of a static final field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a final member field allows most architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizations c . Finally, the use of volatile does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one HashMap , you can store as many more not-modified HashMap s as you want to the same reference and be assured that all readers will see a safely published map. For more gory details, refer to Shipilev or this FAQ by Manson and Goetz . [1] Directly quoting from shipilev . a That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields). b Optionally, you can use a synchronized method to get/set, or an AtomicReference or something, but we're talking about the minimum work you can do. c Some architectures with very weak memory models (I'm looking at you , Alpha) may require some type of read barrier before a final read - but these are very rare today.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3093/" ] }
104,196
What are the benefits of doing static code analysis on your source code? I was playing around with FxCop and I was wondering if there any benefits beyond making sure you are following the coding standards.
There are all kinds of benefits: If there are anti-patterns in your code, you can be warned about it. There are certain metrics (such as McCabe's Cyclomatic Complexity)that tell useful things about source code. You can also get great stuff like call-graphs, and class diagramsfrom static analysis. Those are wonderful if you are attacking anew code base. Take a look at SourceMonitor
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2137/" ] }
104,225
I have a co-worker that maintains that TRUE used to be defined as 0 and all other values were FALSE. I could swear that every language I've worked with, if you could even get a value for a boolean, that the value for FALSE is 0. Did TRUE used to be 0? If so, when did we switch?
The 0 / non-0 thing your coworker is confused about is probably referring to when people use numeric values as return value indicating success, not truth (i.e. in bash scripts and some styles of C/C++). Using 0 = success allows for a much greater precision in specifying causes of failure (e.g. 1 = missing file, 2 = missing limb, and so on). As a side note: in Ruby, the only false values are nil and false. 0 is true, but not as opposed to other numbers. 0 is true because it's an instance of the object 0.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/104225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10887/" ] }
104,235
What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.
Put the following where you need it: System.Diagnostics.Debugger.Break();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432/" ] }
104,254
I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the java.io.Console class to manage output and, more importantly, user input. The problem is that System.console() returns null when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with. Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.
I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath. java -cp workspace\p1\bin;workspace\p2\bin foo.Main You can debug using the remote debugger and taking advantage of the class files built in your project. In this example, the Eclipse project structure looks like this: workspace\project\ \.classpath \.project \debug.bat \bin\Main.class \src\Main.java 1. Start the JVM Console in Debug Mode debug.bat is a Windows batch file that should be run externally from a cmd.exe console. @ECHO OFFSET A_PORT=8787SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=yjava.exe %A_DBG% -cp .\bin Main In the arguments, the debug port has been set to 8787 . The suspend=y argument tells the JVM to wait until the debugger attaches. 2. Create a Debug Launch Configuration In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new Remote Java Application configuration with the following settings: Project: your project name Connection Type: Standard (Socket Attach) Host: localhost Port: 8787 3. Debugging So, all you have to do any time you want to debug the app is: set a break point launch the batch file in a console launch the debug configuration You can track this issue in bug 122429 . You can work round this issue in your application by using an abstraction layer as described here .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19147/" ] }
104,291
I wrote a utility for photographers that I plan to sell online pretty cheap ($10). I'd like to allow the user to try the software out for a week or so before asking for a license. Since this is a personal project and the software is not very expensive, I don't think that purchasing the services of professional licensing providers would be worth it and I'm rolling my own. Currently, the application checks for a registry key that contains an encrypted string that either specifies when the trial expires or that they have a valid license. If the key is not present, a trial period key is created. So all you would need to do to get another week for free is delete the registry key. I don't think many users would do that, especially when the app is only $10, but I'm curious if there's a better way to do this that is not onerous to the legitimate user. I write web apps normally and haven't dealt with this stuff before. The app is in .NET 2.0, if that matters.
EDIT: You can make your current licensing scheme considerable more difficult to crack by storing the registry information in the Local Security Authority (LSA). Most users will not be able to remove your key information from there. A search for LSA on MSDN should give you the information you need. Opinions on licensing schemes vary with each individual, more among developers than specific user groups (such as photographers). You should take a deep breath and try to see what your target user would accept, given the business need your application will solve. This is my personal opinion on the subject. There will be vocal individuals that disagree. The answer to this depends greatly on how you expect your application to be used. If you expect the application to be used several times every day, you will benefit the most from a very long trial period (several month), to create a lock-in situation. For this to work you will have to have a grace period where the software alerts the user that payment will be needed soon. Before the grace period you will have greater success if the software is silent about the trial period. Wether or not you choose to believe in this quite bold statement is of course entirely up to you. But if you do, you should realize that the less often your application will be used, the shorter the trial period should be. It is also very important that payment is very quick and easy for the user (as little data entry and as few clicks as possible). If you are very uncertain about the usage of the application, you should choose a very short trial period. You will, in my experience, achieve better results if the application is silent about the fact that it is in trial period in this case. Though effective for licensing purposes, "Call home" features is regarded as a privacy threat by many people. Personally I disagree with the notion that this is any way bad for a customer that is willing to pay for the software he/she is using. Therefore I suggest implementing a licensing scheme where the application checks the license status (trial, paid) on a regular basis, and helps the user pay for the software when it's time. This might be overkill for a small utility application, though. For very small, or even simple, utility applications, I argue that upfront payment without trial period is the most effective. Regarding the security of the solution, you have to make it proportional to the development effort. In my line of work, security is very critical because there are partners and dealers involved, and because the investment made in development is very high. For a small utility application, it makes more sense to price it right and rely on the honest users that will pay for the software that address their business needs.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521/" ] }
104,292
I'm getting the following error when trying to build my app using Team Foundation Build: C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(1682,9): error MSB3554: Cannot write to the output file "obj\Release\Company.Redacted.BlahBlah.Localization.Subsystems. Startup_Shutdown_Processing.StartupShutdownProcessingMessages.de.resources". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. My project builds fine on my development machine as the source is only two folders deep, but TF Build seems to use a really deep directory that is causing it to break. How do I change the folders that are used? Edit: I checked the .proj file for my build that is stored in source control and found the following: <!-- BUILD DIRECTORY This property is included only for backwards compatibility. The build directory used for a build definition is now stored in the database, as the BuildDirectory property of the definition's DefaultBuildAgent. For compatibility with V1 clients, keep this property in sync with the value in the database.--><BuildDirectoryPath>UNKNOWN</BuildDirectoryPath> If this is stored in the database how do I change it? Edit: Found the following blog post which may be pointing me torward the solution. Now I just need to figure out how to change the setting in the Build Agent. http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx Currently my working directory is "$(Temp)\$(BuildDefinitionPath)" but now I don't know what wildcards are available to specify a different folder.
You need to edit the build working directory of your Build Agent so that the begging path is a little smaller. To edit the build agent, right click on the "Builds" node and select "Manage Build Agents..." I personally use something like c:\bw\$(BuildDefinitionId). $(BuildDefinitionId) translates into the id of the build definition (hence the name :-) ), which means you get a build path starting with something like c:\bw\36 rather than c:\Documents and Settings\tfsbuild\Local Settings\Temp\BuildDefinitionName Good luck, Martin.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
104,322
How do you install Boost on MacOS?Right now I can't find bjam for the Mac.
Download MacPorts , and run the following command: sudo port install boost
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ] }
104,329
What kind of performance implications are there to consider when using try-catch statements in php 5? I've read some old and seemingly conflicting information on this subject on the web before. A lot of the framework I currently have to work with was created on php 4 and lacks many of the niceties of php 5. So, I don't have much experience myself in using try-catchs with php.
One thing to consider is that the cost of a try block where no exception is thrown is a different question from the cost of actually throwing and catching an exception. If exceptions are only thrown in failure cases, you almost certainly don't care about performance, since you won't fail very many times per execution of your program. If you're failing in a tight loop (a.k.a: banging your head against a brick wall), your application likely has worse problems than being slow. So don't worry about the cost of throwing an exception unless you're somehow forced to use them for regular control flow. Someone posted an answer talking about profiling code which throws an exception. I've never tested it myself, but I confidently predict that this will show a much bigger performance hit than just going in and out of a try block without throwing anything. Another thing to consider is that where you nest calls a lot of levels deep, it can even be faster to have a single try...catch right at the top than it is to check return values and propagate errors on every call. In the opposite of that situation, where you find that you're wrapping every call in its own try...catch block, your code will be slower. And uglier.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14959/" ] }