source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
174,981 | Is there any IDE for coding mono on windows platform? | MonoDevelop has now released a installer for Windows. You no longer need to build it from source. It is available from the MonoDevelop website However on windows it runs on the .NET Framework, not Mono - it uses the .NET debugger instead of the Mono one. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/174981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
]
} |
175,044 | I have done a little Django development, but it has all been in a text editor. I was curious what more advanced development tools others are using in their Django development. I am used to using Visual Studio for development and really like the IntelliSense , code completion, and file organization it provides and would like to find something (or a combination of tools) that would provide some of this in the Django/Python environment. | I use Eclipse and a plain vanilla PyDev . There isn't any specific Django functionality. The best I came up with was setting up a run profile to run the development web server. If you add the web tools project (WTP), you'll get syntax highlighting in your templates, but nothing that relates to the specific template language. PyDev is a decent plugin, and if you are already familiar with Eclipse and use it for other projects it is a good way to go. I recall NetBeans starting to get Python support, but I have no idea where that is right now. Lots of people rave about NetBeans 6, but in the Java world Eclipse still reigns as the king of the OSS IDEs. Update: LiClipse is also fantastic for Django. Install it, use this method to get the icon into Ubuntu's menu. Start LiClipse and in File > New > Project ..., select PyDev and PyDev Django project. You may have to set up your Python interpreter etc, but that you'll be able to figure out on your own. Once the Django project is created, you can right click on the project and the menu will have a "Django" option, which allows various things like creating a Django app or running migrations etc. LiClipse is good because it consumes far lesser memory than PyCharm and supports refactoring and autocomplete reasonably well. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/175044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405/"
]
} |
175,056 | In a project I am working on, we have an ongoing discussion amongst the dev team - should the production environment be deployed as a checkout from the SVN repository or as an export? The development environment is obviously a checkout, since it is constantly updated.For the production, I'm personally for checking out the main trunk, since it makes future updates easier (just run svn update). However some of the devs are against it, as svn creates files with the group/owner and permissions of the svn process (this is on a linux OS, so those things matter), and also having the .svn directories on the production seem to them to be somewhat dirty. Also, if it is a checkout - how do you push individual features to the production without including in-development code? do you use tags or branch out for each feature? any alternatives? EDIT: I might not have been clear - one of the requirement is to be able to constantly be able to push fixes to the production environment. We want to avoid a complete build (which takes much longer than a simple update) just for pushing critical fixes. | The Subversion FAQ seems to advocate deployment as a checkout, autoupdated with post-commit hook scripts. They prevent Apache from exporting .svn folders (probably a good idea) by adding the following in httpd.conf: # Disallow browsing of Subversion working copy administrative dirs.<DirectoryMatch "^/.*/\.svn/"> Order deny,allow Deny from all</DirectoryMatch> I'm extremely new to svn myself, but maybe you could trigger a hook script when you create a new tag. That way, when you're ready to update the live site, you just commit your last changes to the trunk, create the new tag, and the script updates your live site with svn update. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
]
} |
175,066 | My database contains three tables called Object_Table , Data_Table and Link_Table . The link table just contains two columns, the identity of an object record and an identity of a data record. I want to copy the data from DATA_TABLE where it is linked to one given object identity and insert corresponding records into Data_Table and Link_Table for a different given object identity. I can do this by selecting into a table variable and the looping through doing two inserts for each iteration. Is this the best way to do it? Edit : I want to avoid a loop for two reason, the first is that I'm lazy and a loop/temp table requires more code, more code means more places to make a mistake and the second reason is a concern about performance. I can copy all the data in one insert but how do get the link table to link to the new data records where each record has a new id? | In one statement : No. In one transaction : Yes BEGIN TRANSACTION DECLARE @DataID int; INSERT INTO DataTable (Column1 ...) VALUES (....); SELECT @DataID = scope_identity(); INSERT INTO LinkTable VALUES (@ObjectID, @DataID);COMMIT The good news is that the above code is also guaranteed to be atomic , and can be sent to the server from a client application with one sql string in a single function call as if it were one statement. You could also apply a trigger to one table to get the effect of a single insert. However, it's ultimately still two statements and you probably don't want to run the trigger for every insert. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/175066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
]
} |
175,091 | I'm trying to host a PHP web site that was given to me. I see this warning: Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in Unknown on line 0 What does this mean? How might I track down the source of this problem within the code? | basically you have a variable with the same name as your session. ex: $_SESSION['var1'] = null;$var1 = 'something'; which will reproduce this error. you can stop PHP from trying to find existing variables and warning you about them by adding these lines to your script: ini_set('session.bug_compat_warn', 0);ini_set('session.bug_compat_42', 0); these values can be set in php.ini or .htaccess as well | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/175091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
]
} |
175,103 | I have a URL , and I'm trying to match it to a regular expression to pull out some groups. The problem I'm having is that the URL can either end or continue with a "/" and more URL text. I'd like to match URLs like this: http://server/xyz/2008-10-08-4 http://server/xyz/2008-10-08-4/ http://server/xyz/2008-10-08-4/123/more But not match something like this: http://server/xyz/2008-10-08-4-1 So, I thought my best bet was something like this: /(.+)/(\d{4}-\d{2}-\d{2})-(\d+)[/$] where the character class at the end contained either the "/" or the end-of-line. The character class doesn't seem to be happy with the "$" in there though. How can I best discriminate between these URLs while still pulling back the correct groups? | /(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$ 1st Capturing Group (.+) .+ matches any character (except for line terminators) + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) 2nd Capturing Group (\d{4}-\d{2}-\d{2}) \d{4} matches a digit (equal to [0-9] ) {4} Quantifier — Matches exactly 4 times - matches the character - literally (case sensitive) \d{2} matches a digit (equal to [0-9] ) {2} Quantifier — Matches exactly 2 times - matches the character - literally (case sensitive) \d{2} matches a digit (equal to [0-9] ) {2} Quantifier — Matches exactly 2 times - matches the character - literally (case sensitive) 3rd Capturing Group (\d+) \d+ matches a digit (equal to [0-9] ) + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) 4th Capturing Group (.*)? ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy) .* matches any character (except for line terminators) * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) $ asserts position at the end of the string | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
]
} |
175,116 | For obvious productivity reasons, I make an effort of learning and using as many of the keyboard shortcuts for the various Re# commands. However, it seems that the unit test runner does not have any associated shortcut keys. I want to be able to select certain tests and be able to run or debug them without resorting to grabbing the mouse each time. Is using the mouse my only option? | ReSharper adds items to Visual Studio's keyboard settings dialog box. Go to: Tools -> Options, Environment -> Keyboard In the search bar, type "resharper" and see the vast options that you can control with the keyboard. Specifically, there is one to launch the unit test explorer window, and there's a couple called ReSharper.ReSharper_UnitTest_RunSolution ReSharper.ReSharper_UnitTest_RunContext that are likely what you need. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
175,170 | What function can I use in Excel VBA to slice an array? | Application.WorksheetFunction.Index(array, row, column) If you specify a zero value for row or column, then you'll get the entire column or row that is specified. Example: Application.WorksheetFunction.Index(array, 0, 3) This will give you the entire 3rd column. If you specify both row and column as non-zero, then you'll get only the specific element.There is no easy way to get a smaller slice than a complete row or column. Limitation : There is a limit to the array size that WorksheetFunction.Index can handle if you're using a newer version of Excel. If array has more than 65,536 rows or 65,536 columns, then it throws a "Type mismatch" error. If this is an issue for you, then see this more complicated answer which is not subject to the same limitation. Here's the function I wrote to do all my 1D and 2D slicing: Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant' this function returns a slice of an array, Stype is either row or column' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire' row or column is taken), Sindex is the row or column to be sliced' (NOTE: 1 is always the first row or first column)' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljrDim vtemp() As VariantDim i As IntegerOn Err GoTo ErrHandlerSelect Case Sindex Case 0 If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then vtemp = Sarray Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(i + Sstart - 1) Next i End If Case Else Select Case Stype Case "row" If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0) Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(Sindex, i + Sstart - 1) Next i End If Case "column" If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex) Else ReDim vtemp(1 To Sfinish - Sstart + 1) For i = 1 To Sfinish - Sstart + 1 vtemp(i) = Sarray(i + Sstart - 1, Sindex) Next i End If End SelectEnd SelectGetArraySlice2D = vtempExit FunctionErrHandler: Dim M As Integer M = MsgBox("Bad Array Input", vbOKOnly, "GetArraySlice2D")End Function | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
]
} |
175,176 | Why is it that advertised disk space is almost always higher than the disk space reported by the UI? For example, I have an "80 gb" hard drive, but the iTunes UI indicates only 74. I usually see this as well with hard disks and the amount reported with the drive letter. | There are 3 reasons why the amount of space you can actually use is different from that listed for the drive, all of which work against you: Hard drive manufacturers treat 1GB as one billion bytes, while the operating system calls it 1,073,741,824 bytes (1000 * 1000 * 1000 vs 1024 * 1024 * 1024). You lose some space for file tables when formatting. Disk space is divided into chunks larger than 1 byte (typically 4K). Using typical Windows defaults, a 1 byte file takes up 4K of space on disk. Of these, the first two can influence the amount of space reported by the drive (though IIRC the 2nd one was more of an issue with FAT32 than NTFS). The last one only influences the amount of free space remaining, but will still prevent you from using the full capacity of your drive. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10693/"
]
} |
175,186 | Let's say I have this type in my application: public class A { public int id; public B b; public boolean equals(Object another) { return this.id == ((A)another).id; } public int hashCode() { return 31 * id; //nice prime number }} and a Set <A > structure. Now, I have an object of type A and want to do the following: If my A is within the set, update its field b to match my object. Else, add it to the set. So checking if it is in there is easy enough ( contains ), and adding to the set is easy too. My question is this: how do I get a handle to update the object within? Interface Set doesn't have a get method, and the best I could think of was to remove the object in the set and add mine. another, even worse, alternative is to traverse the set with an iterator to try and locate the object. I'll gladly take better suggestions... This includes the efficient use of other data structures. Yuval =8-) EDIT : Thank you all for answering... Unfortunately I can't 'accept' the best answers here, those that suggest using a Map , because changing the type of the collection radically for this purpose only would be a little extreme (this collection is already mapped through Hibernate...) | Since a Set can only contain one instance of an object (as defined by its equals and hashCode methods), just remove it and then add it. If there was one already, that other one will be removed from the Set and replaced by the one you want. I have code that does something similar - I am caching objects so that everywhere a particular object appears in a bunch of different places on the GUI, it's always the same one. In that case, instead of using a Set I'm using a Map, and then I get an update, I retrieve it from the Map and update it in place rather than creating a new instance. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2819/"
]
} |
175,228 | Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious? For example, imagine I have this class in C++: public class SomeClass {private: bool mIsVisible;public: void draw(); void erase();} I could add functions to get/set "mIsVisible" like this: bool getVisible() { return mIsVisible; }; void setVisible(bool visible) { if (!mIsVisible && visible) { draw(); } else if (mIsVisible && !visible) { erase(); } mIsVisible = visible; } However, it would be equally possible to use the following methods instead: bool isVisible() { return mIsVisible; };void show() { if (!mIsVisible) { mIsVisible = true; draw(); }}void hide() { if (mIsVisible) { mIsVisible = false; erase(); }} In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing? | Have a read of the article " Tell, Don't Ask " over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go. Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely: get current visibility value, make decision based on value, update object. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2289/"
]
} |
175,240 | I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format. What is the best way to convert the entire file format using Python? | You can convert the file easily enough just using the unicode function, but you'll run into problems with Unicode characters without a straight ASCII equivalent. This blog recommends the unicodedata module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g. >>> title = u"Klüft skräms inför på fédéral électoral große" is typically converted to Klft skrms infr p fdral lectoral groe which is pretty wrong. However, using the unicodedata module, the result can be much closer to the original text: >>> import unicodedata>>> unicodedata.normalize('NFKD', title).encode('ascii','ignore')'Kluft skrams infor pa federal electoral groe' | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
175,344 | HI, I am new to the scrum methodology and looking for some help to get comfortable with the environment and wondering if there needs to be a bucket to track Developers and QA hours spent on deployments and bug fixes and retests. Seems like it could have major impact on the graph. | My team is supporting a number of legacy apps, so there's quite a bit of unplanned bug fixing that occurs during each sprint. We've adopted the following practice: If the bug is easy/quick to fix (one liner, etc), then just fix it. If the bug is not trivial, and not a blocker, then add it to the backlog. If the bug is a blocker then add a task (to the current sprint) to capture the work required to fix it, and start working on it. This requires that something else be moved (from the current sprint) to the backlog to account for the new hours because your total hours available hasn't changed. When we add new bug tasks we'll mark them differently from the planned tasks so make them easy to see during the sprint review. Sometimes unplanned work ends up being >50% of our sprint, but because we're pushing planned items to the backlog we know very early what we're not delivering this sprint that we had planned on. This has proven to be very useful for our team in dealing with legacy apps where none of us are as familiar or confident with the systems as we'd like to be. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21380/"
]
} |
175,381 | I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control? <div id="formSpinner"> <img src="images/spinner.gif" /> <p>Saving...</p></div> | Add the runat="server" attribute to it so you have: <div id="formSpinner" runat="server"> <img src="images/spinner.gif"> <p>Saving...</p></div> That way you can access the class attribute by using: formSpinner.Attributes["class"] = "classOfYourChoice"; It's also worth mentioning that the asp:Panel control is virtually synonymous (at least as far as rendered markup is concerned) with div , so you could also do: <asp:Panel id="formSpinner" runat="server"> <img src="images/spinner.gif"> <p>Saving...</p></asp:Panel> Which then enables you to write: formSpinner.CssClass = "classOfYourChoice"; This gives you more defined access to the property and there are others that may, or may not, be of use to you. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25538/"
]
} |
175,385 | When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach? | CSS is fine for rollovers. They're implemented basically using the :hover pseudo-selector. Here's a really simple implementation: a{ background-image: url(non-hovered-state.png);}a:hover{ background-image: url(hovered-state.png);} There are a few things you need to be aware of though: IE6 only supports :hover on <a> tags Images specified in CSS but not used on the page won't be loaded immediately (meaning the rollover state can take a second to appear first time) The <a> -tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called CSS Sprites that can prevent this problem, you can find an example of the technique in use to make no-preload rollovers . It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using background-position so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)): a{ background-image: url(rollover-sprites.png); background-position: 0 0; /* Added for clarity */ height: 20px;}a:hover{ background-position: 0 -20px; /* move the image up 20px to show the hovered state below */} Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support background-position ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
]
} |
175,415 | What is the best way to get the names of all of the tables in a specific database on SQL Server? | SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019: SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' To show only tables from a particular database SELECT TABLE_NAME FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' Or, SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' ) PS: For SQL Server 2000: SELECT * FROM sysobjects WHERE xtype='U' | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/175415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
175,451 | How do you prepare your SQL deltas? do you manually save each schema-changing SQL to a delta folder, or do you have some kind of an automated diffing process? I am interested in conventions for versioning database schema along with the source code. Perhaps a pre-commit hook that diffs the schema? Also, what options for diffing deltas exist aside from DbDeploy ? EDIT: seeing the answers I would like to clarify that I am familiar with the standard scheme for running a database migration using deltas. My question is about creating the deltas themselves, preferably automatically. Also, the versioning is for PHP and MySQL if it makes a difference. (No Ruby solutions please). | See Is there a version control system for database structure changes? How do I version my MS SQL database in SVN? and Jeff's article Get Your Database Under Version Control I feel your pain, and I wish there were a better answer. This might be closer to what you were looking for. Mechanisms for tracking DB schema changes Generally, I feel there is no adequate, accepted solution to this, and I roll my own in this area. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
]
} |
175,454 | I am working on a web application and I have run into the following situation. Dim a as ObjectDim i as Integer = 0Try For i=1 to 5 a = new Object() 'Do stuff ' a = Nothing NextCatchFinally a = NothingEnd Try Do i need to do the a=Nothing in the loop or will the garbage collector clean a up? | In .NET, you generally do not need to set a variable reference = Nothing ( null in C#). The garbage collector will clean up, eventually. The reference itself will be destroyed when it goes out of scope (either when your method exits or when the object of this class is finalized.) Note that this doesn't mean the object is destroyed, just the reference to it. The object will still be destroyed non-deterministically by the collector. However, setting your reference = Nothing will provide a hint to .NET that the object may be garbage, and doesn't necessarily hurt anything -- aside from code clutter. If you were to keep it in there, I'd recommend removing it from Try block; it's already in the Finally block and will therefore always be called. (Aside from certain catastrophic exceptions; but in those cases it wouldn't get called in the Try block either!) Finally, I have to admit that I agree with Greg: Your code would be cleaner without this. The hint to the runtime that you're done with the reference is nice, but certainly not critical. Honestly, if I saw this in a code review, I'd probably have the developer rewrite it thusly: Dim a as ObjectDim i as Integer = 0For i=1 to 5 a = new Object() 'Do stuffNext | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1001650/"
]
} |
175,532 | I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I: return null throw an exception other Which is the best practise or idiom? | If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem. If the value can be missing or present and both are valid for the application logic then return a null. More important: What do you do other places in the code? Consistency is important. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/175532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
]
} |
175,554 | I need to convert an arbitrary amount of milliseconds into Days, Hours, Minutes Second. For example: 10 Days, 5 hours, 13 minutes, 1 second. | Well, since nobody else has stepped up, I'll write the easy code to do this: x = ms / 1000seconds = x % 60x /= 60minutes = x % 60x /= 60hours = x % 24x /= 24days = x I'm just glad you stopped at days and didn't ask for months. :) Note that in the above, it is assumed that / represents truncating integer division. If you use this code in a language where / represents floating point division, you will need to manually truncate the results of the division as needed. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/175554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
175,579 | What are they and how do they work? Context happens to be SQL Server | Both on Windows and POSIX systems, named-pipes provide a way for inter-process communication to occur among processes running on the same machine. What named pipes give you is a way to send your data without having the performance penalty of involving the network stack. Just like you have a server listening to a IP address/port for incoming requests, a server can also set up a named pipe which can listen for requests. In either cases, the client process (or the DB access library) must know the specific address (or pipe name) to send the request. Often, a commonly used standard default exists (much like port 80 for HTTP, SQL server uses port 1433 in TCP/IP; \\.\pipe\sql\query for a named pipe). By setting up additional named pipes, you can have multiple DB servers running, each with its own request listeners. The advantage of named pipes is that it is usually much faster, and frees up network stack resources. --BTW, in the Windows world, you can also have named pipes to remote machines -- but in that case, the named pipe is transported over TCP/IP, so you will lose performance. Use named pipes for local machine communication. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/175579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
175,655 | We recently had a problem where, after a series of commits had occurred, a backend process failed to run. Now, we were good little boys and girls and ran rake test after every check-in but, due to some oddities in Rails' library loading, it only occurred when we ran it directly from Mongrel in production mode. I tracked the bug down and it was due to a new Rails gem overwriting a method in the String class in a way that broke one narrow use in the runtime Rails code. Anyway, long story short, is there a way, at runtime, to ask Ruby where a method has been defined? Something like whereami( :foo ) that returns /path/to/some/file.rb line #45 ? In this case, telling me that it was defined in class String would be unhelpful, because it was overloaded by some library. I cannot guarantee the source lives in my project, so grepping for 'def foo' won't necessarily give me what I need, not to mention if I have many def foo 's, sometimes I don't know until runtime which one I may be using. | This is really late, but here's how you can find where a method is defined: http://gist.github.com/76951 # How to find out where a method comes from.# Learned this from Dave Thomas while teaching Advanced Ruby Studio# Makes the case for separating method definitions into# modules, especially when enhancing built-in classes.module Perpetrator def crime endendclass Fixnum include Perpetratorendp 2.method(:crime) # The "2" here is an instance of Fixnum.#<Method: Fixnum(Perpetrator)#crime> If you're on Ruby 1.9+, you can use source_location require 'csv'p CSV.new('string').method(:flock)# => #<Method: CSV#flock>CSV.new('string').method(:flock).source_location# => ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180] Note that this won't work on everything, like native compiled code. The Method class has some neat functions, too, like Method#owner which returns the file where the method is defined. EDIT: Also see the __file__ and __line__ and notes for REE in the other answer, they're handy too. -- wg | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/175655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590/"
]
} |
175,689 | I know you can use C++ keyword 'explicit' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method? I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function with an int, the compiler converted the param to a bool and called the wrong method. I know eventually I'll replace the bool, but for now don't want to break the other routines as this new routine is developed. | No, you can't use explicit, but you can use a templated function to catch the incorrect parameter types. With C++11 , you can declare the templated function as delete d. Here is a simple example: #include <iostream>struct Thing { void Foo(int value) { std::cout << "Foo: value" << std::endl; } template <typename T> void Foo(T value) = delete;}; This gives the following error message if you try to call Thing::Foo with a size_t parameter: error: use of deleted function ‘void Thing::Foo(T) [with T = long unsigned int]’ In pre-C++11 code, it can be accomplished using an undefined private function instead. class ClassThatOnlyTakesBoolsAndUIntsAsArguments{public: // Assume definitions for these exist elsewhere void Method(bool arg1); void Method(unsigned int arg1); // Below just an example showing how to do the same thing with more arguments void MethodWithMoreParms(bool arg1, SomeType& arg2); void MethodWithMoreParms(unsigned int arg1, SomeType& arg2);private: // You can leave these undefined template<typename T> void Method(T arg1); // Below just an example showing how to do the same thing with more arguments template<typename T> void MethodWithMoreParms(T arg1, SomeType& arg2);}; The disadvantage is that the code and the error message are less clear in this case, so the C++11 option should be selected whenever available. Repeat this pattern for every method that takes the bool or unsigned int . Do not provide an implementation for the templatized version of the method. This will force the user to always explicitly call the bool or unsigned int version. Any attempt to call Method with a type other than bool or unsigned int will fail to compile because the member is private, subject to the standard exceptions to visibility rules, of course (friend, internal calls, etc.). If something that does have access calls the private method, you will get a linker error. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16496/"
]
} |
175,695 | How can I represent the following in XSD. <price-update> <![CDATA[ arbitrary data goes here ]]></price-update> | <element name="price-update" type="string"></element> is about as close as you can get. (I thought it best to move the answer out of the comments and into an actual answer). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21297/"
]
} |
175,703 | In Enterprise Manager you could script all SPs in a database through the right click menu, is there a way to do it in Management Studio? | You can right click on the database and to go Tasks -> Generate Scripts... This will allow you to script all or selected objects (schema, stored procedures, tables, users and views) with specific options. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1302/"
]
} |
175,739 | I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function? | 2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point " . ": function isNumeric(str) { if (typeof str != "string") return false // we only process strings! return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)... !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail} To check if a variable (including a string) is a number, check if it is not a number: This works regardless of whether the variable content is a string or number. isNaN(num) // returns true if the variable does NOT contain a valid number Examples isNaN(123) // falseisNaN('123') // falseisNaN('1e10000') // false (This translates to Infinity, which is a number)isNaN('foo') // trueisNaN('10px') // trueisNaN('') // falseisNaN(' ') // falseisNaN(false) // false Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave: function isNumeric(num){ return !isNaN(num)} To convert a string containing a number into a number: Only works if the string only contains numeric characters, else it returns NaN . +num // returns the numeric value of the string, or NaN // if the string isn't purely numeric characters Examples +'12' // 12+'12.' // 12+'12..' // NaN+'.12' // 0.12+'..12' // NaN+'foo' // NaN+'12px' // NaN To convert a string loosely to a number Useful for converting '12px' to 12, for example: parseInt(num) // extracts a numeric value from the // start of the string, or NaN. Examples parseInt('12') // 12parseInt('aaa') // NaNparseInt('12px') // 12parseInt('foo2') // NaN These last three mayparseInt('12a5') // 12 be different from whatparseInt('0x10') // 16 you expected to see. Floats Bear in mind that, unlike +num , parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead ): +'12.345' // 12.345parseInt(12.345) // 12parseInt('12.345') // 12 Empty strings Empty strings may be a little counter-intuitive. +num converts empty strings or strings with spaces to zero, and isNaN() assumes the same: +'' // 0+' ' // 0isNaN('') // falseisNaN(' ') // false But parseInt() does not agree: parseInt('') // NaNparseInt(' ') // NaN | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/175739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
]
} |
175,785 | I have a form with a textarea. Users enter a block of text which is stored in a database. Occasionally a user will paste text from Word containing smart quotes or emdashes. Those characters appear in the database as: –, ’, “ ,†What function should I call on the input string to convert smart quotes to regular quotes and emdashes to regular dashes ? I am working in PHP. Update: Thanks for all of the great responses so far. The page on Joel's site about encodings is very informative: http://www.joelonsoftware.com/articles/Unicode.html Some notes on my environment: The MySQL database is using UTF-8 encoding. Likewise, the HTML pages that display the content are using UTF-8 (Update:) by explicitly setting the meta content-type. On those pages the smart quotes and emdashes appear as a diamond with question mark. Solution: Thanks again for the responses. The solution was twofold: Make sure the database and HTMLfiles were explicitly set to useUTF-8 encoding. Use htmlspecialchars() instead of htmlentities() . | This sounds like a Unicode issue. Joel Spolsky has a good jumping off point on the topic: http://www.joelonsoftware.com/articles/Unicode.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
]
} |
175,836 | When using the .NET WebBrowser control how do you open a link in a new window using the the same session (ie.. do not start a new ASP.NET session on the server), or how do you capture the new window event to open the URL in the same WebBrowser control? | I just spent an hour looking for the answer, so I though I would post the results here. You can use the SHDocVwCtl.WebBrowser_V1 object to capture the NewWindow event. NOTE: Code from http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_21484555.html#discussion //-------------------------------VB.NET Version:-------------------------------Dim WithEvents Web_V1 As SHDocVwCtl.WebBrowser_V1Private Sub Form_Load() Set Web_V1 = WebBrowser1.ObjectEnd SubPrivate Sub Web_V1_NewWindow(ByVal URL As String, ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, Processed As Boolean) Processed = True WebBrowser1.Navigate URLEnd Sub//-------------------------------C# Version-------------------------------private SHDocVw.WebBrowser_V1 Web_V1; //Interface to expose ActiveX methodsprivate void Form1_Load(object sender, EventArgs e){ //Setup Web_V1 interface and register event handler Web_V1 = (SHDocVw.WebBrowser_V1)this.webBrowser1.ActiveXInstance; Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow);}private void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData,string Headers, ref bool Processed){ Processed = true; //Stop event from being processed //Code to open in same window this.webBrowser1.Navigate(URL); //Code to open in new window instead of same window //Form1 Popup = new Form1(); //Popup.webBrowser1.Navigate(URL); //Popup.Show();} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17373/"
]
} |
175,845 | I have a repeater control where in the footer I have a DropDownList. In my code-behind I have: protected void ddMyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e){ if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // Item binding code } else if (e.Item.ItemType == ListItemType.Footer) { DropDownList ddl = e.Item.FindDropDownList("ddMyDropDownList"); // Fill the list control ddl.SelectedIndexChanged += new EventHandler(ddMyDropDownList_SelectedIndexChanged); ddl.AutoPostBack = true; } } The page appear to PostBack however my EventHandler does not get called. Any ideas? | If you just want to fire the OnSelectedIndexChanged, this is how it should look: Page.aspx - Source <FooterTemplate> <asp:DropDownList ID="ddlOptions" runat="server" AutoPostBack="true" onselectedindexchanged="ddlOptions_SelectedIndexChanged"> <asp:ListItem>Option1</asp:ListItem> <asp:ListItem>Option2</asp:ListItem> </asp:DropDownList></FooterTemplate> Page.aspx.cs - Code-behind protected void ddlOptions_SelectedIndexChanged(object sender, EventArgs e) { //Event Code here. } And that's it. Nothing more is needed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3111/"
]
} |
175,857 | How do you protect your commercial application from being installed on multiple computers from people who only own one license? Do you think it's a good idea to have more than just a serial based scheme? | The following method works well, as long as you have a public server at your disposal: Serial based protection, user must enter a serial before using the program On first serial entry, bind the serial to the MAC address and create an auth code generated from both of these values. Check with your server to make sure the serial and MAC can be bound to eachother. Register the MAC on the server. On each subsequent run, never contact the server again, but each time make sure the serial + MAC address matches their auth code. If the user has no MAC address, allow them to run the program as long as they have a serial. This gives you protection against someone simply copying the registry from one computer to another. If the user tries to install with the same serial on another computer, the server will not allow you to bind the serial number to the MAC address because it is already bound. It is not a perfect solution but it protects you 99% of the time. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
175,881 | When I try to install a new instance of SQL Server 2008 Express on a development machine with SQL 2005 Express already up and running, the install validation fails because the "SQL 2005 Express tools" are installed and I'm told to remove them. What exactly does that mean? After reading this article: http://www.asql.biz/Articoli/SQLX08/Art1_5.aspx I uninstalled the 2005 version of the SQL Management Studio but received the same error from the 2008 installer during my follow-up attempt. Updates 1) Uninstalled the SQL 2005 Management Studio only. Received the same error from the 2008 install. 2) Removed all SQL 2005 common components. Received the same error from the 2008 install. 3) Installed the shared components from the SQL 2008 installation program. Received the same error from the 2008 install when trying to install the new SQL 2008 instance. 4) Uninstalled SQL 2008 components, rebooted, re-installed SQL 2005 Management Studio from installation media, rebooted, un-installed SQL 2005 Workstation Components from Control Panel, re-booted. Installation of SQL 2008 is now proceeding as it should. Seems likely that if I'd re-booted after update 2 above things would have gone more smoothly. :-( | Although you should have no problem running a 2005 instance of the database engine beside a 2008 instance, The tools are installed into a shared directory, so you can't have two versions of the tools installed. Fortunately, the 2008 tools are backwards-compatible. As we speak, I'm using SSMS 2008 and Profiler 2008 to manage my 2005 Express instances. Works great. Before installing the 2008 tools, you need to remove any and all "shared" components from 2005. Try going to your Add/Remove programs control panel, find Microsoft SQL Server 2005, and click "Change." Then choose "Workstation Components" and remove everything there (this will not remove your database engine). I believe the 2008 installer also has an option to upgrade shared components only. You might try that. Good luck! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260/"
]
} |
175,882 | Now there's something I always wondered: how is sleep() implemented ? If it is all about using an API from the OS, then how is the API made ? Does it all boil down to using special machine-code on the CPU ? Does that CPU need a special co-processor or other gizmo without which you can't have sleep() ? The best known incarnation of sleep() is in C (to be more accurate, in the libraries that come with C compilers, such as GNU's libc), although almost every language today has its equivalent, but the implementation of sleep in some languages (think Bash) is not what we're looking at in this question... EDIT: After reading some of the answers, I see that the process is placed in a wait queue. From there, I can guess two alternatives, either a timer is set so that the kernel wakes the process at the due time, or whenever the kernel is allowed a time slice, it polls the clock to check whether it's time to wake a process. The answers only mention alternative 1. Therefore, I ask: how does this timer behave ? If it's a simple interrupt to make the kernel wake the process, how can the kernel ask the timer to "wake me up in 140 milliseconds so I can put the process in running state" ? | The "update" to question shows some misunderstanding of how modern OSs work. The kernel is not "allowed" a time slice. The kernel is the thing that gives out time slices to user processes. The "timer" is not set to wake the sleeping process up - it is set to stop the currently running process. In essence, the kernel attempts to fairly distribute the CPU time by stopping processes that are on CPU too long. For a simplified picture, let's say that no process is allowed to use the CPU more than 2 milliseconds. So, the kernel would set timer to 2 milliseconds, and let the process run. When the timer fires an interrupt, the kernel gets control. It saves the running process' current state (registers, instruction pointer and so on), and the control is not returned to it. Instead, another process is picked from the list of processes waiting to be given CPU, and the process that was interrupted goes to the back of the queue. The sleeping process is simply not in the queue of things waiting for CPU. Instead, it's stored in the sleeping queue. Whenever kernel gets timer interrupt, the sleep queue is checked, and the processes whose time have come get transferred to "waiting for CPU" queue. This is, of course, a gross simplification. It takes very sophisticated algorithms to ensure security, fairness, balance, prioritize, prevent starvation, do it all fast and with minimum amount of memory used for kernel data. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
]
} |
175,951 | Among other text and visual aids on a form submission, post-validation, I'm coloring my input boxes red to signify the interactive area needing attention. On Chrome (and for Google Toolbar users) the auto-fill feature re-colors my input forms yellow. Here's the complex issue: I want auto-complete allowed on my forms, as it speeds users logging in. I am going to check into the ability to turn the autocomplete attribute to off if/when there's an error triggered, but it is a complex bit of coding to programmatically turn off the auto-complete for the single affected input on a page. This, to put it simply, would be a major headache. So to try to avoid that issue, is there any simpler method of stopping Chrome from re-coloring the input boxes? [edit] I tried the !important suggestion below and it had no effect. I have not yet checked Google Toolbar to see if the !important attribute would work for that. As far as I can tell, there isn't any means other than using the autocomplete attribute (which does appear to work). | I know in Firefox you can use the attribute autocomplete="off" to disable the autocomplete functionality. If this works in Chrome (haven't tested), you could set this attribute when an error is encountered. This can be used for both a single element <input type="text" name="name" autocomplete="off"> ...as well as for an entire form <form autocomplete="off" ...> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/175951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486915/"
]
} |
175,961 | List<tinyClass> ids = new List<tinyClass();ids.Add(new tinyClass(1, 2));bool b = ids.IndexOf(new tinyClass(1, 2)) >= 0; //true or false? If it compares by value, it should return true; if by reference, it will return false. If it compares by reference, and I make tinyClass a struct - will that make a difference? | From MSDN: This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list. The Default property checks whether type T implements the System.IEquatable<T> generic interface and if so returns an EqualityComparer<T> that uses that implementation. Otherwise it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T. It seems like it uses the Equals method, unless the stored class implements the IEquatable<T> interface. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8435/"
]
} |
175,962 | How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+: DECLARE @count intSET @count = 20SELECT TOP @count * FROM SomeTable | SELECT TOP (@count) * FROM SomeTable This will only work with SQL 2005+ | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/175962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769/"
]
} |
175,982 | I have a copy of emacs that I use on a couple of different (windows) computers from a thumb drive, and I am wondering if it is possible to create something that is sort of the equivalent of a bash alias or symlink within emacs? Something that I could use within find-file is the main thing that i'm looking for, so for example: C-f <some link> would take me somewhere. Currently I have to add a new defun every time i get to a new computer, which is just kind of a pain and I would swear i've seen this somewhere, but months of googling have turned up nothing. What i've got right now is something like: (defun go-awesome () "Find my way to my work home" (interactive) (find-file "c:/cygwin/home/awesome")) But that feels increadibly overdone and hacky for just visiting a fairly hacky for just visiting a file that i visit semi-regularly. And it requires a lot of effort to set up a new file. The biggest problem with it though, in my opinion is that it doesn't fit in my workflow. When i want to visit a file i always do C-x C-f , and if i realize that "hey i'm at work" i then have to C-g M-x go-awesome . Perhaps it would be more clear if i said that i wanted to be able to do something that is the equivalent of an ln -s /some/awesome/dir but internal to emacs, instead of built into the OS, so that C-x C-f ~/awesome/some/sub/dir would work on windows or anywhere else. | I'm not really clear on what you're asking for. I store my commonly-used files in registers in my .emacs: (set-register ?c '(file . "c:/data/common.txt"))(set-register ?f '(file . "c:/data/frequent.txt")) Then I can jump to a file with jump-to-register ( C-x r j ): For example, " C-x r j c " takes me to c:/data/common.txt (loading it if necessary). Is that what you're looking for? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25616/"
]
} |
175,993 | After making some changes in my models (eg. new field in a model and a new model) what is the best way of reflecting these changes to my populated database? PS: I wanted to see many solutions in one place rated. Apparently more solutions are already listed here . | I've asked a similar question here and got quite a few answers. There are quite a lot of ways of doing it, like manually doing the dumping and reloading with SQL, using fixtures or using one of the "emerging" schema-evolution packages for Django: Django Evolution South dmigrations (there's a DjangoCon video of a panel on schema-evolution in Django where these 3 solutions are discussed) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/175993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785/"
]
} |
175,994 | I have written an HTML Application (hta file) and am wondering if there is a way to embed an icon file into the hta file itself. I have seen html emails that include embedded graphic files, is there any way to do this with html applications and icons? HTA files have an HTA:APPLICATION tag that allows you to specify an icon, but I want to have only a single file for download. I don't want to have an external icon file. Is this possible? More info on hta files here: HTA files . | I've found an hack to set the icon. Prepare an icon file icon.ico and an hta file source.hta with the following contents: <HTML><HEAD> <SCRIPT> path = document.URL; document.write( '<HTA:APPLICATION ID="oHTA" APPLICATIONNAME="myApp" ICON="'+path+'">'); </SCRIPT></HEAD><BODY SCROLL="no"> Hello, World!</BODY></HTML> Open a command prompt and type: copy /b icon.ico+source.hta iconapp.hta That will concatenate the icon and hta into a single file. In my test case Internet explorer skipped over the icon data and display the HTML correctly. The path of the icon is then set to that of the .hta file itself using javascript and the icon is loaded. I have tested this on Windows XP SP3, Internet explorer 8. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/175994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20848/"
]
} |
176,011 | If you are creating a 1d array, you can implement it as a list, or else use the 'array' module in the standard library. I have always used lists for 1d arrays. What is the reason or circumstance where I would want to use the array module instead? Is it for performance and memory optimization, or am I missing something obvious? | Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time . If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays , in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t ). The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl ). array.array is also a reasonable way to represent a mutable string in Python 2.x ( array('B', bytes) ). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray . However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays. To make a long story short : array.array is useful when you need a homogeneous C array of data for reasons other than doing math . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/176011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
]
} |
176,013 | What do you recommend for setting up a shared server with php from a security/performance point of view? Apache mod_php (how do you secure that? other than safe_mode as it won't be in PHP6) Apache CGI + suexec Lighttpd and spawn a FastCGI per user LE: I'm not interested in using an already made control panel as i'm trying to write my own so i want to know what's the best way to setup this myself.I was thinking in using Lighttpd and spawn a fastcgi for every hosted user making the fcgi process run under his credentials (there is a tutorial for this on lighttpd wiki).This would be somewhat secure but would this affect performance (lots of users / memory needed for every fcgi) so much that it's not a viable solution? | Personally, while Lighttpd is OK, I would go with Nginx + FastCGI if you end up going with a lightweight webserver + FastCGI solution. I've run benchmarks and read all the code, and Nginx is an order of magnitude faster/more stable under load -- it's very good. But, that's not what you asked. Essentially, I would say there's a spectrum of security/scaleability vs. speed tradeoffs in the three options you list, and you just need to decide where you want to be. If you're a shared hosting provider with untrusted users installing god-knows-what PHP apps you'll lean more toward security, if this is shared amongst more trusted users you might lean toward performance. Here are my thoughts: CGI + suexec: This is by far the most secure, and most efficient/scaleable for you in terms of numbers of users/sites in a shared hosting environment. Processes are spawned and memory used only as requests come in. Of course, the CGI-spawning makes this the slowest for execution time of individual scripts. How much slower? Well you would have to benchmark, but generally if people are running long-running apps (i.e. something like WordPress which takes 0.25-0.5 seconds just to load its libs and initialize on each request), then the CGI-spawning penalty starts to look pretty negligible in context. FastCGI: The issue here (and it doesn't matter if your webserver is Apache, Lighttpd or Nginx) is figuring out how many FCGI child processes you let each user leave running, because each process eats memory equal to the size of the PHP interpreter (in Linux not all of it is wired of course, but I digress). And, unlike mod_php, these processes aren't shared among users so you have to limit per user. For instance, Dreamhost caps this at 3 for their customers -- now, for a customer running a website that gets bursts of more than 2-5 page views a second, that's actually pretty bad because those requests just stack up and the site hangs. Now, I like FastCGI with a lightweight webserver when I'm running apps on a dedicated server/cluster, when I can give the app hundreds of FCGI children (all with webserver privs of course, à la Apache/prefork + mod_php). But, I don't think it makes sense for shared hosting where you have to allocate/cap the FCGI children per user. Apache + mod_php: Least secure since everything running with webserver privs, but your pool of live PHP processes is shared so it's best on the performance end. From a developer perspective, I can't tolerate php_safe mode, and from a sysadmin perspective it's really only an illusion of security (it mitigates against stupid users but doesn't protect from an actual attack) so I would actually rather have CGI if my other option has to include safe_mode. Dreamhost does sort of a hybrid, they do Apache CGI + suexec by default, but let the (small) percentage of their more users who are sophisticated elect to do FCGI if they want to, subject to a cap and their own monitoring of memory usage. That saves a ton of memory resources versus enabling FCGI for everyone by default. Another issue if you're talking about standard commercial shared hosting is, Apache is full-featured, has modules for just about anything (including stuff like mod_security you might want), and your users will like it because all their .htaccess configs will work etc. -- you will run into support headaches with anything else when they go to install Drupal or WordPress or whatever (a lot less of an issue if we're talking internal users). Personally I would recommend just keeping it simple to start and going with CGI + suexec for best security and scaleability. If your users want FCGI or mod_php and you have a good channel open for suggestions/communication with them, they'll ask for it, but either of these are a much bigger headache for you with only marginal performance improvements for them, so my suggestion would be to not do either of them initially but be responsive if they clamor for it. I do sympathize with the desire to do something "interesting" like Lighttpd + FCGI instead of the standard Apache + CGI + suexec, but I deep down I really can't recommend it. If you're running multiple servers, you could end up putting CGI on some and something else for the power users on the others. And be sure to have cron grep all the www dirs for things like old-ass versions of phpBB! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
]
} |
176,038 | I'm trying to access the Reporting Services via Web Services in my Visual Studio 2008 Application. How/where can I find my WSDL? | The following example shows the format of the URL to the Reporting Services management WSDL file: http://server/reportserver/ReportService2005.asmx?wsdl | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
]
} |
176,106 | I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction. I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible? [C# and .net 3.5 by the way] List of USPS State Abbreviations | I like something like this: private static String states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|";public static bool isStateAbbreviation (String state){ return state.Length == 2 && states.IndexOf( state ) > 0;} This method has the advantage of using an optimized system routine that is probably using a single machine instruction to do the search. If I was dealing with non-fixed length words, then I'd check for "|" + state + "|" to ensure that I hadn't hit a substring instead of full match. That would take a wee bit longer, due to the string concatenation, but it would still match in a fixed amount of time. If you want to validate lowercase abbreviations as well as uppercase, then either check for state.UpperCase(), or double the 'states' string to include the lowercase variants. I'll guarantee that this will beat the Regex or Hashtable lookups every time, no matter how many runs you make, and it will have the least memory usage. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506/"
]
} |
176,118 | Apparently there's a lot of variety in opinions out there, ranging from, " Never! Always encapsulate (even if it's with a mere macro!) " to " It's no big deal – use them when it's more convenient than not. " So. Specific, concrete reasons (preferably with an example) Why global variables are dangerous When global variables should be used in place of alternatives What alternatives exist for those that are tempted to use global variables inappropriately While this is subjective, I will pick one answer (that to me best represents the love/hate relationship every developer should have with globals) and the community will vote theirs to just below. I believe it's important for newbies to have this sort of reference, but please don't clutter it up if another answer exists that's substantially similar to yours – add a comment or edit someone else's answer. | Variables should always have a smaller scope possible. The argument behind that is that every time you increase the scope, you have more code that potentially modifies the variable, thus more complexity is induced in the solution. It is thus clear that avoiding using global variables is preferred if the design and implementation naturally allow that. Due to this, I prefer not to use global variables unless they are really needed. I can not agree with the 'never' statement either. Like any other concept, global variables are something that should be used only when needed. I would rather use global variables than using some artificial constructs (like passing pointers around), which would only mask the real intent. Some good examples where global variables are used are singleton pattern implementations or register access in embedded systems. On how to actually detect excessive usages of global variables: inspection, inspection, inspection. Whenever I see a global variable I have to ask myself: Is that REALLY needed at a global scope? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/176118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
} |
176,131 | New school datastore paradigms like Google BigTable and Amazon SimpleDB are specifically designed for scalability, among other things. Basically, disallowing joins and denormalization are the ways this is being accomplished. In this topic, however, the consensus seems to be that joins on large tables don't necessarilly have to be too expensive and denormalization is "overrated" to some extentWhy, then, do these aforementioned systems disallow joins and force everything together in a single table to achieve scalability? Is it the sheer volumes of data that needs to be stored in these systems (many terabytes)? Do the general rules for databases simply not apply to these scales?Is it because these database types are tailored specifically towards storing many similar objects? Or am I missing some bigger picture? | Distributed databases aren't quite as naive as Orion implies; there has been quite a bit of work done on optimizing fully relational queries over distributed datasets. You may want to look at what companies like Teradata, Netezza, Greenplum, Vertica, AsterData, etc are doing. (Oracle got in the game, finally, as well, with their recent announcement; Microsoft bought their solition in the name of the company that used to be called DataAllegro). That being said, when the data scales up into terabytes, these issues become very non-trivial. If you don't need the strict transactionality and consistency guarantees you can get from RDBMs, it is often far easier to denormalize and not do joins. Especially if you don't need to cross-reference much. Especially if you are not doing ad-hoc analysis, but require programmatic access with arbitrary transformations. Denormalization is overrated. Just because that's what happens when you are dealing with a 100 Tera, doesn't mean this fact should be used by every developer who never bothered to learn about databases and has trouble querying a million or two rows due to poor schema planning and query optimization. But if you are in the 100 Tera range, by all means... Oh, the other reason these technologies are getting the buzz -- folks are discovering that some things never belonged in the database in the first place, and are realizing that they aren't dealing with relations in their particular fields, but with basic key-value pairs. For things that shouldn't have been in a DB, it's entirely possible that the Map-Reduce framework, or some persistent, eventually-consistent storage system, is just the thing. On a less global scale, I highly recommend BerkeleyDB for those sorts of problems. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5409/"
]
} |
176,137 | Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? I'm currently looking at Geotools but unfortunately the solution is not obvious. | No Library, No Nothing. Copy This! Using These Two Classes , You can Convert Degree(latitude/longitude) to UTM and Vice Versa! private class Deg2UTM{ double Easting; double Northing; int Zone; char Letter; private Deg2UTM(double Lat,double Lon) { Zone= (int) Math.floor(Lon/6+31); if (Lat<-72) Letter='C'; else if (Lat<-64) Letter='D'; else if (Lat<-56) Letter='E'; else if (Lat<-48) Letter='F'; else if (Lat<-40) Letter='G'; else if (Lat<-32) Letter='H'; else if (Lat<-24) Letter='J'; else if (Lat<-16) Letter='K'; else if (Lat<-8) Letter='L'; else if (Lat<0) Letter='M'; else if (Lat<8) Letter='N'; else if (Lat<16) Letter='P'; else if (Lat<24) Letter='Q'; else if (Lat<32) Letter='R'; else if (Lat<40) Letter='S'; else if (Lat<48) Letter='T'; else if (Lat<56) Letter='U'; else if (Lat<64) Letter='V'; else if (Lat<72) Letter='W'; else Letter='X'; Easting=0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180))/(1-Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180)))*0.9996*6399593.62/Math.pow((1+Math.pow(0.0820944379, 2)*Math.pow(Math.cos(Lat*Math.PI/180), 2)), 0.5)*(1+ Math.pow(0.0820944379,2)/2*Math.pow((0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180))/(1-Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180)))),2)*Math.pow(Math.cos(Lat*Math.PI/180),2)/3)+500000; Easting=Math.round(Easting*100)*0.01; Northing = (Math.atan(Math.tan(Lat*Math.PI/180)/Math.cos((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))-Lat*Math.PI/180)*0.9996*6399593.625/Math.sqrt(1+0.006739496742*Math.pow(Math.cos(Lat*Math.PI/180),2))*(1+0.006739496742/2*Math.pow(0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))/(1-Math.cos(Lat*Math.PI/180)*Math.sin((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))),2)*Math.pow(Math.cos(Lat*Math.PI/180),2))+0.9996*6399593.625*(Lat*Math.PI/180-0.005054622556*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+4.258201531e-05*(3*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2))/4-1.674057895e-07*(5*(3*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2))/4+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2)*Math.pow(Math.cos(Lat*Math.PI/180),2))/3); if (Letter<'M') Northing = Northing + 10000000; Northing=Math.round(Northing*100)*0.01; }}private class UTM2Deg{ double latitude; double longitude; private UTM2Deg(String UTM) { String[] parts=UTM.split(" "); int Zone=Integer.parseInt(parts[0]); char Letter=parts[1].toUpperCase(Locale.ENGLISH).charAt(0); double Easting=Double.parseDouble(parts[2]); double Northing=Double.parseDouble(parts[3]); double Hem; if (Letter>'M') Hem='N'; else Hem='S'; double north; if (Hem == 'S') north = Northing - 10000000; else north = Northing; latitude = (north/6366197.724/0.9996+(1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)-0.006739496742*Math.sin(north/6366197.724/0.9996)*Math.cos(north/6366197.724/0.9996)*(Math.atan(Math.cos(Math.atan(( Math.exp((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*( 1 - 0.006739496742*Math.pow((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996 )/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996)))*Math.tan((north-0.9996*6399593.625*(north/6366197.724/0.9996 - 0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996 )*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))-north/6366197.724/0.9996)*3/2)*(Math.atan(Math.cos(Math.atan((Math.exp((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996)))*Math.tan((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))-north/6366197.724/0.9996))*180/Math.PI; latitude=Math.round(latitude*10000000); latitude=latitude/10000000; longitude =Math.atan((Math.exp((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*( north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2* north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3)) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))*180/Math.PI+Zone*6-183; longitude=Math.round(longitude*10000000); longitude=longitude/10000000; } } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
]
} |
176,158 | Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements? For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find_if, count_if, or sort directly on this array. Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms. | You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,: int ary[100];// init ...std::sort(ary, ary+100); // sorts the arraystd::find(ary, ary+100, pred); find some element I think you'll find that most stuff works just as you would expect. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
]
} |
176,159 | In most modern IDEs, you can have Debug and Release build configurations, and you can quickly switch between them. In Delphi 7, this does not seem to be possible. I have to go to Project Settings and toggle optimization and all the debug information stuff manually. It would be great if there was a plugin or some such that handled this for me. Does anyone know of one? Any other suggestions? Edit: I can't upgrade to Delphi 2007 or 2009 as we have a large Delphi 7 codebase which would have to be converted. I agree that would be the best solution in theory though :P | You can very easily add project configurations, similar to what other IDEs offer, using Andreas Hausladen's great DDevExtensions IDE expert. Just make sure to download the 1.6 version from the link I mentioned, since later versions only work with Delphi 2009. The 1.6 version works with any Delphi version between 5 and 2007, inclusive. The expert adds a submenu under the Project menu, in case you can't find it at first. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
]
} |
176,195 | I am looking at starting a hosted CMS-like service for customers. As it would, it would require the customer to input text which would be served up to anyone that comes to visit their site. I am planning on using Markdown, possibly in combination with WMD (the live markdown preview that SO uses) for the big blocks of text. Now, should I be sanitizing their input for html? Given that there would only be a handful of people editing their 'CMS', all paying customers, should i be stripping out the bad HTML, or should I just let them run wild? After all, it is their 'site' Edit: The main reason as to why I would do it is to let them use their own javascript, and have their own css and divs and what not for the output | Why wouldn't you sanitize the input? If you don't, you're inviting calamity - to either your customer or yourself or both. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
]
} |
176,196 | Why is the following displayed different in Linux vs Windows? System.out.println(new String("¿".getBytes("UTF-8"), "UTF-8")); in Windows: ¿ in Linux: ¿ | System.out.println() outputs the text in the system default encoding, but the console interprets that output according to its own encoding (or "codepage") setting. On your Windows machine the two encodings seem to match, but on the Linux box the output is apparently in UTF-8 while the console is decoding it as a single-byte encoding like ISO-8859-1. Or maybe, as Jon suggested, the source file is being saved as UTF-8 and javac is reading it as something else, a problem that can be avoided by using Unicode escapes. When you need to output anything other than ASCII text, your best bet is to write it to a file using an appropriate encoding, then read the file with a text editor--consoles are too limited and too system-dependent. By the way, this bit of code: new String("¿".getBytes("UTF-8"), "UTF-8") ...has no effect on the output. All that does is encode the contents of the string to a byte array and decode it again, reproducing the original string--an expensive no-op. If you want to output text in a particular encoding, you need to use an OutputStreamWriter, like so: FileOutputStream fos = new FileOutputStream("out.txt");OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9518/"
]
} |
176,264 | What is the difference between a URL , a URI , and a URN ? | From RFC 3986 : A URI can be further classified as a locator, a name, or both. Theterm "Uniform Resource Locator" (URL) refers to the subset of URIsthat, in addition to identifying a resource, provide a means oflocating the resource by describing its primary access mechanism(e.g., its network "location"). The term "Uniform Resource Name"(URN) has been used historically to refer to both URIs under the"urn" scheme [RFC2141] , which are required to remain globally uniqueand persistent even when the resource ceases to exist or becomesunavailable, and to any other URI with the properties of a name. So all URLs are URIs, and all URNs are URIs - but URNs and URLs are different, so you can't say that all URIs are URLs. If you haven't already read Roger Pate's answer , I'd advise doing so as well. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/176264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041950/"
]
} |
176,267 | My current position is this: if I thoroughly test my ASP.NET applications using web tests (in my case via the VS.NET'08 test tools and WatiN, maybe) with code coverage and a broad spectrum of data, I should have no need to write individual unit tests, because my code will be tested in conjunction with the UI through all layers. Code coverage will ensure I'm hitting every functional piece of code (or reveal unused code) and I can provide data that will cover all reasonably expected conditions. However, if you have a different opinion, I'd like to know: What additional benefit does unit testing give that justifies the effort to include it in a project (keep in mind, I'm doing the web tests anyway, so in many cases, the unit tests would be covering code that web tests already cover). Can you explain your reasons in detail with concete examples? Too often I see responses like "that's not what it's meant for" or "it promotes higher quality" - which really doesn't address the practical question I have to face, which is, how can I justify - with tangible results - spending more time testing? | Code coverage will ensure I'm hitting every functional piece of code "Hit" does not mean "Testing" The problem with only doing web-testing is that it only ensures that you hit the code, and that it appears to be correct at a high-level. Just because you loaded the page, and it didn't crash, doesn't mean that it actually works correctly. Here are some things I've encountered where 'web tests' covered 100% of the code, yet completely missed some very serious bugs which unit testing would not have. The page loaded correctly from a cache, but the actual database was broken The page loaded every item from the database, but only displayed the first one - it appeared to be fine even though it failed completely in production because it took too long The page displayed a valid-looking number, which was actually wrong, but it wasn't picked up because 1000000 is easy to mistake for 100000 The page displayed a valid number by coincidence - 10x50 is the same as 25x20, but one is WRONG The page was supposed to add a log entry to the database, but that's not visible to the user so it wasn't seen. Authentication was bypassed to make the web-tests actually work, so we missed a glaring bug in the authentication code. It is easy to come up with hundreds more examples of things like this. You need both unit tests to make sure that your code actually does what it is supposed to do at a low level, and then functional/integration (which you're calling web) tests on top of those, to prove that it actually works when all those small unit-tested-pieces are chained together. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11314/"
]
} |
176,284 | Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL thats fed into it can be anything from http://www.domain.com to www.domain.com/path/script.php?=whatever Whats the best way to go about doing this? | parse_url turns a URL into an associative array: php > $foo = "http://www.example.com/foo/bar?hat=bowler&accessory=cane";php > $blah = parse_url($foo);php > print_r($blah);Array( [scheme] => http [host] => www.example.com [path] => /foo/bar [query] => hat=bowler&accessory=cane) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/176284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
176,316 | I would like to make the update of the web application as automated as possible. I'm looking for a tool that can compare two instances of a database and generate an update script for me. As part of the build process create a instance of the last version of the database (ie currently in production) and compare that to what has been changed on the development version. Any input is appreciated. | I like SqlDbDiff . Way cheaper than RedGate's SQL Compare | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11434/"
]
} |
176,343 | Perl 6 seems to have an explosion of equality operators. What is =:= ? What's the difference between leg and cmp ? Or eqv and === ? Does anyone have a good summary? | =:= tests if two containers (variables or items of arrays or hashes) are aliased, ie if one changes, does the other change as well? my $x;my @a = 1, 2, 3;# $x =:= @a[0] is false$x := @a[0];# now $x == 1, and $x =:= @a[0] is true$x = 4;# now @a is 4, 2, 3 As for the others: === tests if two references point to the same object, and eqv tests if two things are structurally equivalent. So [1, 2, 3] === [1, 2, 3] will be false (not the same array), but [1, 2, 3] eqv [1, 2, 3] will be true (same structure). leg compares strings like Perl 5's cmp , while Perl 6's cmp is smarter and will compare numbers like <=> and strings like leg . 13 leg 4 # -1, because 1 is smaller than 4, and leg converts to string13 cmp 4 # +1, because both are numbers, so use numeric comparison. Finally ~~ is the "smart match", it answers the question "does $x match $y ". If $y is a type, it's type check. If $y is a regex, it's regex match - and so on. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/176343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
176,347 | I read some of the answers on here re: testing views and controllers, and mocking, but I still can't figure out how to test an ASP.NET MVC controller that reads and sets Session values (or any other context based variables.)How do I provide a (Session) context for my test methods? Is mocking the answer? Anybody have examples?Basically, I'd like to fake a session before I call the controller method and have the controller use that session. Any ideas? | Check out Stephen Walther's post on Faking the Controller Context: ASP.NET MVC Tip #12 – Faking the Controller Context [TestMethod]public void TestSessionState(){ // Create controller var controller = new HomeController(); // Create fake Controller Context var sessionItems = new SessionStateItemCollection(); sessionItems["item1"] = "wow!"; controller.ControllerContext = new FakeControllerContext(controller, sessionItems); var result = controller.TestSession() as ViewResult; // Assert Assert.AreEqual("wow!", result.ViewData["item1"]); // Assert Assert.AreEqual("cool!", controller.HttpContext.Session["item2"]);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17729/"
]
} |
176,376 | Suppose I have a set of values, stored in a std::set: {1, 2, 6, 8} and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6. The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case? | Yes: upper_bound(X) returns an iterator pointing to the first element greater than X . There is also a lower_bound(X) function which returns an iterator pointing to the first element not less than X . Thus, all of the elements in the half-open interval [lower_bound(X), upper_bound(X)) will be equal to X. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
]
} |
176,379 | SQL Server 2005/2008 Express edition has the limitation of 4 GB per database. As far as I known the database engine considers data only, thus excluding log files, unused space, and index size. Getting the length of the MDF file should not give the correct database size in terms of SQL Server limitation. My question is how to get the database size? | sp_spaceused | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/176379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23372/"
]
} |
176,409 | I need to build a simple HTTP server in C. Any guidance? Links? Samples? | I suggest you take a look at tiny httpd . If you want to write it from scratch, then you'll want to thoroughly read RFC 2616 . Use BSD sockets to access the network at a really low level. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/176409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25645/"
]
} |
176,446 | Why do I get compiler errors with this Java code? 1 public List<? extends Foo> getFoos()2 {3 List<? extends Foo> foos = new ArrayList<? extends Foo>();4 foos.add(new SubFoo());5 return foos;6 } Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface. Errors I get with this code: On Line 3: "Cannot instantiate ArrayList<? extends Foo>" On Line 4: "The method add(capture#1-of ? extends Foo) in the type List<capture#1-of ? extends Foo> is not applicable for the arguments (SubFoo)" Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList<Foo>();". But I'm still having the issue with Line 4. | Use this instead: 1 public List<? extends Foo> getFoos()2 {3 List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */4 foos.add(new SubFoo());5 return foos;6 } Once you declare foos as List<? extends Foo> , the compiler doesn't know that it's safe to add a SubFoo. What if an ArrayList<AltFoo> had been assigned to foos ? That would be a valid assignment, but adding a SubFoo would pollute the collection. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197/"
]
} |
176,476 | I've been using htmldoc for a while, but I've run into some fairly serious limitations. I need the end solution to work on a Linux box. I'll be calling this library/utility/application from a Perl app, so any Perl interfaces would be a bonus. | Sorry to unearth this old post, but it came out first in my search for the best HTML/PDF conversion tool.On Linux wkhtmltopdf is very good (takes into account CSS, among others) and GPL. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2901/"
]
} |
176,514 | What is meant by nvarchar ? What is the difference between char , nchar , varchar , and nvarchar in SQL Server? | Just to clear up... or sum up... nchar and nvarchar can store Unicode characters. char and varchar cannot store Unicode characters. char and nchar are fixed-length which will reserve storage space for number of characters you specify even if you don't use up all that space. varchar and nvarchar are variable-length which will only use up spaces for the characters you store. It will not reserve storage like char or nchar . nchar and nvarchar will take up twice as much storage space, so it may be wise to use them only if you need Unicode support. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/176514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
]
} |
176,527 | I need to enumerate all classes in a package and add them to a List. The non-dynamic version for a single class goes like this: List allClasses = new ArrayList();allClasses.add(String.class); How can I do this dynamically to add all classes in a package and all its subpackages? Update: Having read the early answers, it's absolutely true that I'm trying to solve another secondary problem, so let me state it. And I know this is possible since other tools do it. See new question here . Update: Reading this again, I can see how it's being misread. I'm looking to enumerate all of MY PROJECT'S classes from the file system after compilation. | ****UPDATE 1 (2012)**** OK, I've finally gotten around to cleaning up the code snippet below. I stuck it into it's own github project and even added tests. https://github.com/ddopson/java-class-enumerator ****UPDATE 2 (2016)**** For an even more robust and feature-rich classpath scanner, see https://github.com/classgraph/classgraph . I'd recommend first reading my code snippet to gain a high level understanding, then using lukehutch's tool for production purposes. ****Original Post (2010)**** Strictly speaking, it isn't possible to list the classes in a package . This is because a package is really nothing more than a namespace (eg com.epicapplications.foo.bar), and any jar-file in the classpath could potentially add classes into a package. Even worse, the classloader will load classes on demand, and part of the classpath might be on the other side of a network connection. It is possible to solve a more restrictive problem. eg, all classes in a JAR file, or all classes that a JAR file defines within a particular package. This is the more common scenario anyways. Unfortunately, there isn't any framework code to make this task easy. You have to scan the filesystem in a manner similar to how the ClassLoader would look for class definitions. There are a lot of samples on the web for class files in plain-old-directories. Most of us these days work with JAR files. To get things working with JAR files, try this... private static ArrayList<Class<?>> getClassesForPackage(Package pkg) { String pkgname = pkg.getName(); ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); // Get a File object for the package File directory = null; String fullPath; String relPath = pkgname.replace('.', '/'); System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath); URL resource = ClassLoader.getSystemClassLoader().getResource(relPath); System.out.println("ClassDiscovery: Resource = " + resource); if (resource == null) { throw new RuntimeException("No resource for " + relPath); } fullPath = resource.getFile(); System.out.println("ClassDiscovery: FullPath = " + resource); try { directory = new File(resource.toURI()); } catch (URISyntaxException e) { throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e); } catch (IllegalArgumentException e) { directory = null; } System.out.println("ClassDiscovery: Directory = " + directory); if (directory != null && directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // we are only interested in .class files if (files[i].endsWith(".class")) { // removes the .class extension String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); System.out.println("ClassDiscovery: className = " + className); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } else { try { String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> entries = jarFile.entries(); while(entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); if(entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) { System.out.println("ClassDiscovery: JarEntry: " + entryName); String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); System.out.println("ClassDiscovery: className = " + className); try { classes.add(Class.forName(className)); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } catch (IOException e) { throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e); } } return classes;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13041/"
]
} |
176,559 | In the Google C++ Style Guide, there's a section on Operator Overloading that has a curious statement: Overloading also has surprising ramifications. For instance, you can't forward declare classes that overload operator& . This seems incorrect, and I haven't been able to find any code that causes GCC to have a problem with it. Does anyone know what that statement is referring to? | 5.3.1 of the Standard has "The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator&() as a member function, then the behavior is undefined (and no diagnostic is required)." I didn't know this either, but as another poster has pointed out, it's easy to see how it could cause a compiler to generate incorrect code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
]
} |
176,572 | I have a UI widget that needs to be put in an IFRAME both for performance reasons and so we can syndicate it out to affiliate sites easily. The UI for the widget includes tool-tips that display over the top of other page content. See screenshot below or go to the site to see it in action. Is there any way to make content from within the IFRAME overlap the parent frame's content? | No it's not possible. Ignoring any historical reasons, nowadays it would be considered a security vulnerability -- eg. many sites put untrusted content into iframes (the iframe source being a different origin so cannot modify the parent frame, per the same origin policy). If such untrusted content had a mechanism to place content outside of the bounds of the iframe it could (for example) place an "identical" login div (or whatever) over a parent frame's real login fields, and could thus steal username/password information. Which would suck. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/176572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
]
} |
176,673 | If I have a datetime field, how do I get just records created later than a certain time, ignoring the date altogether? It's a logging table, it tells when people are connecting and doing something in our application. I want to find out how often people are on later than 5pm. (Sorry - it is SQL Server. But this could be useful for other people for other databases) | For SQL Server: select * from myTable where datepart(hh, myDateField) > 17 See http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22523/"
]
} |
176,695 | The attached screenshot is from OS X/Firefox 3. Note that the center tab (an image) has a dotted line around it, apparently because it was the most-recently selected tab. Is there a way I can eliminate this dotted line in CSS or JavaScript? (Hmmm...the free image hosting service has reduced the size of the image. But if you could see it, you'd notice a dotted-line select area around the block.) Screen Shot http://www.freeimagehosting.net/uploads/th.fadf78173b.png | You'll want to add the following line to your css: a:active, a:focus { outline-style: none; -moz-outline-style:none; } (Assuming your tabs are done using the a element, of course.) [edit] On request from everyone else, for future viewers of this it should be noted that the outline is essential for keyboard-navigators as it designates where your selection is and, so, gives a hint to where your next 'tab' might go. Thus, it's inadvisable to remove this dotted-line selection. But it is still useful to know how you would do it, if you deem it necessary. And as mentioned in a comment, if you are only dealing with FF > v1.5, feel free to leave out the -moz-outline-style:none; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
]
} |
176,712 | I'd like to find the base url of my application, so I can automatically reference other files in my application tree... So given a file config.php in the base of my application, if a file in a subdirectory includes it, knows what to prefix a url with. application/config.phpapplication/admin/something.phpapplication/css/style.css So given that http://www.example.com/application/admin/something.php is accessed, I want it to be able to know that the css file is in $approot/css/style.css . In this case, $approot is " /application " but I'd like it to know if the application is installed elsewhere. I'm not sure if it's possible, many applications (phpMyAdmin, Squirrelmail I think) have to set a config variable to begin with. It would be more user friendly if it just knew. | I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it. define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/');$tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));$tempPath2 = explode('/', substr(ABSPATH, 0, -1));$tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));for ($i = count($tempPath2); $i < count($tempPath1); $i++) array_pop ($tempPath3);$urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);if ($urladdr{strlen($urladdr) - 1}== '/') define('URLADDR', 'http://' . $urladdr);else define('URLADDR', 'http://' . $urladdr . '/');unset($tempPath1, $tempPath2, $tempPath3, $urladdr); The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod_rewrite situations. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14253/"
]
} |
176,720 | What is the easiest way to do this? Is it possible with managed code? | this.BackgroundImage = //Imagethis.FormBorderStyle = FormBorderStyle.None;this.Width = this.BackgroundImage.Width;this.Height = this.BackgroundImage.Height;this.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
]
} |
176,745 | Given an aggregation of class instances which refer to each other in a complex, circular, fashion: is it possible that the garbage collector may not be able to free these objects? I vaguely recall this being an issue in the JVM in the past, but I thought this was resolved years ago. yet, some investigation in jhat has revealed a circular reference being the reason for a memory leak that I am now faced with. Note: I have always been under the impression that the JVM was capable of resolving circular references and freeing such "islands of garbage" from memory. However, I am posing this question just to see if anyone has found any exceptions. | Only a very naive implementation would have a problem with circular references. Wikipedia has a good article on the different GC algorithms. If you really want to learn more, try (Amazon) Garbage Collection: Algorithms for Automatic Dynamic Memory Management . Java has had a good garbage collector since 1.2 and an exceptionally good one in 1.5 and Java 6. The hard part for improving GC is reducing pauses and overhead, not basic things like circular reference. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9931/"
]
} |
176,775 | Currently I am borrowing java.math.BigInteger from the J# libraries as described here . Having never used a library for working with large integers before, this seems slow, on the order of 10 times slower, even for ulong length numbers. Does anyone have any better (preferably free) libraries, or is this level of performance normal? | As of .NET 4.0 you can use the System.Numerics.BigInteger class. See documentation here: http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx Another alternative is the IntX class. IntX is an arbitrary precision integers library written in pure C# 2.0 with fast - O(N * log N) - multiplication/division algorithms implementation. It provides all the basic operations on integers like addition, multiplication, comparing, bitwise shifting etc. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/176775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
]
} |
176,820 | I need to index a whole lot of webpages, what good webcrawler utilities are there? I'm preferably after something that .NET can talk to, but that's not a showstopper. What I really need is something that I can give a site url to & it will follow every link and store the content for indexing. | HTTrack -- http://www.httrack.com/ -- is a very good Website copier. Works pretty good. Have been using it for a long time. Nutch is a web crawler(crawler is the type of program you're looking for) -- http://lucene.apache.org/nutch/ -- which uses a top notch search utility lucene. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
176,827 | I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up tag is not preferred). How do I prevent it from posting back to the server? | ASPX code: <asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton> Code behind: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { someID.Attributes.Add("onClick", "return false;"); }} What renders as HTML is: <a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a> In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/176827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417/"
]
} |
176,857 | I should probably take this for a forum but figured someone here might know the answer. I'm trying to install sql server 2008 on a home vista machine but it keeps telling 'Restart computer failed' everytime it does a check to make sure pre-reqs are met. I've restarted my computer and even uinstalled/installed .net 3.5 sp1. only thread i found about this was: http://forums.microsoft.com/msdn/showpost.aspx?postid=3656807&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=1 the last post on that forum states that there is a way to 'forcefully' (using command prompt) there is a way to bypass the reboot check. does anyone know what commands can be used to bypass the rebook check?? | Found this here: http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3762432&SiteID=1 "You can open Regedit, and modify this key"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager" and delete any value in "PendingFileRenameOperations"" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/176857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
176,858 | In a static view, how can I view an old version of a file? Given an empty file (called empty in this example) I can subvert diff to show me the old version: % cleartool diff -ser empty File@@/main/28 This feels like a pretty ugly hack. Have I missed a more basic command? Is there a neater way to do this? (I don't want to edit the config spec - that's pretty tedious, and I'm trying to look at a bunch of old versions.) Clarification : I want to send the version of the file to stdout, so I can use it with the rest of Unix (grep, sed, and so on.) If you found this question because you're looking for a way to save a version of an element to a file, see Brian's answer . | I'm trying to look at a bunch of old versions I am not sure if you are speaking about "a bunch of old versions" of one file , "a bunch of old versions" from several files. To visualize several old versions of one file, the simplest mean is to display its version tree ( ct lsvtree -graph File ), and then select a version, right-click on it and ' Send To ' an editor which accepts multiple files (like Notepad++). In a few click you will have a view of those old versions. Note: you must have CC6.0 or 7.0.1 IFix01 (7.0.0 and 7.0.1 fail to 'sent to' a file with the following error message " Access to unnamed file was denied ") But to visualize several old versions of different files, I would recommend a dynamic view and editing the config spec of that view (and not the snapshot view you are currently working with), in order to quickly select all those old files (hopefully through a simple select rule like ' element * aLabel ') [From the comments:] what's the idiomatic way to "cat" an earlier revision of a file? The idiomatic way is through a dynamic view (that you configure with the exact same config spec than your existing snapshot view). You can then browse (as in 'change directory to') the various extended paths of a file. If you want to cat all versions of a branch of a file, you go in: cd /view/MyView/vobs/myVobs/myPath/myFile@@/main/[...]/maBranchcat 1cat 2...cat x ' 1 ', ' 2 ', ... ' x ' being the version 1, 2, ... x of your file within that branch. For a snapshot view , the extended path is not accessible , so your "hack" is the way to go. However, 2 remarks here: to quickly display all previous revisions of a snapshot file in a given branch, you can type: (one line version for copy-paste, Unix syntax:) cleartool find addon.xml -ver 'brtype(aBranch) && !version(.../aBranch/LATEST) && ! version(.../aBranch/0)' -exec 'cleartool diff -ser empty "$CLEARCASE_XPN"' (multi-line version for readability:) cleartool find addon.xml -ver 'brtype(aBranch) && !version(.../aBranch/LATEST) && ! version(.../aBranch/0)' -exec 'cleartool diff -ser empty "$CLEARCASE_XPN"' you can quickly have an output a little nicer with (one line version for copy-paste, Unix syntax:) cleartool find addon.xml -ver 'brtype(aBranch) && !version(.../aBranch/LATEST) && ! version(.../aBranch/0)' -exec 'cleartool diff -ser empty "$CLEARCASE_XPN"' | ccperl -nle '$a=$_; $b = $a; $b =~ s/^>+\s(?:file\s+\d+:\s+)?//g;print $b if $a =~/^>/' (multi-line version for readability:) cleartool find addon.xml -ver 'brtype(aBranch) && !version(.../aBranch/LATEST) && ! version(.../aBranch/0)' -exec 'cleartool diff -ser empty "$CLEARCASE_XPN"'| ccperl -nle '$a=$_; $b = $a; $b =~ s/^>+\s(?:file\s+\d+:\s+)?//g; print $b if $a =~/^>/' That way, the output is nicer. The " cleartool get " command (man page) mentioned below by Brian don't do stdout: The get command copies only file elements into a view. On a UNIX or Linux system, copy /dev/hello_world/foo.c@@/main/2 into the current directory. cmd-context get –to foo.c.temp /dev/hello_world/foo.c@@/main/2 On a Windows system, copy \dev\hello_world\foo.c@@\main\2 into the C:\build directory. cmd-context get –to C:\build\foo.c.temp \dev\hello_world\foo.c@@\main\2 So maybe than, by piping the result to a cat (or type in windows), you can then do something with the output of said cat ( type ) command. cmd-context get –to C:\build\foo.c.temp \dev\hello_world\foo.c@@\main\2 | type C:\build\foo.c.temp | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17221/"
]
} |
176,918 | Given a list ["foo", "bar", "baz"] and an item in the list "bar" , how do I get its index 1 ? | >>> ["foo", "bar", "baz"].index("bar")1 Reference: Data Structures > More on Lists Caveats follow Note that while this is perhaps the cleanest way to answer the question as asked , index is a rather weak component of the list API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index follow. It is probably worth initially taking a look at the documentation for it: list.index(x[, start[, end]]) Return zero-based index in the list of the first item whose value is equal to x . Raises a ValueError if there is no such item. The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument. Linear time-complexity in list length An index call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999) , because the former only has to search 10 entries, while the latter searches a million: >>> import timeit>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)9.356267921015387>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)0.0004404920036904514 Only returns the index of the first match to its argument A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression. >>> [1, 1].index(1)0>>> [i for i, e in enumerate([1, 2, 1]) if e == 1][0, 2]>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)>>> next(g)0>>> next(g)2 Most places where I once would have used index , I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for index , take a look at these excellent Python features. Throws if element not present in list A call to index results in a ValueError if the item's not present. >>> [1, 1].index(2)Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: 2 is not in list If the item might not be present in the list, you should either Check for it first with item in my_list (clean, readable approach), or Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.) | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/176918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25680/"
]
} |
176,922 | For decades, in the field of computing (except disk manufacturers), a KB (kilobyte) was understood to mean 1024 bytes. In the past few years, there has been a movement to use KiB ("kibibyte") to mean 1024 bytes, and change the meaning of kilobyte to be 1000 bytes , dooming us to many more years of confusion. On the other hand, the movement seems to be confined to Gnome, and some overzealous wikipedia editing . Will you be converting your programs to use KiB? If you have ever displayed a filesize in KB, did you divide by 1000 or 1024? | KB is 1024 bytes, damnit. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/176922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15947/"
]
} |
176,931 | How can I get MSBuild to evaluate and print in a <Message /> task an absolute path given a relative path? Property Group <Source_Dir>..\..\..\Public\Server\</Source_Dir><Program_Dir>c:\Program Files (x86)\Program\</Program_Dir> Task <Message Importance="low" Text="Copying '$(Source_Dir.FullPath)' to '$(Program_Dir)'" /> Output Copying '' to 'c:\Program Files (x86)\Program\' | In MSBuild 4.0 , the easiest way is the following: $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)\your\path')) This method works even if the script is <Import> ed into another script; the path is relative to the file containing the above code. (consolidated from Aaron's answer as well as the last part of Sayed's answer ) In MSBuild 3.5 , you can use the ConvertToAbsolutePath task: <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Test" ToolsVersion="3.5"> <PropertyGroup> <Source_Dir>..\..\..\Public\Server\</Source_Dir> <Program_Dir>c:\Program Files (x86)\Program\</Program_Dir> </PropertyGroup> <Target Name="Test"> <ConvertToAbsolutePath Paths="$(Source_Dir)"> <Output TaskParameter="AbsolutePaths" PropertyName="Source_Dir_Abs"/> </ConvertToAbsolutePath> <Message Text='Copying "$(Source_Dir_Abs)" to "$(Program_Dir)".' /> </Target></Project> Relevant output: Project "P:\software\perforce1\main\XxxxxxXxxx\Xxxxx.proj" on node 0 (default targets). Copying "P:\software\Public\Server\" to "c:\Program Files (x86)\Program\". A little long-winded if you ask me, but it works. This will be relative to the "original" project file, so if placed inside a file that gets <Import> ed, this won't be relative to that file. In MSBuild 2.0 , there is an approach which doesn't resolve "..". It does however behave just like an absolute path: <PropertyGroup> <Source_Dir_Abs>$(MSBuildProjectDirectory)\$(Source_Dir)</Source_Dir_Abs></PropertyGroup> The $(MSBuildProjectDirectory) reserved property is always the directory of the script that contains this reference. This will also be relative to the "original" project file, so if placed inside a file that gets <Import> ed, this won't be relative to that file. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/176931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
]
} |
176,964 | I want to return top 10 records from each section in one query. Can anyone help with how to do it? Section is one of the columns in the table. Database is SQL Server 2005. I want to return the top 10 by date entered. Sections are business, local, and feature. For one particular date I want only the top (10) business rows (most recent entry), the top (10) local rows, and the top (10) features. | If you are using SQL 2005 you can do something like this... SELECT rs.Field1,rs.Field2 FROM ( SELECT Field1,Field2, Rank() over (Partition BY Section ORDER BY RankCriteria DESC ) AS Rank FROM table ) rs WHERE Rank <= 10 If your RankCriteria has ties then you may return more than 10 rows and Matt's solution may be better for you. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/176964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
]
} |
176,989 | In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0 . You could not assign NULL to any pointer other than void* , which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers. To this day, I have continued to use zero as a null pointer but those around me insist on using NULL . I personally do not see any benefit to giving a name ( NULL ) to an existing value - and since I also like to test pointers as truth values: if (p && !q) do_something(); then using zero makes more sense (as in if you use NULL , you cannot logically use p && !q - you need to explicitly compare against NULL , unless you assume NULL is zero, in which case why use NULL ). Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference? Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still. | Here's Stroustrup's take on this: C++ Style and Technique FAQ In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days. If you have to name the null pointer, call it nullptr ; that's what it's called in C++11. Then, nullptr will be a keyword. That said, don't sweat the small stuff. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/176989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23744/"
]
} |
176,992 | I'm developing in an environment that is severely constrained, but the developers also have tight control over. VCRedist_x86.exe - A 4Mb redistributable - is no fun (four hours to transfer). I'd really prefer to just redistribute MFC90.dll, msvcm90.dll, msvcp90.dll and msvcr90.dll - that's more like 2Mb. However, Redistributing Visual C++ Files says: It is not supported to redistribute C/C++ applications that are built without a manifest. Visual C++ libraries cannot be used by C/C++ applications without a manifest binding the application to these libraries. For more information, see Choosing a Deployment Method . My original plan of copying the DLLs into the program's working directory doesn't seem to work in this brave new world of manifests. My next guess is to bodge up the registry entries required to populate the files into the WinSxS directory and populate it myself (rather than using the 4 meg program). [edit] The software is frequently updated, so DLLs are strongly preferred to static linking. [/edit] How can I sucessfully distribute the necessary files but keep the overhead down? | We use this: Howto: Deploy VC2008 apps without installing vcredist_x86.exe Essentially Don't embed a manifest in your exe files. Copy the C++ DLLs and their manifests to your app's directory. Remove the "publicKeyToken" from all manifests (yours and Microsoft's). If necessary, change the version info in your app's manifest files to match the Microsoft manifest files (or vice versa) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/176992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257/"
]
} |
177,080 | Method signature in Java: public List<String> getFilesIn(List<File> directories) similar one in ruby def get_files_in(directories) In the case of Java, the type system gives me information about what the method expects and delivers. In Ruby's case, I have no clue what I'm supposed to pass in, or what I'll expect to receive. In Java, the object must formally implement the interface. In Ruby, the object being passed in must respond to whatever methods are called in the method defined here. This seems highly problematic: Even with 100% accurate, up-to-date documentation, the Ruby code has to essentially expose its implementation, breaking encapsulation. "OO purity" aside, this would seem to be a maintenance nightmare. The Ruby code gives me no clue what's being returned; I would have to essentially experiment, or read the code to find out what methods the returned object would respond to. Not looking to debate static typing vs duck typing, but looking to understand how you maintain a production system where you have almost no ability to design by contract. Update No one has really addressed the exposure of a method's internal implementation via documentation that this approach requires. Since there are no interfaces, if I'm not expecting a particular type, don't I have to itemize every method I might call so that the caller knows what can be passed in? Or is this just an edge case that doesn't really come up? | What it comes down to is that get_files_in is a bad name in Ruby - let me explain. In java/C#/C++, and especially in objective C, the function arguments are part of the name . In ruby they are not. The fancy term for this is Method Overloading , and it's enforced by the compiler. Thinking of it in those terms, you're just defining a method called get_files_in and you're not actually saying what it should get files in. The arguments are not part of the name so you can't rely on them to identify it. Should it get files in a directory? a drive? a network share? This opens up the possibility for it to work in all of the above situations. If you wanted to limit it to a directory, then to take this information into account, you should call the method get_files_in_directory . Alternatively you could make it a method on the Directory class, which Ruby already does for you . As for the return type, it's implied from get_files that you are returning an array of files. You don't have to worry about it being a List<File> or an ArrayList<File >, or so on, because everyone just uses arrays (and if they've written a custom one, they'll write it to inherit from the built in array). If you only wanted to get one file, you'd call it get_file or get_first_file or so on. If you are doing something more complex such as returning FileWrapper objects rather than just strings, then there is a really good solution: # returns a list of FileWrapper objectsdef get_files_in_directory( dir )end At any rate. You can't enforce contracts in ruby like you can in java, but this is a subset of the wider point, which is that you can't enforce anything in ruby like you can in java. Because of ruby's more expressive syntax, you instead get to more clearly write english-like code which tells other people what your contract is (therein saving you several thousand angle brackets). I for one believe that this is a net win. You can use your newfound spare time to write some specs and tests and come out with a much better product at the end of the day. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3029/"
]
} |
177,122 | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: Firstly : Given an established Perl project, what are some decent ways to speed it up beyond just plain in-code optimization? Secondly : When writing a program from scratch in Perl, what are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C? Please stay away from general optimization techniques unless they are Perl specific . I asked this about Python earlier, and I figured it might be good to do it for other languages (I'm especially curious if there are corollaries to psycho and pyrex for Perl). | Please remember the rules of Optimization Club: The first rule of Optimization Clubis, you do not Optimize. The second rule of Optimization Club is, you do not Optimize without measuring. If your app is running faster than the underlying transport protocol, the optimization is over. One factor at a time. No marketroids, no marketroid schedules. Testing will go on as long as it has to. If this is your first night at Optimization Club, you have to write a test case. So, assuming you actually have working code, run your program under Devel::NYTProf . Find the bottlenecks. Then come back here to tell us what they are. If you don't have working code, get it working first. The single biggest optimization you will ever make is going from non-working to working. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
]
} |
177,146 | How do I get the list of open file handles by process id in C#? I'm interested in digging down and getting the file names as well. Looking for the programmatic equivalent of what process explorer does. Most likely this will require interop. Considering adding a bounty on this, the implementation is nasty complicated. | Ouch this is going to be hard to do from managed code. There is a sample on codeproject Most of the stuff can be done in interop, but you need a driver to get the filename cause it lives in the kernel's address space. Process Explorer embeds the driver in its resources. Getting this all hooked up from C# and supporting 64bit as well as 32, is going to be a major headache. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
]
} |
177,161 | I need to get just the first item (actually, just the first key) off a rather large associative array in JavaScript. Here's how I'm doing it currently (using jQuery): getKey = function (data) { var firstKey; $.each(data, function (key, val) { firstKey = key; return false; }); return firstKey;}; Just guessing, but I'd say there's got to be a better (read: more efficient) way of doing this. Any suggestions? UPDATE: Thanks for the insightful answers and comments! I had forgotten my JavaScript 101, wherein the spec says you're not guaranteed a particular order in an associative array. It's interesting, though, that most browsers do implement it that way. I'd prefer not to sort the array before getting that first key, but it may be unavoidable given my use case. | There isn't really a first or last element in associative arrays (i.e. objects). The only order you can hope to acquire is the order the elements were saved by the parser -- and no guarantees for consistency with that. But, if you want the first to come up , the classic manner might actually be a bit easier: function getKey(data) { for (var prop in data) return prop;} Want to avoid inheritance properties? function getKey(data) { for (var prop in data) if (data.propertyIsEnumerable(prop)) return prop;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
]
} |
177,188 | I'm not talking about a post build event for a project. Rather, I want to run an executable automatically after the entire solution is built. Is there a way to do a post build event for the solution? | Visual Studio 2010 and before You can do this in the Macro Editor by handling OnBuildDone. The event gives you a couple of handy properties you can check: scope (project/solution/batch) and action (build/rebuild/clean/deploy). To do what you want would be something like this (not tested, mind): Public Sub AfterBuild(scope As vsBuildScope, action As vsBuildAction) _ Handles BuildEvents.OnBuildDone If scope = vsBuildScope.vsBuildScopeSolution Then System.Diagnostics.Process.Start("some file I want to run") End IfEnd Sub Visual Studio 2012 The solution above won't work in Visual Studio 2012 because Microsoft has removed macros in that version. However, you can still do essentially the same thing with an add-in. To see how, go here: Alternative to Macros in Visual Studio 2012 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
]
} |
177,189 | Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created). In C#, I use Mutex class for this but I don't know how to do this in Java. | If I believe this article , by : having the first instance attempt to open a listening socket on the localhost interface. If it's able to open the socket, it is assumed that this is the first instance of the application to be launched. If not, the assumption is that an instance of this application is already running. The new instance must notify the existing instance that a launch was attempted, then exit. The existing instance takes over after receiving the notification and fires an event to the listener that handles the action. Note: Ahe mentions in the comment that using InetAddress.getLocalHost() can be tricky: it does not work as expected in DHCP-environment because address returned depends on whether the computer has network access. Solution was to open connection with InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) ; Probably related to bug 4435662 . I also found bug 4665037 which reports than Expected results of getLocalHost : return IP address of machine, vs. Actual results : return 127.0.0.1 . it is surprising to have getLocalHost return 127.0.0.1 on Linux but not on windows. Or you may use ManagementFactory object. As explained here : The getMonitoredVMs(int processPid) method receives as parameter the current application PID, and catch the application name that is called from command line, for example, the application was started from c:\java\app\test.jar path, then the value variable is " c:\\java\\app\\test.jar ". This way, we will catch just application name on the line 17 of the code below. After that, we search JVM for another process with the same name, if we found it and the application PID is different, it means that is the second application instance. JNLP offers also a SingleInstanceListener | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
]
} |
177,197 | Please anybody can tell me the questions, that can be asked in an interview for below topics Socket Programming Multi-Threading An advance thanks goes to everybody who provide their time | Socket Programming Difference between UDP and TCP. Difference between asynchronous and synchronous sockets. What is a packet. How'd you determine if packet didn't arrive malformed. How'd you determine where one packet ends and where another one starts. What is a port. Multi-Threading What synchronization primitives do you know, tell difference between them. What is a deadlock and what is a livelock. What is a race condition. What does the term 'lock-free' mean. What is the best way to terminate a thread. Why you shouldn't use TerminateThread-esque functions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21599/"
]
} |
177,242 | Whenever I start our Apache Felix (OSGi) based application under SUN Java ( build 1.6.0_10-rc2-b32 and other 1.6.x builds) I see the following message output on the console (usually under Ubuntu 8.4): Warning: The encoding 'UTF-8' is not supported by the Java runtime. I've seen this message display occasionally when running both Tomcat and Resin as well. If java supports unicode and UTF-8, what causes this message? I've yet to find any reference, or answer to this anywhere else. | According the documentation "Every implementation of the Java platform is required to support the following standard charsets... US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16." So I doubt that Sun have released a build without UTF-8 support. The actual error message appears to be from here , which is part of the Xerces XML parser. I imagine it is the XML parser where the problem is occurring. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1720/"
]
} |
177,271 | Can anyone provide some pseudo code for a roulette selection function? How would I implement this: I don't really understand how to read this math notation. I never took any probability or statistics. | It's been a few years since i've done this myself, however the following pseudo code was found easily enough on google. for all members of population sum += fitness of this individualend forfor all members of population probability = sum of probabilities + (fitness / sum) sum of probabilities += probabilityend forloop until new population is full do this twice number = Random between 0 and 1 for all members of population if number > probability but less than next probability then you have been selected end for end create offspringend loop The site where this came from can be found here if you need further details. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
]
} |
177,275 | If you are using ASP.NET MVC how are you doing grid display?Rolled your own?Got a library from somewhere? These are some of the known grid display solutions I have found for ASP.NET MVC ASP.NET MVC Flexgrid - Has nice column layout method Code based ASP.NET MVC GridView - simple, small, clean MVC Contrib - grid from codePlex jQueryGrid - jQuery grid Datatables - jQuery plugin - believed to be section 508 compliant ( .NET binding ) extJS - cross browser RIA framework - has grid support Ingrid - jQuery data grid jqxGrid - jQuery data grid Telerik MVC - jQuery based grid that is GPL v2 licensed, commercial version also available MVC Controls Toolkit - Client Site Based Grid Infragistics igGrid - jQuery based MVC grid dhtmlxGrid - Ajax-enabled JavaScript grid control ASP.net MVC Awesome Ajax List - a different, very flexible approach, can be used as a grid Syncfusion MVC Grid - Commercial grid ASP.net MVC Awesome Grid - part of the Awesome library (jQuery based) Shield UI Grid for ASP.NET MVC Grid controls for ASP.NET MVC 5 projects If you know of anything else that you are using or know to be good, please let me know. | We have been using jqGrid on a project and have had some good luck with it. Lots of options for inline editing, etc. If that stuff isn't necessary, then we've just used a plain foreach loop like @Hrvoje. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
]
} |
177,277 | I have a TreeView control in my WinForms .NET application that has multiple levels of childnodes that have childnodes with more childnodes, with no defined depth. When a user selects any parent node (not necessarily at the root level), how can I get a list of all the nodes beneith that parent node? For example, I started off with this: Dim nodes As List(Of String)For Each childNodeLevel1 As TreeNode In parentNode.Nodes For Each childNodeLevel2 As TreeNode In childNodeLevel1.Nodes For Each childNodeLevel3 As TreeNode In childNodeLevel2.Nodes nodes.Add(childNodeLevel3.Text) Next NextNext The problem is that this loop depth is defined and I'm only getting nodes burried down three levels. What if next time the user selects a parent node, there are seven levels? | Use recursion Function GetChildren(parentNode as TreeNode) as List(Of String) Dim nodes as List(Of String) = New List(Of String) GetAllChildren(parentNode, nodes) return nodesEnd FunctionSub GetAllChildren(parentNode as TreeNode, nodes as List(Of String)) For Each childNode as TreeNode in parentNode.Nodes nodes.Add(childNode.Text) GetAllChildren(childNode, nodes) NextEnd Sub | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
]
} |
177,287 | Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon. This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities. Update: This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough. | what about this: import win32apiwin32api.MessageBox(0, 'hello', 'title') Additionally: win32api.MessageBox(0, 'hello', 'title', 0x00001000) will make the box appear on top of other windows, for urgent messages. See MessageBox function for other options. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
177,323 | What is the most efficient way to read the last row with SQL Server? The table is indexed on a unique key -- the "bottom" key values represent the last row. | If you're using MS SQL, you can try: SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/177323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
]
} |
177,373 | I have a generic list... public List<ApprovalEventDto> ApprovalEvents The ApprovalEventDto has public class ApprovalEventDto { public string Event { get; set; } public DateTime EventDate { get; set; }} How do I sort the list by the event date? | You can use List.Sort() as follows: ApprovalEvents.Sort((lhs, rhs) => (lhs.EventDate.CompareTo(rhs.EventDate))); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6268/"
]
} |
177,389 | This question will expand on: Best way to open a socket in Python When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail. Edit:I tried this: try: s.connect((address, '80'))except: alert('failed' + address, 'down') but the alert function is called even when that connection should have worked. | It seems that you catch not the exception you wanna catch out there :) if the s is a socket.socket() object, then the right way to call .connect would be: import sockets = socket.socket()address = '127.0.0.1'port = 80 # port number is a number, not stringtry: s.connect((address, port)) # originally, it was # except Exception, e: # but this syntax is not supported anymore. except Exception as e: print("something's wrong with %s:%d. Exception is %s" % (address, port, e))finally: s.close() Always try to see what kind of exception is what you're catching in a try-except loop. You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
177,393 | In our code we used to have something like this: *(controller->bigstruct) = ( struct bigstruct ){ 0 }; This used to work great, and then we upgraded versions of GCC and suddenly started seeing stack overflows. Looking at the assembly, the old GCC code (2.x) was basically doing this: memset(controller->bigstruct, 0, sizeof(struct bigstruct)); The new GCC (3.4.x) was doing this struct bigstruct temp = { 0 }; controller->bigstruct = temp; After reviewing the C99 spec, I could see why; C99 basically requires that anonymous structures exist on the stack. It's a good concept, but this structure was 4 Megabytes large, and only ever intended to exist on heap! We've resorted to making our own 'initialize' function that explicitly sets the members, but that's ugly and a maintenance headache. I don't consider memset a proper solution, because I can't know that a bit-value of 0 is an appropriate zero value for the type ( nit-picking, I know, but there you are; I don't mind that the compiler does it, because it can know ) What is the "correct", or at least best, way to initialize a large structure like this? To furthur clarify why I think memset isn't a solution: The rules of initialization of members not explicitly initialized are the same as static initialization, and are as follows: - If it has pointer type, it is initialized to a null pointer; - If it has arithmetic type, it is initialized to ( positive or unsigned ) zero; ... 'memset' will set the memory to bit-pattern zero, which isn't necessarily the same thing. Imagine a system that doesn't use IEEE floating point numbers. Unusual, but supported by C. The representation of 0.0 doesn't have to mean "all-bits zero", it could be anything convenient to the processor. | memset is the way to go. You do not have many alternatives. Do something like: #define InitStruct(var, type) type var; memset(&var, 0, sizeof(type)) So that you only have to: InitStruct(st, BigStruct); And then use st as usual... I do not get how "0" is not a valid "0" type for a struct. The only way to "mass initialize" a struct is to set all of its memory to a value; otherwise you would have to make extra logic to tell it to use a specific bit pattern per member. The best "generic" bit pattern to use is 0. Besides - this is the same logic that you used when doing *(controller->bigstruct) = *( struct bigstruct ){ 0 }; Therefore I don't get your reluctance to use it :) The first comment to this post made me do some research before I called him and idiot and I found this: http://www.lysator.liu.se/c/c-faq/c-1.html Very interesting; if I could vote-up a comment I would :) That being said - your only option if you want to target archaic architectures with non-0 null values is still to do manual initialization to certain members. Thanks Thomas Padron-McCarthy! I learned something new today :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25704/"
]
} |
177,437 | const static int foo = 42; I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant foo from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it private ? | It has uses in both C and C++. As you guessed, the static part limits its scope to that compilation unit . It also provides for static initialization. const just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only. All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const on there will warn you if any code would try to modify that. If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/177437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079/"
]
} |
177,468 | I'm developing a simple Qt 4 app and making my own dialog. I subclassed QDialog , inserted the Q_OBJECT macro in the class declaration block, and... I get [Linker error] undefined reference to `vtable for MyDialog' and there is no moc_MyDialog.cpp generated by the moc compiler. I am using Qt 4.1.3 on Windows XP and mingw. I followed the build process from the Qt-supplied build shell. I used qmake to create make files and compiled everything with a make command. I have other classes that subclass QPushButton and QObject respectively, but they compile OK. I can't find any differences between them and the broken one. There must be missing something in the broken class, but I'm unable to spot it. | The undefined reference to "vtable for MyDialog" is caused because there is no moc file. Most c++ compilers create the vtable definition in the object file containing the first virtual function. When subclassing a qt object and using the Q_OBJECT macro, this will be in the moc*.cpp file. Therefore, this error means that the moc file is missing. The possible problems I can think of are: The header file for the class MyDialog.h is not added to HEADERS in the qmake file. You ran qmake to generate the make file before adding the Q_OBJECT macro. This created a make file without the moc rules. This is easily fixed by simply running qmake again. Your dialog derives from more than one class and QDialog is not the first class that it derives from. For qmake to work correctly, the QObject derived base class needs to be the first class that is inherited from. If you are using Qt Creator, you might get this error if your previous deployment was failed due to some reason (like application already running). In that case, simply do a 'Clean Project' and then 'Rebuild Project' and then 'Run' to deploy. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24028/"
]
} |
177,479 | I'm looking into building a content site with possibly thousands of different entries, accessible by index and by search. What are the measures I can take to prevent malicious crawlers from ripping off all the data from my site? I'm less worried about SEO, although I wouldn't want to block legitimate crawlers all together. For example, I thought about randomly changing small bits of the HTML structure used to display my data, but I guess it wouldn't really be effective. | Any site that it visible by human eyes is, in theory, potentially rippable. If you're going to even try to be accessible then this, by definition, must be the case (how else will speaking browsers be able to deliver your content if it isn't machine readable). Your best bet is to look into watermarking your content, so that at least if it does get ripped you can point to the watermarks and claim ownership. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011/"
]
} |
177,506 | double r = 11.631;double theta = 21.4; In the debugger, these are shown as 11.631000000000000 and 21.399999618530273 . How can I avoid this? | These accuracy problems are due to the internal representation of floating point numbers and there's not much you can do to avoid it. By the way, printing these values at run-time often still leads to the correct results, at least using modern C++ compilers. For most operations, this isn't much of an issue. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.