source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
95,890 | When someone talks about a variables storage class specifier, what are they talking about? They also often talk about variable linkage in the same context, what is that? | The storage class specifier controls the storage and the linkage of your variables. These are two concepts that are different.C specifies the following specifiers for variables: auto, extern, register, static. Storage The storage duration determines how long your variable will live in ram. There are three types of storage duration: static, automatic and dynamic. static If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables. automatic If the variable is declared in a function, but without the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function. Once you return, the variable no longer exist. Automatic storage is typically done on the stack. It is a very fast operation to create these variables (simply increment the stack pointer by the size). dynamic If you use malloc (or new in C++) you are using dynamic storage. This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically. Linkage Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage. no linkage This variable is only visible where it was declared. Typically applies to variables declared in a function. internal linkage This variable will be visible to all the functions within the file (called a translation unit ), but other files will not know it exists. external linkage The variable will be visible to other translation units. These are often thought of as "global variables". Here is a table describing the storage and linkage characteristics based on the specifiers Storage Class Function File Specifier Scope Scope ----------------------------------------------------- none automatic static no linkage external linkage extern static static external linkage external linkage static static static no linkage internal linkage auto automatic invalid no linkageregister automatic invalid no linkage | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/95890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
95,895 | I have two DateTime objects: StartDate and EndDate . I want to make sure StartDate is before EndDate . How is this done in C#? | if (StartDate < EndDate) // code if you just want the dates, and not the time if (StartDate.Date < EndDate.Date) // code | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/95895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
95,910 | Given this class class Foo{ // Want to find _bar with reflection [SomeAttribute] private string _bar; public string BigBar { get { return this._bar; } }} I want to find the private item _bar that I will mark with a attribute. Is that possible? I have done this with properties where I have looked for an attribute, but never a private member field. What are the binding flags that I need to set to get the private fields? | Use BindingFlags.NonPublic and BindingFlags.Instance flags FieldInfo[] fields = myType.GetFields( BindingFlags.NonPublic | BindingFlags.Instance); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/95910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
]
} |
95,912 | My Vista application needs to know whether the user has launched it "as administrator" (elevated) or as a standard user (non-elevated). How can I detect that at run time? | The following C++ function can do that: HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet );/*Parameters:ptet [out] Pointer to a variable that receives the elevation type of the current process. The possible values are: TokenElevationTypeDefault - This value indicates that either UAC is disabled, or the process is started by a standard user (not a member of the Administrators group). The following two values can be returned only if both the UAC is enabled and the user is a member of the Administrator's group: TokenElevationTypeFull - the process is running elevated. TokenElevationTypeLimited - the process is not running elevated.Return Values: If the function succeeds, the return value is S_OK. If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError().Implementation:*/HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet ){ if ( !IsVista() ) return E_FAIL; HRESULT hResult = E_FAIL; // assume an error occurred HANDLE hToken = NULL; if ( !::OpenProcessToken( ::GetCurrentProcess(), TOKEN_QUERY, &hToken ) ) { return hResult; } DWORD dwReturnLength = 0; if ( ::GetTokenInformation( hToken, TokenElevationType, ptet, sizeof( *ptet ), &dwReturnLength ) ) { ASSERT( dwReturnLength == sizeof( *ptet ) ); hResult = S_OK; } ::CloseHandle( hToken ); return hResult;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/95912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17037/"
]
} |
95,954 | Suppose we have: interface Foo { bool Func(int x);}class Bar: Foo{ bool Func(int x) { return (x>0); } }class Baz: Foo{ bool Func(int x) { return (x<0); } } Now we can toss around Bar and Baz as a Foos and call their Func methods. Delegates simplify this a little bit: delegate bool Foo(int x);bool Bar(int x){ return (x<0);}bool Baz(int x){ return (x>0);} Now we can toss around Bar and Baz as Foo delegates. What is the real benefit of delegates, except for getting shorter code? | There is a slight difference, delegates can access the member variables of classes in which, they are defined. In C# (unlike Java) all inner class are consider to be static. Therefore if you are using an interface to manage a callback, e.g. an ActionListener for a button. The implementing inner class needs to be passed (via the constructor) references to the parts of the containing class that it may need to interact with during the callback. Delegates do not have this restriction therefore reduces the amount of code required to implement the callback. Shorter, more concise code is also a worthy benefit. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/95954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6264/"
]
} |
95,967 | Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK. | SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col WHERE Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name AND Tab.Constraint_Type = 'PRIMARY KEY' AND Col.Table_Name = '<your table name>' | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/95967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
]
} |
95,988 | I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor? Create Table A(id int identity,Fname nvarchar(50),Lname nvarchar(50))Create Table B(Fname nvarchar(50),Lname nvarchar(50),NewId int)Insert into A(fname, lname)SELECT fname, lnameFROM B I'm using MS SQL Server 2005. | Use the ouput clause from 2005: DECLARE @output TABLE (id int)Insert into A (fname, lname)OUTPUT inserted.ID INTO @outputSELECT fname, lname FROM Bselect * from @output now your table variable has the identity values of all the rows you insert. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/95988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2526/"
]
} |
96,003 | Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students. Edit: Instructors and Students must be the same; instructors could be students in other classes, and vice versa. I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books. | There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance: class Person < ActiveRecord::Base; end # btw, model names are singular in railsclass Student < Person; endclass Instructor < Person; end then class Course < ActiveRecord::Base # renamed here because class Class already exists in ruby has_many :students has_many :instructorsend Just remember that for single table inheritance to work, you need a type column in the people table. using an association model might solve your issue class Course < ActiveRecord::Base has_many :studentships has_many :instructorships has_many :students, :through => :studentships has_many :instructors, :through => :instructorshipsendclass Studentship < ActiveRecord::Base belongs_to :course belongs_to :student, :class_name => "Person", :foreign_key => "student_id"endclass Instructorship < ActiveRecord::Base belongs_to :course belongs_to :instructor, :class_name => "Person", :foreign_key => "instructor_id"end | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/722/"
]
} |
96,029 | I have an ASP.Net page that will be hosted on a couple different servers, and I want to get the URL of the page (or even better: the site where the page is hosted) as a string for use in the code-behind. Any ideas? | Use this: Request.Url.AbsoluteUri That will get you the full path (including http://.. .) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/96029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
96,042 | I'm working on the creation of an ActiveX EXE using VB6, and the only example I got is all written in Delphi. Reading the example code, I noticed there are some functions whose signatures are followed by the safecall keyword. Here's an example: function AddSymbol(ASymbol: OleVariant): WordBool; safecall; What is the purpose of this keyword? | Safecall passes parameters from right to left, instead of the pascal or register (default) from left to right With safecall, the procedure or function removes parameters from the stack upon returning (like pascal, but not like cdecl where it's up to the caller) Safecall implements exception 'firewalls'; esp on Win32, this implements interprocess COM error notification. It would otherwise be identical to stdcall (the other calling convention used with the win api) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/431/"
]
} |
96,066 | I'm trying to incorporate some JavaScript unit testing into my automated build process. Currently JSUnit works well with JUnit, but it seems to be abandonware and lacks good support for Ajax, debugging, and timeouts. Has anyone had any luck automating (with Ant ) a unit testing library such as YUI test, jQuery's QUnit , or jQUnit ? Note: I use a custom built Ajax library, so the problem with Dojo's DOH is that it requires you to use their own Ajax function calls and event handlers to work with any Ajax unit testing. | There are many JavaScript unit test framework out there (JSUnit, scriptaculous, ...), but JSUnit is the only one I know that may be used with an automated build. If you are doing 'true' unit test you should not need AJAX support. For example, if you are using an RPC Ajax framework such as DWR, you can easily write a mock function: function mockFunction(someArg, callback) { var result = ...; // Some treatments setTimeout( function() { callback(result); }, 300 // Some fake latency ); } And yes, JSUnit does handle timeouts: Simulating Time in JSUnit Tests | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
]
} |
96,086 | I've had a lot of trouble trying to come up with the best way to properly follow TDD principles while developing UI in JavaScript. What's the best way to go about this? Is it best to separate the visual from the functional? Do you develop the visual elements first, and then write tests and then code for functionality? | I've done some TDD with Javascript in the past, and what I had to do was make the distinction between Unit and Integration tests. Selenium will test your overall site, with the output from the server, its post backs, ajax calls, all of that. But for unit testing, none of that is important. What you want is just the UI you are going to be interacting with, and your script. The tool you'll use for this is basically JsUnit , which takes an HTML document, with some Javascript functions on the page and executes them in the context of the page. So what you'll be doing is including the Stubbed out HTML on the page with your functions. From there,you can test the interaction of your script with the UI components in the isolated unit of the mocked HTML, your script, and your tests. That may be a bit confusing so lets see if we can do a little test. Lets to some TDD to assume that after a component is loaded, a list of elements is colored based on the content of the LI. tests.html <html><head><script src="jsunit.js"></script><script src="mootools.js"></script><script src="yourcontrol.js"></script></head><body> <ul id="mockList"> <li>red</li> <li>green</li> </ul> </body><script> function testListColor() { assertNotEqual( $$("#mockList li")[0].getStyle("background-color", "red") ); var colorInst = new ColorCtrl( "mockList" ); assertEqual( $$("#mockList li")[0].getStyle("background-color", "red") ); }</script></html> Obviously TDD is a multi-step process, so for our control, we'll need multiple examples. yourcontrol.js (step1) function ColorCtrl( id ) { /* Fail! */ } yourcontrol.js (step2) function ColorCtrl( id ) { $$("#mockList li").forEach(function(item, index) { item.setStyle("backgrond-color", item.getText()); }); /* Success! */} You can probably see the pain point here, you have to keep your mock HTML here on the page in sync with the structure of what your server controls will be. But it does get you a nice system for TDD'ing with JavaScript. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
]
} |
96,160 | You're building a web application. You need to store the state for a shopping cart like object during a user's session. Some notes: This is not exactly a shopping cart, but more like an itinerary that the user is building... but we'll use the word cart for now b/c ppl relate to it. You do not care about "abandoned" carts Once a cart is completed we will persist it to some server-side data store for later retrieval. Where do you store that stateful object? And how ? server (session, db, etc?) client (cookie key-vals, cookie JSON object, hidden form-field, etc?) other... Update : It was suggested that I list the platform we're targeting - tho I'm not sure its totally necessary... but lets say the front-end is built w/ASP.NET MVC. | It's been my experience with the Commerce Starter Kit and MVC Storefront (and other sites I've built) that no matter what you think now, information about user interactions with your "products" is paramount to the business guys. There's so many metrics to capture - it's nuts. I'll save you all the stuff I've been through - what's by far been the most successful for me is just creating an Order object with "NotCheckedOut" status and then adding items to it and the user adds items. This lets users have more than one cart and allows you to mine the tar out of the Orders table. It also is quite easy to transact the order - just change the status. Persisting "as they go" also allows the user to come back and finish the cart off if they can't, for some reason. Forgiveness is massive with eCommerce. Cookies suck, session sucks, Profile is attached to the notion of a user and it hits the DB so you might as well use the DB. You might think you don't want to do this - but you need to trust me and know that you WILL indeed need to feed the stats wonks some data later. I promise you. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18152/"
]
} |
96,196 | The C preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a #define . The following macro: #define SUCCEEDED(hr) ((HRESULT)(hr) >= 0) is in no way superior to the type safe: inline bool succeeded(int hr) { return hr >= 0; } But macros do have their place, please list the uses you find for macros that you can't do without the preprocessor. Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments. | As wrappers for debug functions, to automatically pass things like __FILE__ , __LINE__ , etc: #ifdef ( DEBUG )#define M_DebugLog( msg ) std::cout << __FILE__ << ":" << __LINE__ << ": " << msg#else#define M_DebugLog( msg )#endif Since C++20 the magic type std::source_location can however be used instead of __LINE__ and __FILE__ to implement an analogue as a normal function (template). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/96196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
]
} |
96,247 | I create a web application (WAR) and deploy it on Tomcat. In the webapp there is a page with a form where an administrator can enter some configuration data. I don't want to store this data in an DBMS, but just in an XML file on the file system. Where to put it? I would like to put the file somewhere in the directory tree where the application itself is deployed. Should my configuration file be in the WEB-INF directory? Or put it somewhere else? And what is the Java code to use in a servlet to find the absolute path of the directory? Or can it be accessed with a relative path? | What we do is to put it in a separate directory on the server (you could use something like /config, /opt/config, /root/config, /home/username/config, or anything you want). When our servlets start up, they read the XML file, get a few things out of it (most importantly DB connection information), and that's it. I asked about why we did this once. It would be nice to store everything in the DB, but obviously you can't store DB connection information in the DB. You could hardcode things in the code, but that's ugly for many reasons. If the info ever has to change you have to rebuild the code and redeploy. If someone gets a copy of your code or your WAR file they would then get that information. Putting things in the WAR file seems nice, but if you want to change things much it could be a bad idea. The problem is that if you have to change the information, then next time you redeploy it will overwrite the file so anything you didn't remember to change in the version getting built into the WAR gets forgotten. The file in a special place on the file system thing works quite well for us. It doesn't have any big downsides. You know where it is, it's stored seperatly, makes deploying to multiple machines easy if they all need different config values (since it's not part of the WAR). The only other solution I can think of that would work well would be keeping everything in the DB except the DB login info. That would come from Java system properties that are retrieved through the JVM. This the Preferences API thing mentioned by Hans Doggen above. I don't think it was around when our application was first developed, if it was it wasn't used. As for the path for accessing the configuration file, it's just a file on the filesystem. You don't need to worry about the web path. So when your servlet starts up it just opens the file at "/config/myapp/config.xml" (or whatever) and it will find the right thing. Just hardcodeing the path in for this one seems pretty harmless to me. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746/"
]
} |
96,297 | General Follow the same standards for all tests. Be clear about what each test state is. Be specific about the expected behavior. Examples 1) MethodName_StateUnderTest_ExpectedBehavior Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () Public void Sum_simpleValues_Calculated () Source: Naming standards for Unit Tests 2) Separating Each Word By Underscore Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () Public void Sum_Simple_Values_Calculated () Other End method names with Test Start method names with class name | I am pretty much with you on this one man. The naming conventions you have used are: Clear about what each test state is. Specific about the expected behaviour. What more do you need from a test name? Contrary to Ray's answer I don't think the Test prefix is necessary. It's test code, we know that. If you need to do this to identify the code, then you have bigger problems, your test code should not be mixed up with your production code. As for length and use of underscore, its test code , who the hell cares? Only you and your team will see it, so long as it is readable, and clear about what the test is doing, carry on! :) That said, I am still quite new to testing and blogging my adventures with it :) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/96297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18170/"
]
} |
96,313 | I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory. I'd just delete and do the checkout again but the whole directory is over a gig. Is there a tool that will restore the .svn folders for specific folders without having to download everything? I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine. Oh.. I'm a big fan of TortoiseSVN or the command line for linux. Thoughts? | In case you have changes to the files, and cannot delete them, you can use the Subversion 1.5 feature that allows you to 'checkout with obstructions'. Just delete the .svn directory in this directory and: (you don't need to delete inside directories when using --depth files, thanks Eric) In case the broken directory was the top directory of the working copy: svn checkout --depth files --force REPOS WC And if the directory above the broken one is still versioned run: svn update --depth files --force WC in that directory. In both samples REPOS is the url in the repository that matches the broken directory, and WC is the path to the directory. Files that were originally modified will be in the modified state after this. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/96313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430/"
]
} |
96,317 | Given an instance of System.Reflection.Assembly . | Not possible. Nothing specifies a "Root" namespace. The default namespace in the options is a visual studio thing, not a .net thing | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4094/"
]
} |
96,360 | I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST.(Non essential xml generating code replaced with "Hello there") StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); This is causing a server error, and the second servlet is never invoked. | This kind of thing is much easier using a library like HttpClient . There's even a post XML code example : PostMethod post = new PostMethod(url);RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1");post.setRequestEntity(entity);HttpClient httpclient = new HttpClient();int result = httpclient.executeMethod(post); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27/"
]
} |
96,405 | I have to deploy my php/html/css/etc code to multiple servers and i am looking at my options for software that allows easy and secure deployment to multiple servers. Also helps if it could be tied into my SVN. Any suggestions? | Capistrano is pretty handy for that. There's a few people using it ( 1 , 2 , 3 ) for deploying PHP code as evidenced by doing a quick search . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14433/"
]
} |
96,414 | I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works: InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring); The next step is this code: HICON hIconLarge, hIconSmall;ICONINFO oIconInfo;ExtractIconEx("c:\\progra~1\\winzip\\winzip32.exe", 0, &hIconLarge, &hIconSmall, 1);GetIconInfo(hIconSmall, &oIconInfo);//???????SetMenuItemBitmaps(hParentMenu, indexMenu-1, MF_BITMAP | MF_BYPOSITION, hbmp, hbmp); What do I put in to replace the ?'s. Attempts to Google this knowledge have found many tips that I failed to get working. Any advice on getting this to work, especially on older machines (e.g. no .net framework, no vista) is appreciated. | Capistrano is pretty handy for that. There's a few people using it ( 1 , 2 , 3 ) for deploying PHP code as evidenced by doing a quick search . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18192/"
]
} |
96,428 | I have this string 'john smith~123 Street~Apt 4~New York~NY~12345' Using JavaScript, what is the fastest way to parse this into var name = "john smith";var street= "123 Street";//etc... | With JavaScript’s String.prototype.split function: var input = 'john smith~123 Street~Apt 4~New York~NY~12345';var fields = input.split('~');var name = fields[0];var street = fields[1];// etc. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/96428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
]
} |
96,486 | Any suggestion for a JavaScript interactive drawing library? Just need to draw lines, polygons, texts of different colors. IE/Firefox/Opera/Safari compatible. | Raphael is pretty cool for that, and works across browsers since it uses VML (for MSIE) and SVG (for everything else). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/96486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18203/"
]
} |
96,500 | Suppose I have the following code: class some_class{};some_class some_function(){ return some_class();} This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong? | No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
96,553 | Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses? For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate: SELECT * FROM 4e_magic_items INNER JOIN 4e_magic_item_levels ON 4e_magic_items.id = 4e_magic_item_levels.itemid INNER JOIN 4e_monster_sources ON 4e_magic_items.source = 4e_monster_sources.id WHERE (itemlevel BETWEEN 1 AND 30) AND source!=16 AND source!=2 AND source!=5 AND source!=13 AND source!=15 AND source!=3 AND source!=4 AND source!=12 AND source!=7 AND source!=14 AND source!=11 AND source!=10 AND source!=8 AND source!=1 AND source!=6 AND source!=9 AND type!='Arms' AND type!='Feet' AND type!='Hands' AND type!='Head' AND type!='Neck' AND type!='Orb' AND type!='Potion' AND type!='Ring' AND type!='Rod' AND type!='Staff' AND type!='Symbol' AND type!='Waist' AND type!='Wand' AND type!='Wondrous Item' AND type!='Alchemical Item' AND type!='Elixir' AND type!='Reagent' AND type!='Whetstone' AND type!='Other Consumable' AND type!='Companion' AND type!='Mount' AND (type!='Armor' OR (false )) AND (type!='Weapon' OR (false )) ORDER BY type ASC, itemlevel ASC, name ASC It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such. | Reading your query makes me want to play an RPG. This is definitely not too long. As long as they are well formatted, I'd say a practical limit is about 100 lines. After that, you're better off breaking subqueries into views just to keep your eyes from crossing. I've worked with some queries that are 1000+ lines, and that's hard to debug. By the way, may I suggest a reformatted version? This is mostly to demonstrate the importance of formatting; I trust this will be easier to understand. select * from 4e_magic_items mi ,4e_magic_item_levels mil ,4e_monster_sources mswhere mi.id = mil.itemid and mi.source = ms.id and itemlevel between 1 and 30 and source not in(16,2,5,13,15,3,4,12,7,14,11,10,8,1,6,9) and type not in( 'Arms' ,'Feet' ,'Hands' ,'Head' ,'Neck' ,'Orb' , 'Potion' ,'Ring' ,'Rod' ,'Staff' ,'Symbol' ,'Waist' , 'Wand' ,'Wondrous Item' ,'Alchemical Item' ,'Elixir' , 'Reagent' ,'Whetstone' ,'Other Consumable' ,'Companion' , 'Mount' ) and ((type != 'Armor') or (false)) and ((type != 'Weapon') or (false))order by type asc ,itemlevel asc ,name asc/*Some thoughts:==============0 - Formatting really matters, in SQL even more than most languages.1 - consider selecting only the columns you need, not "*"2 - use of table aliases makes it short & clear ("MI", "MIL" in my example)3 - joins in the WHERE clause will un-clutter your FROM clause4 - use NOT IN for long lists5 - logically, the last two lines can be added to the "type not in" section. I'm not sure why you have the "or false", but I'll assume some good reason and leave them here.*/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18210/"
]
} |
96,579 | I'm writing an inner loop that needs to place struct s in contiguous storage. I don't know how many of these struct s there will be ahead of time. My problem is that STL's vector initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the struct 's members to their values. Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements? (I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.) Also, see my comments below for a clarification about when the initialization occurs. SOME CODE: void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size() memberVector.resize(mvSize + count); // causes 0-initialization for (int i = 0; i < count; ++i) { memberVector[mvSize + i].d1 = data1[i]; memberVector[mvSize + i].d2 = data2[i]; }} | std::vector must initialize the values in the array somehow, which means some constructor (or copy-constructor) must be called. The behavior of vector (or any container class) is undefined if you were to access the uninitialized section of the array as if it were initialized. The best way is to use reserve() and push_back() , so that the copy-constructor is used, avoiding default-construction. Using your example code: struct YourData { int d1; int d2; YourData(int v1, int v2) : d1(v1), d2(v2) {}};std::vector<YourData> memberVector;void GetsCalledALot(int* data1, int* data2, int count) { int mvSize = memberVector.size(); // Does not initialize the extra elements memberVector.reserve(mvSize + count); // Note: consider using std::generate_n or std::copy instead of this loop. for (int i = 0; i < count; ++i) { // Copy construct using a temporary. memberVector.push_back(YourData(data1[i], data2[i])); }} The only problem with calling reserve() (or resize() ) like this is that you may end up invoking the copy-constructor more often than you need to. If you can make a good prediction as to the final size of the array, it's better to reserve() the space once at the beginning. If you don't know the final size though, at least the number of copies will be minimal on average. In the current version of C++, the inner loop is a bit inefficient as a temporary value is constructed on the stack, copy-constructed to the vectors memory, and finally the temporary is destroyed. However the next version of C++ has a feature called R-Value references ( T&& ) which will help. The interface supplied by std::vector does not allow for another option, which is to use some factory-like class to construct values other than the default. Here is a rough example of what this pattern would look like implemented in C++: template <typename T>class my_vector_replacement { // ... template <typename F> my_vector::push_back_using_factory(F factory) { // ... check size of array, and resize if needed. // Copy construct using placement new, new(arrayData+end) T(factory()) end += sizeof(T); } char* arrayData; size_t end; // Of initialized data in arrayData};// One of many possible implementationsstruct MyFactory { MyFactory(int* p1, int* p2) : d1(p1), d2(p2) {} YourData operator()() const { return YourData(*d1,*d2); } int* d1; int* d2;};void GetsCalledALot(int* data1, int* data2, int count) { // ... Still will need the same call to a reserve() type function. // Note: consider using std::generate_n or std::copy instead of this loop. for (int i = 0; i < count; ++i) { // Copy construct using a factory memberVector.push_back_using_factory(MyFactory(data1+i, data2+i)); }} Doing this does mean you have to create your own vector class. In this case it also complicates what should have been a simple example. But there may be times where using a factory function like this is better, for instance if the insert is conditional on some other value, and you would have to otherwise unconditionally construct some expensive temporary even if it wasn't actually needed. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/96579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6160/"
]
} |
96,597 | My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5. I have read in various blogs and documents scattered around the web that this may be done by using RPMForge. I have followed the instructions found on CentOS Wiki , including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge). However, when I attempt to run: $ yum info subversion the version number given to me is still 1.4.2, with a status of Installed. My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades. Any thoughts? | What you are trying to do is to replace a "core" package (one which iscontained in the CentOS repository) with a newer package from a "3rdparty" repository (RPMForge), which is what the priorities plugin isdesigned to prevent. The RPMForge repository contains both additional packages not found inCentOS, as well as newer versions of core packages. Unfortunately, yum is pretty stupid and will always update a package to the latest versionit can find in any repository. So running " yum update " with RPMforgeenabled will update half of your system with the latest (bleeding edge,possibly unstable and less well supported) packages from RPMForge. Therefore, the recommended way to use repos like RPMForge is to use themonly together with a yum plugin like "priorites", which preventspackages from "high" priority repos to overwrite those from "low"priority repos (the name of the "priority" parameter is verymisleading). This way you can savely install additional packages (thatare not in core) from RPMForge, which is what most people want. Now to your original question ... If you want to replace a core package, things get a little tricky.Basically, you have two options: Uninstall the priority plugin, and disable the RPMForge repository bydefault (set enabled = 0 in /etc/yum.repos.d/rpmforge.repo ). You canthen selectively enable it on the command line: yum --enablerepo=rpmforge install subversion will install the latest subversion and dependencies from RPMForge. The problem with this approach is that if there is an update to thesubversion package in RPMForge, you will not see it when the repo isdisabled. To keep subversion up to date, you have to remember to run yum --enablerepo=rpmforge update subversion from time to time. The second possibility is to use the priorites plugin, but manually"mask" the core subversion package (add exclude=subversion to the [base] and [update] sections in /etc/yum.repos.d/CentOS-Base.repo ). Now yum will behave as if there is no package named "subversion" inthe core repository and happily install the latest version fromRPMForge. Plus, you will always get the latest subversion updateswhen running yum update . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5570/"
]
} |
96,615 | So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing git pull or git rebase . I thought I had read that doing git rebase when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using git pull ? | Git pull is a combination of 2 commands git fetch (syncs your local repo with the newest stuff on the remote) git merge (merges the changes from the distant branch, if any, into your local tracking branch) git rebase is only a rough equivalent to git merge. It doesn't fetch anything remotely. In fact it doesn't do a proper merge either, it replays the commits of the branch you're standing on after the new commits from a second branch. Its purpose is mainly to let you have a cleaner history. It doesn't take many merges by many people before the past history in gitk gets terribly spaghetti-like. The best graphical explanation can be seen in the first 2 graphics here . But let me explain here with an example. I have 2 branches: master and mybranch. When standing on mybranch I can run git rebase master and I'll get anything new in master inserted before my most recent commits in mybranch. This is perfect, because if I now merge or rebase the stuff from mybranch in master, my new commits are added linearly right after the most recent commits. The problem you refer to happens if I rebase in the "wrong" direction. If I just got the most recent master (with new changes) and from master I rebase like this (before syncing my branch): git rebase mybranch Now what I just did is that I inserted my new changes somewhere in master's past. The main line of commits has changed. And due to the way git works with commit ids, all the commits (from master) that were just replayed over my new changes have new ids. Well, it's a bit hard to explain just in words... Hope this makes a bit of sense :-) Anyway, my own workflow is this: 'git pull' new changes from remote switch to mybranch 'git rebase master' to bring master's new changes in my commit history switch back to master 'git merge mybranch', which only fast-forwards when everything in master is also in mybranch (thus avoiding the commit reordering problem on a public branch) 'git push' One last word. I strongly recommend using rebase when the differences are trivial (e.g. people working on different files or at least different lines). It has the gotcha I tried to explain just up there, but it makes for a much cleaner history. As soon as there may be significant conflicts (e.g. a coworker has renamed something in a bunch of files), I strongly recommend merge. In this case, you'll be asked to resolve the conflict and then commit the resolution. On the plus side, a merge is much easier to resolve when there are conflicts. The down side is that your history may become hard to follow if a lot of people do merges all the time :-) Good luck! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14873/"
]
} |
96,624 | I have an assembly which should not be used by any application other than the designated executable. Please give me some instructions to do so. | You can sign the assembly and the executable with the same key and then put a check in the constructor of the classes you want to protect: public class NotForAnyoneElse { public NotForAnyoneElse() { if (typeof(NotForAnyoneElse).Assembly.GetName().GetPublicKeyToken() != Assembly.GetEntryAssembly().GetName().GetPublicKeyToken()) { throw new SomeException(...); } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18198/"
]
} |
96,718 | How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE: public class ObjectExtensions{ ...}public class StringExtensions{ ...} am I making this too complicated or does this make sense? | I organize extension methods using a combination of namespace and class name, and it's similar to the way you describe in the question. Generally I have some sort of "primary assembly" in my solution that provides the majority of the shared functionality (like extension methods). We'll call this assembly "Framework" for the sake of discussion. Within the Framework assembly, I try to mimic the namespaces of the things for which I have extension methods. For example, if I'm extending System.Web.HttpApplication, I'd have a "Framework.Web" namespace. Classes like "String" and "Object," being in the "System" namespace, translate to the root "Framework" namespace in that assembly. Finally, naming goes along the lines you've specified in the question - the type name with "Extensions" as a suffix. This yields a class hierarchy like this: Framework (namespace) Framework.ObjectExtensions (class) Framework.StringExtensions (class) Framework.Web (namespace) Framework.Web.HttpApplicationExtensions (class) The benefit is that, from a maintenance perspective, it's really easy later to go find the extension methods for a given type. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
]
} |
96,732 | I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible. This with is C# and .NET 3.5. The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL. The way I originally planned to do this is by writing code to put the third party DLL in the location specified by System.Reflection.Assembly.GetExecutingAssembly().Location.ToString() minus the last /nameOfMyAssembly.dll . I can successfully save the third party .DLL in this location (which ends up being C:\Documents and Settings\myUserName\Local Settings\Application Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb_fe18c901 ), but when I get to the part of my code requiring this DLL, it can't find it. Does anybody have any idea as to what I need to be doing differently? | Once you've embedded the third-party assembly as a resource, add code to subscribe to the AppDomain.AssemblyResolve event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails to locate an assembly according to the probing (policies) in effect. In the event handler for AppDomain.AssemblyResolve , load the resource using Assembly.GetManifestResourceStream and feed its content as a byte array into the corresponding Assembly.Load overload. Below is how one such implementation could look like in C#: AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>{ var resName = args.Name + ".dll"; var thisAssembly = Assembly.GetExecutingAssembly(); using (var input = thisAssembly.GetManifestResourceStream(resName)) { return input != null ? Assembly.Load(StreamToBytes(input)) : null; }}; where StreamToBytes could be defined as: static byte[] StreamToBytes(Stream input) { var capacity = input.CanSeek ? (int) input.Length : 0; using (var output = new MemoryStream(capacity)) { int readLength; var buffer = new byte[4096]; do { readLength = input.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, readLength); } while (readLength != 0); return output.ToArray(); }} Finally, as a few have already mentioned, ILMerge may be another option to consider, albeit somewhat more involved. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/96732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
]
} |
96,748 | I'm building a widget, and I've been using iframes to present content within it. At some point, I might start serving third party HTML and JS, so I thought iframes would be a good idea. It does make the widget javascript a little more complicated, and I'm concerned that this might not be the best implementation. Do you have any advice? It would be a huge help to hear what other people think about iframes. | No, nothing wrong with iframes. Iframes are probably a better idea if you're going to start serving third party content. The upcoming HTML5 spec also plans to build more security features into iframes for situations like this, so I would consider it good practice to use them now also. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9106/"
]
} |
96,759 | I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file. function f_parse_csv($file, $longest, $delimiter){ $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($mdarray, $line); } fclose($file); return $mdarray;} I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of Y-m-d H:i:s and I would like to be able to sort with the most recent date being the first row. | You can use array_multisort() Try something like this: foreach ($mdarray as $key => $row) { // replace 0 with the field's index/key $dates[$key] = $row[0];}array_multisort($dates, SORT_DESC, $mdarray); For PHP >= 5.5.0 just extract the column to sort by. No need for the loop: array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/96759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1536217/"
]
} |
96,780 | Visual Studio randomly crashes when adding/removing references and projects.Any thoughts why? Will installing Sp1 help? EDIT: I do not work with any addons except SourceSafe. I do most of my development in connected mode. Developing using: Visual Studio 2008 WinXp Terminal Service -> Win2k3 Sp2 (64bit) VSS 8.0, 32bit | Try deleting your .user and .suo files - these are the user options files that VS creates. You get a .user file for each project and a .suo file for your solution. When they get corrupted, odd things happen. Deleting them will make you lose little things like which project is selected as the startup project when you start debugging, but it usually clears up odd behavior like this. You may also want to clear out any temporary file locations, like the Temporary ASP.NET Files folders (if you're working in ASP.NET) just in case something odd is being cached somewhere. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
]
} |
96,826 | Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with "abc " directly followed by anything other than "defg" . I've used "[^defg]" to match any single character other than d, e, f or g. My first instinct was to try /abc [^\(defg\)] or /abc [^\<defg\>] but neither one of those works. | Here's the search string. /abc \(defg\)\@! The concept you're looking for is called a negative look-ahead assertion. Try this in vim for more info: :help \@! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5379/"
]
} |
96,848 | Is there any way to use a constant as a hash key? For example: use constant X => 1;my %x = (X => 'X'); The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key. | use constant actually makes constant subroutines. To do what you want, you need to explicitly call the sub: use constant X => 1;my %x = ( &X => 'X'); or use constant X => 1;my %x = ( X() => 'X'); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/96848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
} |
96,882 | I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image. I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap. | After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference: Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4). Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG: hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \ -fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation): device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \ egrep '^/dev/' | sed 1q | awk '{print $1}') Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable. Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed): echo ' tell application "Finder" tell disk "'${title}'" open set current view of container window to icon view set toolbar visible of container window to false set statusbar visible of container window to false set the bounds of container window to {400, 100, 885, 430} set theViewOptions to the icon view options of container window set arrangement of theViewOptions to not arranged set icon size of theViewOptions to 72 set background picture of theViewOptions to file ".background:'${backgroundPictureName}'" make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"} set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} update without registering applications delay 5 close end tell end tell' | osascript Finialize the DMG by setting permissions properly, compressing and releasing it: chmod -Rf go-w /Volumes/"${title}"syncsynchdiutil detach ${device}hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}"rm -f /pack.temp.dmg On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.: ..set position of item "'${applicationName}'" of container window to {100, 100}set position of item "Applications" of container window to {375, 100}closeopen | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/96882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16909/"
]
} |
96,922 | The standard answer is that it's useful when you only need to write a few lines of code ... I have both languages integrated inside of Eclipse. Because Eclipse handles the compiling, interpreting, running etc. both "run" exactly the same. The Eclipse IDE for both is similar - instant "compilation", intellisense etc. Both allow the use of the Debug perspective. If I want to test a few lines of Java, I don't have to create a whole new Java project - I just use the Scrapbook feature inside Eclipse which which allows me to "execute Java expressions without having to create a new Java program. This is a neat way to quickly test an existing class or evaluate a code snippet" . Jython allows the use of the Java libraries - but then so (by definition) does Java! So what other benefits does Jython offer? | A quick example (from http://coreygoldberg.blogspot.com/2008/09/python-vs-java-http-get-request.html ) : You have a back end in Java, and you need to perform HTTP GET resquests. Natively : import java.net.*;import java.io.*;public class JGet { public static void main (String[] args) throws IOException { try { URL url = new URL("http://www.google.com"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (MalformedURLException e) {} catch (IOException e) {} }} In Python : import urllibprint urllib.urlopen('http://www.google.com').read() Jython allows you to use the java robustness and when needed, the Python clarity. What else ? As Georges would say... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/96922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9922/"
]
} |
96,952 | What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? Field with value "00345ABC" would need to return "345ABC". | You are looking for the trim() function . Alright, here is your example SELECT TRIM(LEADING '0' FROM myfield) FROM table | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/96952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446/"
]
} |
97,018 | I am the maintainer of a site that has allegedly 'lost' the source code to a flash swf file. How do I decompile this source? Are there any programs online or offline that I could use? | Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code." That being said, I own a copy of Burak's ActionScript Viewer , and it works pretty well. A simple google search will find you many other SWF decompilers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8563/"
]
} |
97,050 | Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted? | The answer is you do neither. Instead you want to do something suggested by Item 24 of Effective STL by Scott Meyers : typedef map<int, int> MapType; // Your map type may vary, just change the typedefMapType mymap;// Add elements to map hereint k = 4; // assume we're searching for keys equal to 4int v = 0; // assume we want the value 0 associated with the key of 4MapType::iterator lb = mymap.lower_bound(k);if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first))){ // key already exists // update lb->second if you care to}else{ // the key does not exist in the map // add it to the map mymap.insert(lb, MapType::value_type(k, v)); // Use lb as a hint to insert, // so it can avoid another lookup} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16496/"
]
} |
97,097 | What is the C# version of VB.net's InputBox? | Add a reference to Microsoft.VisualBasic , InputBox is in the Microsoft.VisualBasic.Interaction namespace: using Microsoft.VisualBasic;string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate); Only the first argument for prompt is mandatory | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/97097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
]
} |
97,113 | I have the following string: cn=abcd,cn=groups,dc=domain,dc=com Can a regular expression be used here to extract the string after the first cn= and before the first , ? In the example above the answer should be abcd . | /cn=([^,]+),/ most languages will extract the match as $1 or matches[1] If you can't for some reason wield subscripts, $x =~ s/^cn=//$x =~ s/,.*$// Thats a way to do it in 2 steps. If you were parsing it out of a log with sed sed -n -r '/cn=/s/^cn=([^,]+),.*$/\1/p' < logfile > dumpfile will get you what you want. ( Extra commands added to only print matching lines ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17273/"
]
} |
97,137 | I know I once know how to do this but... how do you run a script (bash is OK) on login in unix? | From wikipedia Bash When Bash starts, it executes the commands in a variety of different scripts. When Bash is invoked as an interactive login shell, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. When a login shell exits, Bash reads and executes commands from the file ~/.bash_logout, if it exists. When an interactive shell that is not a login shell is started, Bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11760/"
]
} |
97,197 | The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world. Does anybody have a more detailed explanation of the problem? | Let's say you have a collection of Car objects (database rows), and each Car has a collection of Wheel objects (also rows). In other words, Car → Wheel is a 1-to-many relationship. Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following: SELECT * FROM Cars; And then for each Car : SELECT * FROM Wheel WHERE CarId = ? In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars. Alternatively, one could get all wheels and perform the lookups in memory: SELECT * FROM Wheel; This reduces the number of round-trips to the database from N+1 to 2.Most ORM tools give you several ways to prevent N+1 selects. Reference: Java Persistence with Hibernate , chapter 13. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/97197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6120/"
]
} |
97,279 | Does anyone know a keyboard shortcut to close all tabs except for the current one in Visual Studio? And while we're at it, the shortcut for closing all tabs? Is there a Resharper option for this? I've looked in the past and have never been able to find it. | I don't think there is one by default, but you can go to Tools>Options>Environment>Keyboard and bind a key to File.CloseAllButThis. I use ctrl + alt + w | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9344/"
]
} |
97,283 | For example if the user is currently running VS2008 then I want the value VS2008. | I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke: // The GetForegroundWindow function returns a handle to the foreground window// (the window with which the user is currently working).[System.Runtime.InteropServices.DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();// The GetWindowThreadProcessId function retrieves the identifier of the thread// that created the specified window and, optionally, the identifier of the// process that created the window.[System.Runtime.InteropServices.DllImport("user32.dll")]private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);// Returns the name of the process owning the foreground window.private string GetForegroundProcessName(){ IntPtr hwnd = GetForegroundWindow(); // The foreground window can be NULL in certain circumstances, // such as when a window is losing activation. if (hwnd == null) return "Unknown"; uint pid; GetWindowThreadProcessId(hwnd, out pid); foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) { if (p.Id == pid) return p.ProcessName; } return "Unknown";} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
]
} |
97,312 | How do I find out what directory my console app is running in with C#? | To get the directory where the .exe file is: AppDomain.CurrentDomain.BaseDirectory To get the current directory: Environment.CurrentDirectory | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
]
} |
97,338 | I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me? gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP) | The answer is in the GCC manual : use the -MT flag. -MT target Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as .c , and appends the platform's usual object suffix. The result is the target. An -MT option will set the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT , or use multiple -MT options. For example, -MT '$(objpfx)foo.o' might give $(objpfx)foo.o: foo.c | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/97338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
]
} |
97,349 | We want to store our overridden build targets in an external file and include that targets file in the TFSBuild.proj. We have a core set steps that happens and would like to get those additional steps by simply adding the import line to the TFSBuild.proj created by the wizard. <Import Project="$(SolutionRoot)/libs/my.team.build/my.team.build.targets"/> We cannot have an import on any file in the $(SolutionRoot) because at the time the Import statement is validated, the source has not be fetched from the repository. It looks like TFS is pulling down the TFSBuild.proj first without any other files. Even if we add a conditional import, the version in source control will not be imported if present. The previous version, already present on disk will be imported. We can give up storing those build targets with our source, but it is the first dependency to move out of our source tree so we are reluctant to do it. Is there a way to either: Tell Team Build to pull down a few more files so those Import statements evaluate correctly? Override those Team Build targets like AfterCompile in a manner besides the Import ? Ultimately run build targets in Team Build that are kept under the source it's trying to build? | The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj. If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e. <Import Project="myTeamBuild.targets"/> If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path. Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this: $/TeamProject/main/MySolution/TeamBuild Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies) <add key="ConfigurationFolderRecursionType" value="Full" /> Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can. Good luck, Martin. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18264/"
]
} |
97,370 | I have a macro which refreshes all fields in a document (the equivalent of doing an F9 on the fields). I'd like to fire this macro automatically when the user saves the document. Under options I can select "update fields when document is printed", but that's not what I want. In the VBA editor I only seem to find events for the Document_Open() event, not the Document_Save() event. Is it possible to get the macro to fire when the user saves the document? Please note: This is Word 97. I know it ispossible in later versions of Word I don't want to replace the standard Save button on the toolbar with a button to run my custom macro. Replacing the button on the toolbar applies to all documents and I only want it to affect this one document. To understand why I need this, the document contains a "SaveDate" field and I'd like this field to update on the screen when the user clicks Save. So if you can suggest another way to achieve this, then that would be just as good. | The Team Build has a "bootstrap" phase where everything in the Team Build Configuration folder (the folder with TFSBuild.proj) is downloaded from version control. This is performed by the build agent before the build agent calls MSBuild.exe telling it to run TFSBuild.proj. If you move your targets file from under SolutionRoot and place it in your configuration folder alongside the TFSBuild.proj file you will then be able to import it in your TFSBuild.proj file using a relative import statement i.e. <Import Project="myTeamBuild.targets"/> If these targets rely on any additional custom MSBuild task assemblies then you can also have them in the same folder as your TFSBuild.proj file and you can reference them easily using a relative path. Note that in TFS2008, the build configuration folder defaults to being under $/TeamProject/TeamBuildTypes however, it does not have to be there. It can actually live in a folder that is inside your solution - and can even be a project in your solution dedicated to Team Build. This has several advantages including making branching of the build easier. Therefore I typically have my build located in a folder like this: $/TeamProject/main/MySolution/TeamBuild Also note that by default, during the bootstrap phase of the build, the build agent will only download files that are in the build configuration folder and will not recurse down into any subfolders. If you wanted it to include files in subfolders during the bootstrap phase then you can set the following property in the appSettings of the tfsbuildserver.exe.config file on the build agent machines (located in %ProgramFiles%\Visual Studio 9.0\Common7\IDE\PrivateAssemblies) <add key="ConfigurationFolderRecursionType" value="Full" /> Note that if you had multiple build agents you would have to remember to set this setting on all of the machines, and it would affect every build performed by that build agent - so really it is best just to keep the files in the root of the build configuration folder if you can. Good luck, Martin. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9625/"
]
} |
97,371 | I need to copy the newest file in a directory to a new location. So far I've found resources on the forfiles command, a date-related question here, and another related question . I'm just having a bit of trouble putting the pieces together! How do I copy the newest file in that directory to a new place? | Windows shell, one liner: FOR /F "delims=" %%I IN ('DIR *.* /A-D /B /O:-D') DO COPY "%%I" <<NewDir>> & EXIT | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/97371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269/"
]
} |
97,381 | C# has the keyword called yield . VB.NET lacks this keyword. How have the Visual Basic programmers gotten around the lack of this keyword? Do they implement they own iterator class? Or do they try and code to avoid the need of an iterator? The yield keyword does force the compiler to do some coding behind the scenes. The implementation of iterators in C# and its consequences (part 1) has a good example of that. | Note: This answer is old now. Iterator blocks have since been added to VB.NET C# translates the yield keyword into a state machine at compile time. VB.NET does not have the yield keyword, but it does have its own mechanism for safely embedding state within a function that is not easily available in C#. The C# static keyword is normally translated to Visual Basic using the Shared keyword, but there are two places where things get confusing. One is that a C# static class is really a Module in Visual Basic rather than a Shared class (you'd think they'd let you code it either way in Visual Basic, but noooo). The other is that VB.NET does have its own Static keyword. However, Static has a different meaning in VB.NET. You use the Static keyword in VB.NET to declare a variable inside a function, and when you do the variable retains its state across function calls. This is different than just declaring a private static class member in C#, because a static function member in VB.NET is guaranteed to also be thread-safe, in that the compiler translates it to use the Monitor class at compile time. So why write all this here? Well, it should be possible to build a re-usable generic Iterator<T> class (or Iterator(Of T) in VB.NET). In this class you would implement the state machine used by C#, with Yield() and Break() methods that correspond to the C# keywords. Then you could use a static instance (in the VB.NET sense) in a function so that it can ultimately do pretty much the same job as C#'s yield in about the same amount of code (discarding the class implemenation itself, since it would be infinitely re-usable). I haven't cared enough about Yield to attempt it myself, but it should be doable. That said, it's also far from trivial, as C# team member Eric Lippert calls this " the most complicated transformation in the compiler ." I have also come to believe since I wrote the first draft of this over a year ago that it's not really possible in a meaningful way until Visual Studio 2010 comes out, as it would require sending multiple lambdas to the Iterator class and so to be really practical we need .NET 4 's support for multi-line lambdas. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/97381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8505/"
]
} |
97,391 | I have the following enum declared: public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' } How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ? Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard. | You have to check the underlying type of the enumeration and then convert to a proper type: public enum SuperTasks : int { Sleep = 5, Walk = 7, Run = 9 } private void btnTestEnumWithReflection_Click(object sender, EventArgs e) { SuperTasks task = SuperTasks.Walk; Type underlyingType = Enum.GetUnderlyingType(task.GetType()); object value = Convert.ChangeType(task, underlyingType); // x will be int } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
97,433 | I keep getting asked about AppDomains in interviews, and I know the basics : they are an isolation level within an application (making them different from applications) they can have threads (making them different from threads) exceptions in one appdomain do not affect another appdomains cannot access each other's memory each appdomain can have different security I still don't get what makes them necessary. I'm looking for a reasonable concrete circumstance when you would use one. Answers: Untrusted code Core application protected Untrusted/3rd party plugins are barred from corrupting shared memory and non-authorized access to registry or hard drive by isolation in separate appdomain with security restrictions, protecting the application or server. e.g. ASP.NET and SQL Server hosting component code Trusted code Stability Application segmented into safe, independent features/functionality Architectural flexibility Freedom to run multiple applications within a single CLR instance or each program in its own. Anything else? | Probably the most common one is to load assemblies that contain plug-in code from untrusted parties. The code runs in its own AppDomain, isolating the application. Also, it's not possible to unload a particular assembly, but you can unload AppDomains. For the full rundown, Chris Brumme had a massive blog entry on this: http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx https://devblogs.microsoft.com/cbrumme/appdomains-application-domains/ | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/97433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10293/"
]
} |
97,459 | When a C# WinForms textbox receives focus, I want it to behave like your browser's address bar. To see what I mean, click in your web browser's address bar. You'll notice the following behavior: Clicking in the textbox should select all the text if the textbox wasn't previously focused. Mouse down and drag in the textbox should select only the text I've highlighted with the mouse. If the textbox is already focused, clicking does not select all text. Focusing the textbox programmatically or via keyboard tabbing should select all text. I want to do exactly this in WinForms. FASTEST GUN ALERT: please read the following before answering! Thanks guys. :-) Calling .SelectAll() during the .Enter or .GotFocus events won't work because if the user clicked the textbox, the caret will be placed where he clicked, thus deselecting all text. Calling .SelectAll() during the .Click event won't work because the user won't be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user's text selection. Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work because it breaks rule #2 above, it will keep overriding the user's selection on focus. | First of all, thanks for answers! 9 total answers. Thank you. Bad news: all of the answers had some quirks or didn't work quite right (or at all). I've added a comment to each of your posts. Good news: I've found a way to make it work. This solution is pretty straightforward and seems to work in all the scenarios (mousing down, selecting text, tabbing focus, etc.) bool alreadyFocused;...textBox1.GotFocus += textBox1_GotFocus;textBox1.MouseUp += textBox1_MouseUp;textBox1.Leave += textBox1_Leave;...void textBox1_Leave(object sender, EventArgs e){ alreadyFocused = false;}void textBox1_GotFocus(object sender, EventArgs e){ // Select all text only if the mouse isn't down. // This makes tabbing to the textbox give focus. if (MouseButtons == MouseButtons.None) { this.textBox1.SelectAll(); alreadyFocused = true; }}void textBox1_MouseUp(object sender, MouseEventArgs e){ // Web browsers like Google Chrome select the text on mouse up. // They only do it if the textbox isn't already focused, // and if the user hasn't selected all text. if (!alreadyFocused && this.textBox1.SelectionLength == 0) { alreadyFocused = true; this.textBox1.SelectAll(); }} As far as I can tell, this causes a textbox to behave exactly like a web browser's address bar. Hopefully this helps the next guy who tries to solve this deceptively simple problem. Thanks again, guys, for all your answers that helped lead me towards the correct path. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
]
} |
97,506 | This isn't a holy war, this isn't a question of "which is better". What are the pros of using the following format for single statement if blocks. if (x) print "x is true";if(x) print "x is true"; As opposed to if (x) { print "x is true"; }if(x) { print "x is true"; } If you format your single statement ifs without brackets or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you. Update : As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros. Compactness More readable to some Brackets invoke scope, which has a theoretical overhead in some cases | I find this: if( true ) { DoSomething();} else { DoSomethingElse();} better than this: if( true ) DoSomething();else DoSomethingElse(); This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/97506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4668/"
]
} |
97,508 | What libraries can I use to build a GUI for an Erlang application? Please one option per answer. | Most people don't code the actual GUI in Erlang. A more common approach would be to write the GUI layer in Java or C# and then talk to your Erlang app via a socket or pipe. With that in mind, you probably want to look into various libraries for doing RPC between java or .Net applications and Erlang: http://weblogs.asp.net/nleghari/archive/2008/01/08/integrating-net-and-erlang-using-otp-net.aspx http://www.theserverside.com/tt/articles/article.tss?l=IntegratingJavaandErlang EDIT If you're truly set on coding an interface in erlang, you might consider doing a web-based GUI served via Yaws, the erlang web server: http://yaws.hyber.org/appmods.yaws | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7852/"
]
} |
97,522 | What are all the valid self-closing elements (e.g. <br/>) in XHTML (as implemented by the major browsers)? I know that XHTML technically allows any element to be self-closed, but I'm looking for a list of those elements supported by all major browsers. See http://dusan.fora.si/blog/self-closing-tags for examples of some problems caused by self-closing elements such as <div />. | Every browser that supports XHTML (Firefox, Opera, Safari, IE9 ) supports self-closing syntax on every element . <div/> , <script/> , <br></br> all should work just fine. If they don't, then you have HTML with inappropriately added XHTML DOCTYPE. DOCTYPE does not change how document is interpreted. Only MIME type does . W3C decision about ignoring DOCTYPE : The HTML WG has discussed this issue: the intention was to allow old(HTML-only) browsers to accept XHTML 1.0 documents by following theguidelines, and serving them as text/html. Therefore, documents served astext/html should be treated as HTML and not as XHTML. It's a very common pitfall, because W3C Validator largely ignores that rule, but browsers follow it religiously. Read Understanding HTML, XML and XHTML from WebKit blog: In fact, the vast majority of supposedly XHTML documents on the internet are served as text/html . Which means they are not XHTML at all, but actually invalid HTML that’s getting by on the error handling of HTML parsers. All those “Valid XHTML 1.0!” links on the web are really saying “Invalid HTML 4.01!”. To test whether you have real XHTML or invalid HTML with XHTML's DOCTYPE, put this in your document: <span style="color:green"><span style="color:red"/> If it's red, it's HTML. Green is XHTML.</span> It validates, and in real XHTML it works perfectly (see: 1 vs 2 ). If you can't believe your eyes (or don't know how to set MIME types), open your page via XHTML proxy . Another way to check is view source in Firefox. It will highlight slashes in red when they're invalid. In HTML5/XHTML5 this hasn't changed, and the distinction is even clearer, because you don't even have additional DOCTYPE . Content-Type is the king. For the record, the XHTML spec allows any element to be self-closing by making XHTML an XML application : [emphasis mine] Empty-element tags may be used for any element which has no content , whether or not it is declared using the keyword EMPTY. It's also explicitly shown in the XHTML spec : Empty elements must either have an end tag or the start tag must end with /> . For instance, <br/> or <hr></hr> | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/97522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335/"
]
} |
97,578 | Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example: <a href="#" onclick="SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;">Select</a> The <%itemid%> and <%itemname%> are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code. My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler? If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons... This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result. Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me. | In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string. \xXX is for chars < 127, and \uXXXX for Unicode , so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist. For example, <a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/97578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10861/"
]
} |
97,586 | My boss loves VB (we work in a Java shop) because he thinks it's easy to learn and maintain. We want to replace some of the VB with java equivalents using the Eclipse SWT editor, because we think it is almost as easy to maintain. To sell this, we'd like to use an aerith style L&F. Can anyone provide an example of an SWT application still being able to edit the GUI in eclipse, but having the Aerith L&F? | In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string. \xXX is for chars < 127, and \uXXXX for Unicode , so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist. For example, <a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/97586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15441/"
]
} |
97,599 | Being vaguely familiar with the Java world I was googling for a static analysis tool that would also was intelligent enough to fix the issues it finds. I ran at CodePro tool but, again, I'm new to the Java community and don't know the vendors. What tool can you recommend based on the criteria above? | Findbugs PMD Checkstyle Lint4J Classycle JDepend SISSy Google Codepro | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/97599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808/"
]
} |
97,637 | Anyone got a good explanation of "combinators" (Y-combinators etc. and NOT the company )? I'm looking for one for the practical programmer who understands recursion and higher-order functions, but doesn't have a strong theory or math background. (Note: that I'm talking about these things ) | Unless you're deeply into theory, you can regard the Y combinatoras a neat trick with functions, like monads. Monads allow you to chain actions, the Y combinator allows you todefine self-recursive functions. Python has built-in support for self-recursive functions, so youcan define them without Y: > def fun():> print "bla"> fun()> fun()blablabla... fun is accessible inside fun itself, so we can easily call it. But what if Python were different, and fun weren't accessibleinside fun ? > def fun():> print "bla"> # what to do here? (cannot call fun!) The solution is to pass fun itself as an argument to fun : > def fun(arg): # fun receives itself as argument> print "bla"> arg(arg) # to recur, fun calls itself, and passes itself along And Y makes that possible: > def Y(f):> f(f)> Y(fun)blablabla... All it does it call a function with itself as argument. (I don't know if this definition of Y is 100% correct, but I think it's the general idea.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8482/"
]
} |
97,640 | How do I get my project's runtime dependencies copied into the target/lib folder? As it is right now, after mvn clean install the target folder contains only my project's jar, but none of the runtime dependencies. | This works for me: <project> ... <profiles> <profile> <id>qa</id> <build> <plugins> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles></project> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18320/"
]
} |
97,646 | Given a source color of any hue by the system or user, I'd like a simple algorithm I can use to work out a lighter or darker variants of the selected color. Similar to effects used on Windows Live Messenger for styling the user interface. Language is C# with .net 3.5. Responding to comment: Color format is (Alpha)RGB. With values as bytes or floats. Marking answer: For the context of my use (a few simple UI effects), the answer I'm marking as accepted is actually the most simple for this context. However, I've given up votes to the more complex and accurate answers too. Anyone doing more advanced color operations and finding this thread in future should definitely check those out. Thanks SO. :) | Simply multiply the RGB values by the amount you want to modify the level by. If one of the colors is already at the max value, then you can't make it any brighter (using HSV math anyway.) This gives the exact same result with a lot less math as switching to HSV and then modifying V. This gives the same result as switching to HSL and then modifying L, as long as you don't want to start losing saturation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/97646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
]
} |
97,663 | Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc. However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right. I click on Windows|Preferences and type in "wrap" and get: - Java | Code Style | Formatter- Java | Editor | Typing- Web and XML | CSS Files | Source I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect. How can I get word wrap to work in Eclipse PDT for PHP files? | This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in Eclipse Word-Wrap To install it, add the following update site in Eclipse: AhtiK Eclipse WordWrap 0.0.5 Update Site | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/97663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
} |
97,694 | I've been somewhat spoiled using Eclipse and java. I started using vim to do C coding in a linux environment, is there a way to have vim automatically do the proper spacing for blocks? So after typing a { the next line will have 2 spaces indented in, and a return on that line will keep it at the same indentation, and a } will shift back 2 spaces? | These two commands should do it: :set autoindent:set cindent For bonus points put them in a file named .vimrc located in your home directory on linux | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
]
} |
97,741 | Never used a cache like this before. The problem is that I want to load 500,000 + records out of a database and do some selecting/filtering wicked fast. I'm thinking about using a cache, and preliminarily found EHCache and OSCache , any opinions? | Judging by their releases page , OSCache has not been actively maintained since 2007. This is not a good thing. EhCache, on the other hand, is under constant development. For that reason alone, I would choose EhCache. Edit Nov 2013: OSCache, like the rest of OpenSymphony, is dead. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/97741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143/"
]
} |
97,781 | Part of a new product I have been assigned to work on involves server-side conversion of the 'common' video formats to something that Flash can play. As far as I know, my only option is to convert to FLV. I have been giving ffmpeg a go around, but I'm finding a few WMV files that come out with garbled sound (I've tried playing with the audio rates). Are there any other 'good' CLI converters for Linux? Or are there other video formats that Flash can play? | Flash can play the following formats: FLV with AAC or MP3 audio, and FLV1 (Sorenson Spark H.263), VP6, or H.264 video.MP4 with AAC or MP3 audio, and H.264 video (mp4s must be hinted with qt-faststart or mp4box). ffmpeg is an overall good conversion utility; mencoder works better with obscure and proprietary formats (due to the w32codecs binary decoder package) but its muxing is rather suboptimal (read: often totally broken). One solution might be to encode H.264 with x264 through mencoder, and then mux separately with mp4box. As a developer of x264 (and avid user of flash for online video playback), I've had quite a bit of experience in this kind of stuff, so if you want more assistance I'm also available on Freenode IRC on #x264, #ffmpeg, and #mplayer. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2192/"
]
} |
97,850 | For my school work, I do a lot of switching computers (from labs to my laptop to the library). I'd kind of like to put this code under some kind of version control. Of course the problem is that I can't always install additional software on the computers I use. Is there any kind of version control system that I can keep on a thumb drive? I have a 2GB drive to put this on, but I can get a bigger one if necessary. The projects I'm doing aren't especially big FYI. EDIT: This needs to work under windows. EDIT II: Bazaar ended up being what I chose. It's even better if you go with TortoiseBzr. | You could use Portable Python and Bazaar (Bazaar is a Python app). I like to use Bazaar for my own personal projects because of its extreme simplicity. Plus, it can be portable because Python can be portable. You will just need to install it's dependencies in your Portable Python installation as well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
97,865 | I am developing a web app that will be hit frequently by mobile browsers. I am wondering if there is a way to get enough information from the browser request to lookup position data (triangulation or GPS) Not from the request directly, of course. A colleague suggested there some carriers supply a unique identifier in the request header that can be sent to a web service exposed by said provider that will return position data if the customer has enabled that. Can anyone point me in the right direction for this or any other method for gleaning position data, even very approximate. Obviously this is app candy, e.g. if the data is not available the app doesn't really care... Or perhaps a web service by carrier that will provide triangulated data by IP? | Google has ClientLocation as part of their AJAX APIs. You'll need to load Google's AJAX API (requires an API key) and it'll try to resolve the user's location data for you. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/97865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67/"
]
} |
97,875 | I need a way to recursively delete a folder and its children. Is there a prebuilt tool for this, or do I need to write one? DEL /S doesn't delete directories. DELTREE was removed from Windows 2000+ | RMDIR or RD if you are using the classic Command Prompt (cmd.exe): rd /s /q "path" RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S If you are using PowerShell you can use Remove-Item (which is aliased to del , erase , rd , ri , rm and rmdir ) and takes a -Recurse argument that can be shorted to -r rd -r "path" | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/97875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
97,948 | What is std::pair for, why would I use it, and what benefits does boost::compressed_pair bring? | std::pair is a data type for grouping two values together as a single object. std::map uses it for key, value pairs. While you're learning pair , you might check out tuple . It's like pair but for grouping an arbitrary number of values. tuple is part of TR1 and many compilers already include it with their Standard Library implementations. Also, checkout Chapter 1, "Tuples," of the book The C++ Standard Library Extensions: A Tutorial and Reference by Pete Becker, ISBN-13: 9780321412997, for a thorough explanation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/97948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18352/"
]
} |
97,984 | When a PHP application makes a database connection it of course generally needs to pass a login and password. If I'm using a single, minimum-permission login for my application, then the PHP needs to know that login and password somewhere. What is the best way to secure that password? It seems like just writing it in the PHP code isn't a good idea. | Several people misread this as a question about how to store passwords in a database. That is wrong. It is about how to store the password that lets you get to the database. The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/97984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18359/"
]
} |
97,987 | What's the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions. switch statement: // numError is an error enumeration type, with 0 being the non-error case// fire_special_event() is a stub method for the shared processingswitch (numError){ case ERROR_01 : // intentional fall-through case ERROR_07 : // intentional fall-through case ERROR_0A : // intentional fall-through case ERROR_10 : // intentional fall-through case ERROR_15 : // intentional fall-through case ERROR_16 : // intentional fall-through case ERROR_20 : { fire_special_event(); } break; default: { // error codes that require no additional action } break; } if statement: if ((ERROR_01 == numError) || (ERROR_07 == numError) || (ERROR_0A == numError) || (ERROR_10 == numError) || (ERROR_15 == numError) || (ERROR_16 == numError) || (ERROR_20 == numError)){ fire_special_event();} | Use switch. In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement. In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/97987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8883/"
]
} |
98,033 | Several Linq.Enumerable functions take an IEqualityComparer<T> . Is there a convenient wrapper class that adapts a delegate(T,T)=>bool to implement IEqualityComparer<T> ? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution. Specifically, I want to do set operations on Dictionary s, using only the Keys to define membership (while retaining the values according to different rules). | When you want to customize equality checking, 99% of the time you're interested in defining the keys to compare by, not the comparison itself. This could be an elegant solution (concept from Python's list sort method ). Usage: var foo = new List<string> { "abc", "de", "DE" };// case-insensitive distinctvar distinct = foo.Distinct(new KeyEqualityComparer<string>( x => x.ToLower() ) ); The KeyEqualityComparer class: public class KeyEqualityComparer<T> : IEqualityComparer<T>{ private readonly Func<T, object> keyExtractor; public KeyEqualityComparer(Func<T,object> keyExtractor) { this.keyExtractor = keyExtractor; } public bool Equals(T x, T y) { return this.keyExtractor(x).Equals(this.keyExtractor(y)); } public int GetHashCode(T obj) { return this.keyExtractor(obj).GetHashCode(); }} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9990/"
]
} |
98,053 | What is your single favorite mocking library for Python? | I've only used one, but I've had good results with Michael Foord's Mock: http://www.voidspace.org.uk/python/mock/ . Michael's introduction says it better than I could: There are already several Python mocking libraries available, so why another one? Most mocking libraries follow the 'record -> replay' pattern of mocking. I prefer the 'action -> assertion' pattern, which is more readable and intuitive particularly when working with the Python unittest module. ... It also provides utility functions / objects to assist with testing, particularly monkey patching. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/98053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
} |
98,079 | I often refactor code first by creating an inner class inside the class I'm working on--When I'm done, I move the entire thing into a new class file. This makes refactoring code into the new class extremely easy because A) I'm only dealing with a single file, and B) I don't create new files until I have a pretty good idea of the name/names (Sometimes it ends up as more than one class). Is there any way Eclipse can help me with the final move? I should just be able to tell it what package I want the class in, it can figure out the filename from the class name and the directory from the package. This seems like a trivial refactor and really obvious, but I can't figure out the keystrokes/gestures/whatever to make it happen. I've tried dragging, menus, context menus, and browsing through the keyboard shortcuts. Anyone know this one? [edit] These are already "Top Level" classes in this file, not inner classes, and "Move" doesn't seem to want to create a new class for me. This is the hard way that I usually do it--involves going out, creating an empty class, coming back and moving. I would like to do the whole thing in a single step. | I'm sorry I gave the wrong answer before. I rechecked, and it didn't do quite want you want. I did find a solution for you though, again, in 3.4. Highlight the class, do a copy CTRL-C or cut CTRL-X, click on the package you want the class do go into, and do a paste, CTRL-V. Eclipse will auto generate the class for you. Convert Member Type to Top Level doesn't quite work. Doing that will create a field of the outer class and generate a constructor that takes the outer class as a parameter. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12943/"
]
} |
98,090 | I have a system that combines the best and worst of Java and PHP. I am trying to migrate a component that was once written in PHP into a Java One. Does anyone have some tips for how I can parse a PHP serialized datastructure in Java? By serialized I mean output from php's serialize function. | I'm sorry I gave the wrong answer before. I rechecked, and it didn't do quite want you want. I did find a solution for you though, again, in 3.4. Highlight the class, do a copy CTRL-C or cut CTRL-X, click on the package you want the class do go into, and do a paste, CTRL-V. Eclipse will auto generate the class for you. Convert Member Type to Top Level doesn't quite work. Doing that will create a field of the outer class and generate a constructor that takes the outer class as a parameter. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
} |
98,124 | Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year? myDate = new Date();year = myDate.getYear(); year = 108? | It's a Y2K thing, only the years since 1900 are counted. There are potential compatibility issues now that getYear() has been deprecated in favour of getFullYear() - from quirksmode : To make the matter even more complex, date.getYear() is deprecated nowadays and you should use date.getFullYear(), which, in turn, is not supported by the older browsers. If it works, however, it should always give the full year, ie. 2000 instead of 100. Your browser gives the following years with these two methods: * The year according to getYear(): 108* The year according to getFullYear(): 2008 There are also implementation differences between Internet Explorer and Firefox, as IE's implementation of getYear() was changed to behave like getFullYear() - from IBM : Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return "98" for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear(). Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/98124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
]
} |
98,127 | My domain (let's call it www.example.com) creates a cookie.On another site (let's say, www.myspace.com), my domain is loaded within an iFrame. On every browser (Firefox, Opera, Camino, Safari, etc...) except for Internet Explorer, I can access my own cookie. In IE, it doesn't give me access to the cookie from within the iFrame. Is there a way to get around this? Really, this makes no sense because the site trying to access the cookie is www.example.com and the cookie is owned by www.example.com. But for some reason, IE thinks the iFrame makes them unrelated. | Internet Explorer's default privacy setting means that 3rd-party cookies (e.g. those in iframes) are treated differently to 1st party cookies. (by default, 3rd party cookies are silently rejected). For IE6 to accept cookies in an iframe, you need to ensure your site is delivering a P3P compact header. See http://msdn.microsoft.com/en-us/library/ms537343.aspx for more. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13002/"
]
} |
98,135 | I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable? If I run the following code: >>> import django.template>>> from django.template import Template, Context>>> t = Template('My name is {{ my_name }}.') I get: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. | The solution is simple. It's actually well documented , but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.) The following code works: >>> from django.template import Template, Context>>> from django.conf import settings>>> settings.configure()>>> t = Template('My name is {{ my_name }}.')>>> c = Context({'my_name': 'Daryl Spitzer'})>>> t.render(c)u'My name is Daryl Spitzer.' See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/98135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
} |
98,153 | I've found the standard hashing function on VS2005 is painfully slow when trying to achieve high performance look ups. What are some good examples of fast and efficient hashing algorithms that should void most collisions? | I worked with Paul Larson of Microsoft Research on some hashtable implementations. He investigated a number of string hashing functions on a variety of datasets and found that a simple multiply by 101 and add loop worked surprisingly well. unsigned inthash( const char* s, unsigned int seed = 0){ unsigned int hash = seed; while (*s) { hash = hash * 101 + *s++; } return hash;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13646/"
]
} |
98,224 | After downloading files from a remote UNIX FTP server, you want to verify that you have downloaded all the files correctly. Minimal you will get information similar to "dir /s" command in Windows command prompt. The FTP client runs on Windows. | Sadly this was written for Unix/Linux users :/ Personally, I would install CYGWIN just to get Linux binaries of LFTP/RSYNC to work on windows, as there appears not to be anything that competes with it. As @zadok.myopenid.com mentioned rsync, this appears to be a windows build for it using CYGWIN ( if you manage to be able to get ssh access to the box eventually ) http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp Rsync is handy in that it will compare everything with check sums, and optimally transfer partial change blocks. If you get CYGWIN/Linux: http://lftp.yar.ru/ is my favorite exploration tool for this. It can do almost everything bash can do, albeit remotely. Example: $ lftp mirror.3fl.net.aulftp mirror.3fl.net.au:~> ls drwxr-xr-x 14 root root 4096 Nov 27 2007 gamesdrwx------ 2 root root 16384 Apr 13 2006 lost+founddrwxr-xr-x 15 mirror mirror 4096 Jul 15 05:20 publftp mirror.3fl.net.au:/> cd games/misclftp mirror.3fl.net.au:/games/misc>find././dreamchess/./dreamchess/full_game/ ./dreamchess/full_game/dreamchess-0.2.0-win32.exe ./frets_on_fire/./frets_on_fire/full_game/ ./frets_on_fire/full_game/FretsOnFire-1.2.451-macosx.zip ./frets_on_fire/full_game/FretsOnFire-1.2.512-win32.zip./frets_on_fire/full_game/FretsOnFire_ghc_mod.zip./gametap_setup.exe......lftp mirror.3fl.net.au:/games/misc> du gametap_setup.exe 32442 gametap_setup.exelftp mirror.3fl.net.au:/games/misc> du -sh gametap_setup.exe 32M gametap_setup.exelftp mirror.3fl.net.au:/games/misc> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13584/"
]
} |
98,242 | Possible Duplicate: Pre & post increment operator behavior in C, C++, Java, & C# Here is a test case: void foo(int i, int j){ printf("%d %d", i, j);}...test = 0;foo(test++, test); I would expect to get a "0 1" output, but I get "0 0"What gives?? | This is an example of unspecified behavior. The standard does not say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order. In this case, it looks like actually processes the arguments right to left instead of the expected left to right. In general, doing side-effects in arguments is bad programming practice. Instead of foo(test++, test); you should write foo(test, test+1); test++; It would be semantically equivalent to what you are trying to accomplish. Edit:As Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed undefined . So the compiler is free to generate whatever code it wants. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
98,268 | I'm referring to distinctions such as in this answer : ...bash isn't for writing applications it's for, well, scripting. So sure, your application might have some housekeeping scripts but don't go writing critical-business-logic.sh because another language is probably better for stuff like that. As programmer who's worked in many languages, this seems to be C, Java and other compiled language snobbery. I'm not looking for reenforcement of my opinion or hand-wavy answers. Rather, I genuinely want to know what technical differences are being referred to. (And I use C in my day job, so I'm not just being defensive.) | Traditionally a program is compiled and a script is interpreted, but that is not really important anymore. You can generate a compiled version of most scripts if you really want to, and other 'compiled' languages like Java are in fact interpreted (at the byte code level.) A more modern definition might be that a program is intended to be used by a customer (perhaps an internal one) and thus should include documentation and support, while a script is primarily intended for the use of the author. The web is an interesting counter example. We all enjoy looking things up with the Google search engine. The bulk of the code that goes into creating the 'database' it references is used only by its authors and maintainers. Does that make it a script? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
]
} |
98,310 | (I don't want to hear about how crazy I am to want that! :) Focus-follows-mouse is also known as point-to-focus, pointer focus, and (in some implementations) sloppy focus. [Add other terms that will make this more searchable!] X-mouse | I've been coming back to this question periodically for about 10 years and I finally found a simple solution: AutoRaise https://github.com/sbmpost/AutoRaise By default it enables focus-follows-mouse AND autoraise. You can delay the autoraise with a config option. It also has what they call "warp" function that centers the mouse pointer in a window when you Command-Tab to the window. I never knew I needed this until I tried it, but once I tried it, I can't live without it! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
]
} |
98,340 | An example of unspecified behavior in the C language is the order of evaluation of arguments to a function. It might be left to right or right to left, you just don't know. This would affect how foo(c++, c) or foo(++c, c) gets evaluated. What other unspecified behavior is there that can surprise the unaware programmer? | A language lawyer question. Hmkay. My personal top3: violating the strict aliasing rule violating the strict aliasing rule violating the strict aliasing rule :-) Edit Here is a little example that does it wrong twice: (assume 32 bit ints and little endian) float funky_float_abs (float a){ unsigned int temp = *(unsigned int *)&a; temp &= 0x7fffffff; return *(float *)&temp;} That code tries to get the absolute value of a float by bit-twiddling with the sign bit directly in the representation of a float. However, the result of creating a pointer to an object by casting from one type to another is not valid C. The compiler may assume that pointers to different types don't point to the same chunk of memory. This is true for all kind of pointers except void* and char* (sign-ness does not matter). In the case above I do that twice. Once to get an int-alias for the float a, and once to convert the value back to float. There are three valid ways to do the same. Use a char or void pointer during the cast. These always alias to anything, so they are safe. float funky_float_abs (float a){ float temp_float = a; // valid, because it's a char pointer. These are special. unsigned char * temp = (unsigned char *)&temp_float; temp[3] &= 0x7f; return temp_float;} Use memcopy. Memcpy takes void pointers, so it will force aliasing as well. float funky_float_abs (float a){ int i; float result; memcpy (&i, &a, sizeof (int)); i &= 0x7fffffff; memcpy (&result, &i, sizeof (int)); return result;} The third valid way: use unions. This is explicitly not undefined since C99: float funky_float_abs (float a){ union { unsigned int i; float f; } cast_helper; cast_helper.f = a; cast_helper.i &= 0x7fffffff; return cast_helper.f;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/98340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
98,359 | How do you implement the fastest possible Gaussian blur algorithm? I am going to implement it in Java, so GPU solutions are ruled out. My application, planetGenesis , is cross platform, so I don't want JNI . | Math jocks are likely to know this, but for anyone else.. Due to a nice mathematical propertiy of the Gaussian, you can blur a 2D image quickly by first running a 1D Gaussian blur on each row of the image, then run a 1D blur on each column. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/98359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18390/"
]
} |
98,376 | I need to store some simple properties in a file and access them from Ruby. I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read. So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort? I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax"). I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line.... UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone! | Is this for a Rails application or a Ruby one? Really with either you may be able to stick your properties in a yaml file and then YAML::Load(File.open("file")) it. NOTE from Mike Stone: It would actually be better to do: File.open("file") { |yf| YAML::load(yf) } or YAML.load_file("file") as the ruby docs suggest, otherwise the file won't be closed till garbage collection, but good suggestion regardless :-) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
98,449 | How would I go about converting an address or city to a latitude/longitude? Are there commercial outfits I can "rent" this service from? This would be used in a commercial desktop application on a Windows PC with fulltime internet access. | Google has a geocoding API which seems to work pretty well for most of the locations that they have Google Maps data for. http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html They provide online geocoding (via JavaScript): http://code.google.com/apis/maps/documentation/services.html#Geocoding Or backend geocoding (via an HTTP request): http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct The data is usually the same used by Google Maps itself. (note that there are some exceptions to this, such as the UK or Israel, where the data is from a different source and of slightly reduced quality) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17259/"
]
} |
98,454 | There are a number of other questions related to this topic: Whats a good standard code layout for a php application (deleted) How to structure a java application, in other words: where do I put my classes? Recommended Source Control Directory Structure? Structure of Projects in Version Control I could not find any specific to VSTF, which has some capabilities like Team Build, integrated Unit Testing, etc. I'm wondering if these capabilities lead to a slightly different source layout recommendation. Please post example of high level directory structures that you have had good luck with an explain why you like them. I'll let people vote on a "best" approach and I'll award the answer in a few days. | Google has a geocoding API which seems to work pretty well for most of the locations that they have Google Maps data for. http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html They provide online geocoding (via JavaScript): http://code.google.com/apis/maps/documentation/services.html#Geocoding Or backend geocoding (via an HTTP request): http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct The data is usually the same used by Google Maps itself. (note that there are some exceptions to this, such as the UK or Israel, where the data is from a different source and of slightly reduced quality) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
]
} |
98,489 | I'm pretty used to how to do CVS merges in Eclipse, and I'm otherwise happy with the way that both Subclipse and Subversive work with the SVN repository, but I'm not quite sure how to do merges properly. When I do a merge, it seems to want to stick the merged files in a seperate directory in my project rather than overwriting the old files that are to be replaced in the merge, as I am used to in CVS. The question is not particular to either Subclipse or Subversive. Thanks for the help! | Merging an entire branch into trunk Inspect the Branch project history to determine the version from which the branch was taken by default Eclipse Team "History" only shows the past 25 revisions so you will have to click the button in that view labeled "Show All" when you say "Show All" it will take you back past the branch date and show you all the history for trunk as well so you'll have to search for your comment where you branched NOTE : if you use Tortise SVN for this same task (navigate to the branch and select "Show Log") it will show you only the branch history so you can tell exactly where the branch began So now I know that 82517 was the first version ID of the branch history. So all versions of the branch past 82517 have changes that I want to merge into trunk Now go to the "trunk" project in your Eclipse workspace and select "right click - Team - Merge" The default view is the 1 url merge select the URL of the branch from which you are merging under Revisions select "All" press OK This will take you to the "Team Synchronizing" perspective (if it doesn't you should go there yourself) in order to resolve conflicts (see below) Re-Merging more branch changes into trunk Insepct the trunk project history to determine the last time you merged into trunk (you should have commented this) for the sake of argument let's say this version was 82517 So now I know that any version greater than 82517 in the branch needs to be merged into trunk Now go to the "trunk" project in your Eclipse workspace and select "right click - Team - Merge" The default view is the 1 url merge select the URL of the branch from which you are merging under Revisions select "Revisions" radio button and click "Browse" this will open up a list of the latest 25 branch revisions select all the revisions with a number greater than 82517 press OK (you should see the revision list in the input field beside the radio button) press OK This will take you to the "Team Synchronizing" perspective (if it doesn't you should go there yourself) in order to resolve conflicts (see below) Resolving Conflicts You should be at the "Team Synchronizing" perspective. This will look like any regular synchronization for commit purposes where you see files that are new and files that have conflicts. For every file where you see a conflict choose "right click - Edit Conflicts" (do not double click the file, it will bring up the commit diff version tool, this is VERY different) if you see stuff like "<<<<<<< .working" or ">>>>>>> .merge-right.r84513" then you are in the wrong editing mode once you have resolved all the conflicts in that file, tell the file to "mark as merged" once all the files are free of conflicts you can then synchronize your Eclipse project and commit the files to SVN | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13812/"
]
} |
98,559 | uint color; bool parsedhex = uint.TryParse(TextBox1.Text, out color); //where Text is of the form 0xFF0000if(parsedhex) //... doesn't work. What am i doing wrong? | Try Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/98559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
]
} |
98,606 | What is your favorite Visual Studio keyboard shortcut? I'm always up for leaving my hands on the keyboard and away from the mouse! One per answer please. | Ctrl + - and the opposite Ctrl + Shift + - . Move cursor back (or forwards) to the last place it was. No more scrolling back or PgUp / PgDown to find out where you were. This switches open windows in Visual Studio: Ctrl + tab and the opposite Ctrl + Shift + tab | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/98606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13791/"
]
} |
98,610 | By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences. | In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters From there, uncheck .* resources. So Package Explorer -> View Menu -> Filters -> uncheck .* resources . With Eclipse Kepler and OS X this is a bit different: Package Explorer -> Customize View -> Filters -> uncheck .* resources | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/98610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
]
} |
98,628 | Can anyone point me to a library for 2D game physics, etc for programming gravity, jumping actions, etc for a 2d platform/sidescrolling game ?Or could you suggest some algorithms for side scroller like mario, sonic etc? | It sounds like Chipmunk might meet your needs. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8786/"
]
} |
98,641 | I've just started one of my courses, as classes just began 2 weeks ago, and we are learning Scheme right now in one for I assume some reason later on, but so far from what he is teaching is basically how to write in scheme. As I sit here trying to stay awake I'm just trying to grasp why I would want to know this, and why anyone uses it. What does it excel at? Next week I plan to ask him, whats the goal to learn here other than just how to write stuff in scheme. | It's a functional programming language and will do well broaden your experience. Even if you don't use it in the real world doesn't mean it doesn't have any value. It will help you master things like recursion and help to force you to think of problems in different ways than you normally would. I wish my school forced us to learn a functional programming language. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/98641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18431/"
]
} |
98,650 | When asking about common undefined behavior in C , people sometimes refer to the strict aliasing rule. What are they talking about? | A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to uint32_t s or uint16_t s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules. So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this: typedef struct Msg{ unsigned int a; unsigned int b;} Msg;void SendWord(uint32_t);int main(void){ // Get a 32-bit buffer from the system uint32_t* buff = malloc(sizeof(Msg)); // Alias that buffer through message Msg* msg = (Msg*)(buff); // Send a bunch of messages for (int i = 0; i < 10; ++i) { msg->a = i; msg->b = i+1; SendWord(buff[0]); SendWord(buff[1]); }} The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a compatible type or one of the other types allowed by C 2011 6.5 paragraph 7 1 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code. (GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.) To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of buff every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load buff[0] and buff[1] into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of buff could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced. Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have. void SendMessage(uint32_t* buff, size_t size32){ for (int i = 0; i < size32; ++i) { SendWord(buff[i]); }} And rewrote our earlier loop to take advantage of this convenient function for (int i = 0; i < 10; ++i){ msg->a = i; msg->b = i+1; SendMessage(buff, 2);} The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If SendMessage is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help. So how do I get around this? Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11. union { Msg msg; unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)]; }; You can disable strict aliasing in your compiler ( f[no-]strict-aliasing in gcc)) You can use char* for aliasing instead of your system's word. The rules allow an exception for char* (including signed char and unsigned char ). It's always assumed that char* aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars. Beginner beware This is only one potential minefield when overlaying two types onto each other. You should also learn about endianness , word alignment , and how to deal with alignment issues through packing structs correctly. Footnote 1 The types that C 2011 6.5 7 allows an lvalue to access are: a type compatible with the effective type of the object, a qualified version of a type compatible with the effective type of the object, a type that is the signed or unsigned type corresponding to the effective type of the object, a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object, an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or a character type. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/98650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
98,687 | I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework. The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect. What is the best "drop in" solution to switch this over to using connection pooling in python? I am imagining something like the commons DBCP solution for Java. The process is long running and has many threads that need to make requests, but not all at the same time... specifically they do quite a lot of work before brief bursts of writing out a chunk of their results. Edited to add:After some more searching I found anitpool.py which looks decent, but as I'm relatively new to python I guess I just want to make sure I'm not missing a more obvious/more idiomatic/better solution. | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes. It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python is OO, and the mapping from a SQL row to an object is absolutely essential. There aren't many use cases where you deal with SQL rows that don't map to Python objects. I think that SQLAlchemy or SQLObject (and the associated connection pooling) are the more idiomatic Pythonic solutions. Pooling as a separate feature isn't very common because pure SQL (without object mapping) isn't very popular for the kind of complex, long-running processes that benefit from connection pooling. Yes, pure SQL is used, but it's always used in simpler or more controlled applications where pooling isn't helpful. I think you might have two alternatives: Revise your classes to use SQLAlchemy or SQLObject. While this appears painful at first (all that work wasted), you should be able to leverage all the design and thought. It's merely an exercise in adopting a widely-used ORM and pooling solution. Roll out your own simple connection pool using the algorithm you outlined -- a simple Set or List of connections that you cycle through. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/98687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.