source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
146,896 | How can I access UserId in ASP.NET Membership without using Membership.GetUser(username) in ASP.NET Web Application Project? Can UserId be included in Profile namespace next to UserName ( System.Web.Profile.ProfileBase )? | Try this: MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);Response.Write("CurrentUser ID :: " + CurrentUser.ProviderUserKey); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/146896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
]
} |
146,924 | I'm using C and sometimes I have to handle paths like C:\Whatever C:\Whatever\ C:\Whatever\Somefile Is there a way to check if a given path is a directory or a given path is a file? | stat() will tell you this. struct stat s;if( stat(path,&s) == 0 ){ if( s.st_mode & S_IFDIR ) { //it's a directory } else if( s.st_mode & S_IFREG ) { //it's a file } else { //something else }}else{ //error} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/146924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87/"
]
} |
146,936 | As you work in a legacy codebase what will have the greatest impact over time that will improve the quality of the codebase? Remove unused code Remove duplicated code Add unit tests to improve test coverage where coverage is low Create consistent formatting across files Update 3rd party software Reduce warnings generated by static analysis tools (i.e.Findbugs) The codebase has been written by many developers with varying levels of expertise over many years, with a lot of areas untested and some untestable without spending a significant time on writing tests. | Read Michael Feather's book "Working effectively with Legacy Code" This is a GREAT book. If you don't like that answer, then the best advice I can give would be: First, stop making new legacy code[1] [1]: Legacy code = code without unit tests and therefore an unknown Changing legacy code without an automated test suite in place is dangerous and irresponsible. Without good unit test coverage, you can't possibly know what affect those changes will have. Feathers recommends a "stranglehold" approach where you isolate areas of code you need to change, write some basic tests to verify basic assumptions, make small changes backed by unit tests, and work out from there. NOTE: I'm not saying you need to stop everything and spend weeks writing tests for everything. Quite the contrary, just test around the areas you need to test and work out from there. Jimmy Bogard and Ray Houston did an interesting screen cast on a subject very similar to this: http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/05/06/pablotv-eliminating-static-dependencies-screencast.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
]
} |
146,986 | I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like #ifdef IPHONE_SDK... . Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help. | It's in the SDK docs under "Compiling source code conditionally" The relevant definitions are TARGET_OS_IPHONE (and he deprecated TARGET_IPHONE_SIMULATOR), which are defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write: #include "TargetConditionals.h" but this is no longer necessary on the current (xCode 6/iOS8) toolchain. So, for example, if you want to only compile a block of code if you are building for the device, then you should do #if !(TARGET_OS_SIMULATOR)...#endif | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/146986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
]
} |
146,989 | One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a this . For example: this.process(this.event) . A few of my students commented on this, and I'm wondering if I am teaching bad habits. My rationale is: Makes code more readable — Easier to distinguish fields from local variables. Makes it easier to distinguish standard calls from static calls (especially in Java) Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass. Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable? Note: I turned it into a CW since there really isn't a correct answer. | I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see "this" is when it is required, for example: this.fieldName = fieldName When assigning the field. That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m_fieldName" or "_fieldName" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/146989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
]
} |
147,062 | Does iPhone support XML-RPC, Is their any open source framework which I can use? | Checkout the source for the wordpress app. They might be using XML-RPC. :) http://iphone.wordpress.org/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451867/"
]
} |
147,083 | I have a standard windows server that inherits from the ServiceBase class. On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does. For example: protected override void OnStart(string[] args){ if (condition == false) { EventLog.WriteEntry("Pre-condition not met, service was unable to start"); // TODO: Convert service state to "Stopped" because my precondition wasn't met return; } InnitializeService();} Anybody have a good example for how a service can control its own state? | Checkout the source for the wordpress app. They might be using XML-RPC. :) http://iphone.wordpress.org/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049/"
]
} |
147,130 | I'm not asking this question because of the merits of garbage collection first of all. My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time. With that said, why hasn't it been added? There are already some garbage collectors for C++. Is this just one of those "easier said than done" type things? Or are there other reasons it hasn't been added (and won't be added in C++11)? Cross links: Garbage collectors for C++ Just to clarify, I understand the reasons why C++ didn't have a garbage collector when it was first created. I'm wondering why the collector can't be added in. | Implicit garbage collection could have been added in, but it just didn't make the cut. Probably due to not just implementation complications, but also due to people not being able to come to a general consensus fast enough. A quote from Bjarne Stroustrup himself: I had hoped that a garbage collectorwhich could be optionally enabledwould be part of C++0x, but there wereenough technical problems that I haveto make do with just a detailedspecification of how such a collectorintegrates with the rest of thelanguage, if provided. As is the casewith essentially all C++0x features,an experimental implementation exists. There is a good discussion of the topic here . General overview: C++ is very powerful and allows you to do almost anything. For this reason it doesn't automatically push many things onto you that might impact performance. Garbage collection can be easily implemented with smart pointers (objects that wrap pointers with a reference count, which auto delete themselves when the reference count reaches 0). C++ was built with competitors in mind that did not have garbage collection. Efficiency was the main concern that C++ had to fend off criticism from in comparison to C and others. There are 2 types of garbage collection... Explicit garbage collection: C++0x has garbage collection via pointers created with shared_ptr If you want it you can use it, if you don't want it you aren't forced into using it. For versions before C++0x, boost:shared_ptr exists and serves the same purpose. Implicit garbage collection: It does not have transparent garbage collection though. It will be a focus point for future C++ specs though. Why Tr1 doesn't have implicit garbage collection? There are a lot of things that tr1 of C++0x should have had, Bjarne Stroustrup in previous interviews stated that tr1 didn't have as much as he would have liked. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/147130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
147,173 | I am trying to understand some assembly. The assembly as follows, I am interested in the testl line: 000319df 8b4508 movl 0x08(%ebp), %eax 000319e2 8b4004 movl 0x04(%eax), %eax 000319e5 85c0 testl %eax, %eax 000319e7 7407 je 0x000319f0 I am trying to understand that point of testl between %eax and %eax ? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true? | It tests whether eax is 0, or above, or below. In this case, the jump is taken if eax is 0. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/147173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10733/"
]
} |
147,178 | Suppose I have a date, i.e. year, month and day, as integers. What's a good (correct), concise and fairly readable algorithm for computing the ISO 8601 week number of the week the given date falls into? I have come across some truly horrendous code that makes me think surely there must be a better way. I'm looking to do this in Java but psuedocode for any kind of object-oriented language is fine. | tl;dr LocalDate.of( 2015 , 12 , 30 ) .get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) 53 …or… org.threeten.extra.YearWeek.from ( LocalDate.of( 2015 , 12 , 30 )) 2015-W53 java.time Support for the ISO 8601 week is now built into Java 8 and later, in the java.time framework. Avoid the old and notoriously troublesome java.util.Date/.Calendar classes as they have been supplanted by java.time. These new java.time classes include LocalDate for date-only value without time-of-day or time zone. Note that you must specify a time zone to determine ‘today’ as the date is not simultaneously the same around the world. ZoneId zoneId = ZoneId.of ( "America/Montreal" );ZonedDateTime now = ZonedDateTime.now ( zoneId ); Or specify the year, month, and day-of-month as suggested in the Question. LocalDate localDate = LocalDate.of( year , month , dayOfMonth ); The IsoFields class provides info according to the ISO 8601 standard including the week-of-year for a week-based year. int calendarYear = now.getYear();int weekNumber = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );int weekYear = now.get ( IsoFields.WEEK_BASED_YEAR ); Near the beginning/ending of a year, the week-based-year may be ±1 different than the calendar-year. For example, notice the difference between the Gregorian and ISO 8601 calendars for the end of 2015: Weeks 52 & 1 become 52 & 53. ThreeTen-Extra — YearWeek The YearWeek class represents both the ISO 8601 week-based year number and the week number together as a single object. This class is found in the ThreeTen-Extra project. The project adds functionality to the java.time classes built into Java. ZoneId zoneId = ZoneId.of ( "America/Montreal" );YearWeek yw = YearWeek.now( zoneId ) ; Generate a YearWeek from a date. YearWeek yw = YearWeek.from ( LocalDate.of( 2015 , 12 , 30 )) This class can generate and parse strings in standard ISO 8601 format. String output = yw.toString() ; 2015-W53 YearWeek yw = YearWeek.parse( "2015-W53" ) ; You can extract the week number or the week-based-year number. int weekNumber = yw.getWeek() ;int weekBasedYearNumber = yw.getYear() ; You can generate a particular date ( LocalDate ) by specifying a desired day-of-week to be found within that week. To specify the day-of-week, use the DayOfWeek enum built into Java 8 and later. LocalDate ld = yw.atDay( DayOfWeek.WEDNESDAY ) ; About java.time The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 . The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Where to obtain the java.time classes? Java SE 8 , Java SE 9 , Java SE 10 , Java SE 11 , and later - Part of the standard Java API with a bundled implementation. Java 9 adds some minor features and fixes. Java SE 6 and Java SE 7 Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . Android Later versions of Android bundle implementations of the java.time classes. For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP… . The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9511/"
]
} |
147,181 | If I have a Java source file (*.java) or a class file (*.class), how can I convert it to a .exe file? I also need an installer for my program. | javapackager The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version. – Oracle's documentation The javapackager utility ships with the JDK. It can generate .exe files with the -native exe flag, among many other things. WinRun4J WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits: Uses an INI file for specifying classpath, main class, vm args, program args. Custom executable name that appears in task manager. Additional JVM args for more flexible memory use. Built-in icon replacer for custom icon. [more bullet points follow] – WinRun4J's webpage WinRun4J is an open source utility. It has many features. packr Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications. – packr README packr is another open source tool. JSmooth JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. – JSmooth's website JSmooth is open source and has features, but it is very old. The last release was in 2007. JexePack JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported. – JexePack's website JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013. InstallAnywhere InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship. – InstallAnywhere's website InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files. Executable JAR files As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest . For more information An excellent source of information on this topic is Excelsior's article " Convert Java to EXE – Why, When, When Not and How ". See also the companion article " Best JAR to EXE Conversion Tools, Free and Commercial ". | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/147181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
]
} |
147,187 | What is the practical benefit of using HTTP GET, PUT, DELETE, POST, HEAD? Why not focus on their behavioral benefits (safety and idempotency), forgetting their names, and use GET, PUT or POST depending on which behavior we want? Why shouldn't we only use GET, PUT and POST (and drop HEAD, DELETE)? | The [REST][1] approach uses POST, GET, PUT and DELETE to implement the CRUD rules for a web resource. It's a simple and tidy way to expose objects to requests on the web. It's web services without the overheads. Just to clarify the semantic differences. Each operation is rather different. The point is to have nice HTTP methods that have clear, distinct meanings. POST creates new objects. The URI has no key; it accepts a message body that defines the object. SQL Insert. [ Edit While there's no technical reason for POST to have no key, the REST folks suggest strongly that for POST to have distinct meaning as CREATE, it should not have a key.] GET retrieves existing objects. The URI may have a key, depends on whether you are doing singleton GET or list GET. SQL Select PUT updates an existing object. The URI has a key; It accepts a message body that updates an object. SQL Update. DELETE deletes an existing object. The URI has a key. SQL Delete. Can you update a record with POST instead of PUT? Not without introducing some ambiguity. Verbs should have unambiguous effects. Further, POST URI's have no key, where PUT must have a key. When I POST, I expect a 201 CREATED. If I don't get that, something's wrong. Similarly, when I PUT, I expect a 200 OK. If I don't get that, something's wrong. I suppose you could insist on some ambiguity where POST does either POST or PUT. The URI has to be different; also the associated message could be different. Generally, the REST folks take their cue from SQL where INSERT and UPDATE are different verbs. You could make the case that UPDATE should insert if the record doesn't exist or update if the record does exist. However, it's simpler if UPDATE means UPDATE and failure to update means something's wrong. A secret fall-back to INSERT makes the operation ambiguous. If you're not building a RESTful interface, then it's typical to only use GET and POST for retrieve and create/update. It's common to have URI differences or message content differences to distinguish between POST and PUT when a person is clicking submit on a form. It, however, isn't very clean because your code has to determine if you're in the POST=create case or POST=update case. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731/"
]
} |
147,207 | I'm wondering how you'd implement the following use-case in REST. Is it even possible to do without compromising the conceptual model? Read or update multiple resources within the scope of a single transaction. For example, transfer $100 from Bob's bank account into John's account. As far as I can tell, the only way to implement this is by cheating. You could POST to the resource associated with either John or Bob and carry out the entire operation using a single transaction. As far as I'm concerned this breaks the REST architecture because you're essentially tunneling an RPC call through POST instead of really operating on individual resources. | Consider a RESTful shopping basket scenario. The shopping basket is conceptually your transaction wrapper. In the same way that you can add multiple items to a shopping basket and then submit that basket to process the order, you can add Bob's account entry to the transaction wrapper and then Bill's account entry to the wrapper. When all the pieces are in place then you can POST/PUT the transaction wrapper with all the component pieces. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/147207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731/"
]
} |
147,210 | I have a T-SQL table variable (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done? | If you're using a table variable, you can't do it. If it were a table, you could truncate it or use DBCC CHECKIDENT . But, if you have to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output using ROWNUMBER : DECLARE @t table (pkint int IDENTITY(1,1), somevalue nvarchar(50))INSERT INTO @t (somevalue) VALUES( 'one')INSERT INTO @t (somevalue) VALUES('twp')INSERT INTO @t (somevalue) VALUES('three')SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @tDELETE FROM @tINSERT INTO @t (somevalue) VALUES('four')SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t It's the best you can do with the table variable. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747/"
]
} |
147,240 | ('1' * N) !~ /^1?$|^(11+?)\1+$/ On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works? | You can find a lengthy explanation of this code here: http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
147,267 | Here's what I am trying to do: typedef enum { ONE, TWO, THREE } Numbers; I am trying to write a function that would do a switch case similar to the following: char num_str[10];int process_numbers_str(Numbers num) { switch(num) { case ONE: case TWO: case THREE: { strcpy(num_str, num); //some way to get the symbolic constant name in here? } break; default: return 0; //no match return 1;} Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above? | // Define your enumeration like this (in say numbers.h);ENUM_BEGIN( Numbers ) ENUM(ONE), ENUM(TWO), ENUM(FOUR)ENUM_END( Numbers )// The macros are defined in a more fundamental .h file (say defs.h);#define ENUM_BEGIN(typ) enum typ {#define ENUM(nam) nam#define ENUM_END(typ) };// Now in one and only one .c file, redefine the ENUM macros and reinclude// the numbers.h file to build a string table#undef ENUM_BEGIN#undef ENUM#undef ENUM_END#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {#define ENUM(nam) #nam#define ENUM_END(typ) };#undef NUMBERS_H_INCLUDED // whatever you need to do to enable reinclusion#include "numbers.h"// Now you can do exactly what you want to do, with no retyping, and for any// number of enumerated types defined with the ENUM macro family// Your code follows;char num_str[10];int process_numbers_str(Numbers num) { switch(num) { case ONE: case TWO: case THREE: { strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO" } break; default: return 0; //no match return 1;}// Sweet no ? After being frustrated by this for years, I finally came up// with this solution for my most recent project and plan to reuse the idea// forever | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
]
} |
147,298 | I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator. So far I'm torn between: Sun's umem Google's tcmalloc Intel's threading building blocks allocator Emery Berger's hoard From what I've found hoard might be the fastest, but I hadn't heard of it before today, so I'm skeptical if its really as good as it seems. Anyone have personal experience trying out these allocators? | I've used tcmalloc and read about Hoard. Both have similar implementations and both achieve roughly linear performance scaling with respect to the number of threads/CPUs (according to the graphs on their respective sites). So: if performance is really that incredibly crucial, then do performance/load testing. Otherwise, just roll a dice and pick one of the listed (weighted by ease of use on your target platform). And from trshiv's link , it looks like Hoard, tcmalloc, and ptmalloc are all roughly comparable for speed. Overall, tt looks like ptmalloc is optimized for taking as little room as possible, Hoard is optimized for a trade-off of speed + memory usage, and tcmalloc is optimized for pure speed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
]
} |
147,315 | MySQL specifies the row format of a table as either fixed or dynamic, depending on the column data types. If a table has a variable-length column data type, such as TEXT or VARCHAR, the row format is dynamic; otherwise, it's fixed. My question is, what's the difference between the two row formats? Is one more efficient than the other? | The difference really only matters for MyISAM, other storage engines do not care about the difference. EDIT : Many users commented that InnoDB does care: link 1 by steampowered , link 2 by Kaan . With MyISAM with fixed width rows, there are a few advantages: No row fragmentation: It is possible with variable width rows to get single rows split into multiple sections across the data file. This can increase disk seeks and slow down operations. It is possible to defrag it with OPTIMIZE TABLE, but this isn't always practical. Data file pointer size: In MyISAM, there is a concept of a data file pointer which is used when it needs to reference the data file. For example, this is used in indexes when they refer to where the row actually is present. With fixed width sizes, this pointer is based on the row offset in the file (ie. rows are 1, 2, 3 regardless of their size). With variable width, the pointer is based on the byte offset (ie. rows might be 1, 57, 163). The result is that with large tables, the pointer needs to be larger which then adds potentially a lot more overhead to the table. Easier to fix in the case of corruption. Since every row is the same size, if your MyISAM table gets corrupted it is much easier to repair, so you will only lose data that is actually corrupted. With variable width, in theory it is possible that the variable width pointers get messed up, which can result in hosing data in a bad way. Now the primary drawback of fixed width is that it wastes more space. For example, you need to use CHAR fields instead of VARCHAR fields, so you end up with extra space taken up. Normally, you won't have much choice in the format, since it is dictated based on the schema. However, it might be worth if you only have a few varchar's or a single blob/text to try to optimize towards this. For example, consider switching the only varchar into a char, or split the blob into it's own table. You can read even more about this at: http://dev.mysql.com/doc/refman/5.0/en/static-format.html http://dev.mysql.com/doc/refman/5.0/en/dynamic-format.html | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23107/"
]
} |
147,351 | In general, what needs to be done to convert a 16 bit Windows program to Win32? I'm sure I'm not the only person to inherit a codebase and be stunned to find 16-bit code lurking in the corners. The code in question is C. | The meanings of wParam and lParam have changed in many places. I strongly encourage you to be paranoid and convert as much as possible to use message crackers . They will save you no end of headaches. If there is only one piece of advice I could give you, this would be it. As long as you're using message crackers, also enable STRICT . It'll help you catch the Win16 code base using int where it should be using HWND , HANDLE , or something else. Converting these will greatly help with #9 on this list. hPrevInstance is useless. Make sure it's not used. Make sure you're using Unicode-friendly calls. That doesn't mean you need to convert everything to TCHAR s, but means you better replace OpenFile , _lopen , and _lcreat with CreateFile , to name the obvious LibMain is now DllMain , and the entire library format and export conventions are different Win16 had no VMM. GlobalAlloc , LocalAlloc , GlobalFree , and LocalFree should be replaced with more modern equivalents. When done, clean up calls to LocalLock , LocalUnlock and friends; they're now useless. Not that I can imagine your app doing this, but make sure you don't depend on WM_COMPACTING while you're there. Win16 also had no memory protection. Make sure you're not using SendMessage or PostMessage to send pointers to out-of-process windows. You'll need to switch to a more modern IPC mechanism, such as pipes or memory-mapped files. Win16 also lacked preemptive multitasking. If you wanted a quick answer from another window, it was totally cool to call SendMessage and wait for the message to be processed. That may be a bad idea now. Consider whether PostMessage isn't a better option. Pointer and integer sizes change. Remember to check carefully anywhere you're reading or writing data to disk—especially if they're Win16 structures. You'll need to manually redo them to handle the shorter values. Again, the least painful way to deal with this will be to use message crackers where possible. Otherwise, you'll need to manually hunt down and convert int to DWORD and so on where applicable. Finally, when you've nailed the obvious, consider enabling 64-bit compilation checks. A lot of the issues faced with going from 16 to 32 bits are the same as going from 32 to 64, and Visual C++ is actually pretty smart these days. Not only will you catch some lingering issues; you'll get yourself ready for your eventual Win64 migration, too. EDIT : As @ChrisN points out, the official guide for porting Win16 apps to Win32 is available archived, and both fleshes out and adds to my points above. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16220/"
]
} |
147,362 | Like many companies that require all access be through stored procedures, we seem to have a lot of business logic locked away in sprocs. These things are just plain hard to test, and some of them have become silly long. Does anyone out there have a set of best practices that can make it a little easier to confidently test these things? At present we maintain 30 or so "Problem" databases that we run against. This isn't always particularly well documented and it sure isn't automated. | A colleague swears by the TSQLUnit testing framework . May be worth a look for your needs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327/"
]
} |
147,391 | I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers. I tried something like this: void foo(std::vector<unsigned> &vec, boost::mt19937 &state){ struct bar { boost::mt19937 &_state; unsigned operator()(unsigned i) { boost::uniform_int<> rng(0, i - 1); return rng(_state); } bar(boost::mt19937 &state) : _state(state) {} } rand(state); std::random_shuffle(vec.begin(), vec.end(), rand);} But i get a template error calling random_shuffle with rand. However this works: unsigned bar(unsigned i){ boost::mt19937 no_state; boost::uniform_int<> rng(0, i - 1); return rng(no_state);}void foo(std::vector<unsigned> &vec, boost::mt19937 &state){ std::random_shuffle(vec.begin(), vec.end(), bar);} Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables? | In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs). This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
]
} |
147,416 | In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this: For Each item As Host In hostCollection1 hostCollection2.Add(item)Next My collections are generic collections, inherited from the base class -- Collection(Of ) | You can use AddRange: hostCollection2.AddRange(hostCollection1) . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
]
} |
147,451 | In an HTML form post what are valid characters for creating a multipart boundary? | According to RFC 2046 , section 5.1.1: boundary := 0*69<bchars> bcharsnospace bchars := bcharsnospace / " " bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" So it can be between 1 and 70 characters long, consisting of alphanumeric, and the punctuation you see in the list. Spaces are allowed except at the end. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
]
} |
147,454 | It is much more convenient and cleaner to use a single statement like import java.awt.*; than to import a bunch of individual classes import java.awt.Panel;import java.awt.Graphics;import java.awt.Canvas;... What is wrong with using a wildcard in the import statement? | The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event , and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event . If you import both using the wildcard method, one of these three things happens: You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event , and so you can't even compile. You actually manage only to import one (only one of your two imports does .* ), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong. When you compile your code there is no com.mycompany.calendar.Event , but when they later add one your previously valid code suddenly stops compiling. The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong , but future maintainers will thank you for your clarity otherwise. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/147454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22807/"
]
} |
147,468 | PMD would report a violation for: ArrayList<Object> list = new ArrayList<Object>(); The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead". The following line would correct the violation: List<Object> list = new ArrayList<Object>(); Why should the latter with List be used instead of ArrayList ? | Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future. Here's a good article on the subject. Hope it helps! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22807/"
]
} |
147,486 | Given the following XML structure <html> <body> <div> <span>Test: Text2</span> </div> <div> <span>Test: Text3</span> </div> <div> <span>Test: Text5</span> </div> </body></html> What is the best XPath query to locate any span with text that starts with Test ? | //span[starts-with(.,'Test')] References: http://www.w3.org/TR/xpath/#function-starts-with https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10673/"
]
} |
147,500 | Is it possible to include one CSS file in another? | Yes: @import url("base.css"); Note: The @import rule must precede all other rules (except @charset ). Additional @import statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of base.css and special.css into base-special.css and reference only base-special.css . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/147500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460927/"
]
} |
147,507 | Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlist="*") This doesn't seem to perform as expected (as it doesn't import anything). | Please reconsider. The only thing worse than import * is magic import * . If you really want to: m = __import__ (S)try: attrlist = m.__all__except AttributeError: attrlist = dir (m)for attr in attrlist: globals()[attr] = getattr (m, attr) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
]
} |
147,515 | How do you calculate the least common multiple of multiple numbers? So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers. So far this is how I did it LCM = num1 * num2 / gcd ( num1 , num2 ) With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm But I can't figure out how to calculate it for 3 or more numbers. | You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e. lcm(a,b,c) = lcm(a,lcm(b,c)) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/147515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
]
} |
147,528 | In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display. Here is my DEMO : body { font-family: Trebuchet MS, Verdana, MS Sans Serif; font-size:0.9em; margin:0; padding:0;}div#header { width: 100%; height: 100px;}#header a { background-position: 100px 30px; background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px; height: 80px; display: block;}#header, #menuwrapper { background-repeat: repeat; background-image: url(site-style-images/darkblue_background_color.jpg);}#menu #menuwrapper { height:25px;}div#menuwrapper { width:100%}#menu, #content { width:1024px; margin: 0 auto;}div#menu { height: 25px; background-color:#50657a;} <form id="form1"> <div id="header"> <a title="Home" href="index.html" /> </div> <div id="menuwrapper"> <div id="menu"> </div> </div> <div id="content"> </div></form> | Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using: html,body { height:100%; } You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit. This site has some excellent examples: http://www.brunildo.org/test/html_body_0.html http://www.brunildo.org/test/html_body_11b.html http://www.brunildo.org/test/index.html I also recommend going to http://quirksmode.org/ | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/147528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
]
} |
147,551 | Could Silverlight be used for the same things as jQuery, or are they intended for different things? For example, vb.net could be used for the same stuff as C# while C# is intended for different things than what JavaScript is. Is Silverlight and jQuery like vb.net and C#, or more like C# and JavaScript? | Silverlight can be used to create rich interactive media, and is more akin to Flash than anything else. jQuery is a javascript library. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4495/"
]
} |
147,557 | I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#. In my C++ source I can write LOGERR("Some error");orLOGERR("Error with inputs %s and %d", stringvar, intvar); The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user. Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging? Edit: At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :) | Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference: System.Diagnostics.Trace This includes listeners that listen for your Trace() methods, and then write to a log file/output window/event log, ones in the framework that are included are DefaultTraceListener , TextWriterTraceListener and the EventLogTraceListener . It allows you to specify levels (Warning,Error,Info) and categories. Trace class on MSDN Writing to the Event Log in a Web Application UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6188/"
]
} |
147,572 | class someclass {};class base{ int a; int *pint; someclass objsomeclass; someclass* psomeclass;public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; }}int main(){ base temp();} In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided? int main(){ base *temp = new base();} How about in the above code? How can the memory leaks be avoided after the constructor throws? | Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory. If you use something like Boost's scoped_ptr<> template, your class could look more like: class base{ int a; scoped_ptr<int> pint; someclass objsomeclass; scoped_ptr<someclass> psomeclass; base() : pint( new int), objsomeclass( someclass()), psomeclass( new someclass()) { throw "constructor failed"; a = 43; }} And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations). To sum up (and hopefully this also answers the question about the base* temp = new base(); statement): When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object: the destructor for the object being constructed will not be called. destructors for member objects contained in that object's class will be called the memory for the object that was being constructed will be freed. This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws: catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem. use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
]
} |
147,636 | What is the best way to detect if a user leaves a web page? The onunload JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser). Creating one will probably be blocked by current browsers. | Try the onbeforeunload event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo onbeforeunload Demo . Alternatively, you can send out an Ajax request when he leaves. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/147636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2721/"
]
} |
147,646 | What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. What is the best way to achieve this? | There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than). However; if you just want it to work, then in .NET 3.5 there are some options... I have put together a library here that allows efficient and simple access to operators with generics - such as: T result = Operator.Add(first, second); // implicit <T>; here It can be downloaded as part of MiscUtil Additionally, in C# 4.0, this becomes possible via dynamic : static T Add<T>(T x, T y) { dynamic dx = x, dy = y; return dx + dy;} I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as interface ICalc<T>{ T Add(T,T)() T Subtract(T,T)()} etc, but then you need to pass an ICalc<T>; through all the methods, which gets messy. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9107/"
]
} |
147,659 | How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET. | Execute: SELECT name FROM master.sys.databases This the preferred approach now, rather than dbo.sysdatabases , which has been deprecated for some time. Execute this query: SELECT name FROM master.dbo.sysdatabases or if you prefer EXEC sp_databases | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/147659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21963/"
]
} |
147,661 | I've got a young nephew who aspires to grow up to be a game programmer and i'd like to introduce him to the world of open-source as well as get him a sweet gift. Anything like that out there? | Well, this is a tricky question because we don't know the level your nephew is at, nevermind the fact that it's difficult to produce a very nice showy game without a lot more work than a beginner might put forth. X Game Station Nevertheless, André LaMothe's X Game Station is meant to be exactly the system you're asking for - a beginner's guide and system on how to develop complex programs with interactive elements and gameplay on resource limited hardware. Which is pretty much what a game designer is called on to do. GP32 The GP32 was also meant to fill this gap, but with a much more powerful processor. The successor was never released, and the company went bankrupt shortly after, but you may still be able to find one on ebay or within the communities that developed around the original machine. Google Android You might also consider looking toward the Google Android platform . Cell phone gaming is now and will be one of the biggest platforms in the future. The android isn't set up perfectly for gaming, but it's a good first approximation, isn't horribly expensive and includes a robust development toolset for a high-end mobile processor. Several big name game development companies have already pledged support for this platform, so it will also look good on a resume. But a cheap computer and a VGA graphics book is surprisingly fun as a kid... -Adam | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20132/"
]
} |
147,669 | I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application. This works on all the machines I've tested it on, except one. The problem is that the Delphi application gets "Class not registered" when trying to create the COM object. Now, when I look in the registry under HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID , the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed. I have tried regasm /unregister delphitocsharp.dll , and that removes the registry key. Then if I do regasm delphitocsharp.dll , the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered". DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine. All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused. How can I fix or at least further diagnose this issue? | The GUID in AssemblyInfo becomes the "Type-Library" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example: [Guid("00001111-2222-3333-4444-555566667777"), ComVisible(true)] public class MyCOMRegisteredClass If you don't, then the class either a) won't be registered, or b) if you've defined COMVisible(true) at the assembly level, will be assigned a guid that .NET bakes up for you. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
]
} |
147,713 | In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so: unsigned long value = 0xdeadbeef;value &= ~(1<<10); How do I do that in Python ? | Bitwise operations on Python ints work much like in C. The & , | and ^ operators in Python work just like in C. The ~ operator works as for a signed integer in C; that is, ~x computes -x-1 . You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do (x << 5) & 0xffffffff . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16144/"
]
} |
147,719 | Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive? | Use this: {$IFDEF DEBUG}...{$ENDIF} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
} |
147,741 | In a text file, there is a string "I don't like this". However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use f1 = open (file1, "r")text = f1.read() command to do the reading. Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"? Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion? | Ref: http://docs.python.org/howto/unicode Reading Unicode from a file is therefore simple: import codecswith codecs.open('unicode.rst', encoding='utf-8') as f: for line in f: print repr(line) It's also possible to open files in update mode, allowing both reading and writing: with codecs.open('test', encoding='utf-8', mode='w+') as f: f.write(u'\u4500 blah blah blah\n') f.seek(0) print repr(f.readline()[:1]) EDIT : I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII. If you're trying to convert to an ASCII string, try one of the following: Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python ): >>> teststru'I don\xe2\x80\x98t like this'>>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')'I donat like this' | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/147741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
147,752 | In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this: APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'),)client_approved = models.CharField(choices=APPROVAL_CHOICES) to create a drop down box in your form and force the user to choose one of those options. I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation. | In terms of the forms library, you would use the MultipleChoiceField field with a CheckboxSelectMultiple widget to do that. You could validate the number of choices which were made by writing a validation method for the field: class MyForm(forms.Form): my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple()) def clean_my_field(self): if len(self.cleaned_data['my_field']) > 3: raise forms.ValidationError('Select no more than 3.') return self.cleaned_data['my_field'] To get this in the admin application, you'd need to customise a ModelForm and override the form used in the appropriate ModelAdmin . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23366/"
]
} |
147,784 | With the recent buzz on multicore programming is anyone exploring the possibilities of using MPI ? | I've used MPI extensively on large clusters with multi-core nodes. I'm not sure if it's the right thing for a single multi-core box, but if you anticipate that your code may one day scale larger than a single chip, you might consider implementing it in MPI. Right now, nothing scales larger than MPI. I'm not sure where the posters who mention unacceptable overheads are coming from, but I've tried to give an overview of the relevant tradeoffs below. Read on for more. MPI is the de-facto standard for large-scale scientific computation and it's in wide use on multicore machines already. It is very fast. Take a look at the most recent Top 500 list . The top machines on that list have, in some cases, hundreds of thousands of processors, with multi-socket dual- and quad-core nodes. Many of these machines have very fast custom networks (Torus, Mesh, Tree, etc) and optimized MPI implementations that are aware of the hardware. If you want to use MPI with a single-chip multi-core machine, it will work fine. In fact, recent versions of Mac OS X come with OpenMPI pre-installed, and you can download an install OpenMPI pretty painlessly on an ordinary multi-core Linux machine. OpenMPI is in use at Los Alamos on most of their systems. Livermore uses mvapich on their Linux clusters. What you should keep in mind before diving in is that MPI was designed for solving large-scale scientific problems on distributed-memory systems. The multi-core boxes you are dealing with probably have shared memory . OpenMPI and other implementations use shared memory for local message passing by default, so you don't have to worry about network overhead when you're passing messages to local processes. It's pretty transparent, and I'm not sure where other posters are getting their concerns about high overhead. The caveat is that MPI is not the easiest thing you could use to get parallelism on a single multi-core box. In MPI, all the message passing is explicit. It has been called the "assembly language" of parallel programming for this reason. Explicit communication between processes isn't easy if you're not an experienced HPC person, and there are other paradigms more suited for shared memory ( UPC , OpenMP , and nice languages like Erlang to name a few) that you might try first. My advice is to go with MPI if you anticipate writing a parallel application that may need more than a single machine to solve. You'll be able to test and run fine with a regular multi-core box, and migrating to a cluster will be pretty painless once you get it working there. If you are writing an application that will only ever need a single machine, try something else. There are easier ways to exploit that kind of parallelism. Finally, if you are feeling really adventurous, try MPI in conjunction with threads, OpenMP, or some other local shared-memory paradigm. You can use MPI for the distributed message passing and something else for on-node parallelism. This is where big machines are going; future machines with hundreds of thousands of processors or more are expected to have MPI implementations that scale to all nodes but not all cores, and HPC people will be forced to build hybrid applications. This isn't for the faint of heart, and there's a lot of work to be done before there's an accepted paradigm in this space. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6879/"
]
} |
147,801 | What is the best way to parse a float in CSharp?I know about TryParse, but what I'm particularly wondering about is dots, commas etc. I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round.How can I best capture this? | I agree with leppie's reply; to put that in terms of code: string s = "123,456.789";float f = float.Parse(s, CultureInfo.InvariantCulture); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
} |
147,816 | Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc. Here is an example: def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g@args_as_intsdef funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z>>> funny_function("3", 4.0, z="5")22 Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function: >>> help(funny_function)Help on function g in module __main__:g(*args, **kwargs) Fortunately, there is a workaround: def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g@args_as_intsdef funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z This time, the function name and documentation are correct: >>> help(funny_function)Help on function funny_function in module __main__:funny_function(*args, **kwargs) Computes x*y + 2*z But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless. What to do? I can think of two simple but flawed workarounds: 1 -- Include the correct signature in the docstring: def funny_function(x, y, z=3): """funny_function(x, y, z=3) -- computes x*y + 2*z""" return x*y + 2*z This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [ And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example. ] 2 -- Not use a decorator, or use a special-purpose decorator for every specific signature: def funny_functions_decorator(f): def g(x, y, z=3): return f(int(x), int(y), z=int(z)) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically. I'm looking for a solution that is fully general, and automatic. So the question is: is there a way to edit the decorated function signature after it has been created? Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec? Any other approaches? | Install decorator module: $ pip install decorator Adapt definition of args_as_ints() : import [email protected] args_as_ints(f, *args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs)@args_as_intsdef funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*zprint funny_function("3", 4.0, z="5")# 22help(funny_function)# Help on function funny_function in module __main__:# # funny_function(x, y, z=3)# Computes x*y + 2*z Python 3.4+ functools.wraps() from stdlib preserves signatures since Python 3.4: import functoolsdef args_as_ints(func): @functools.wraps(func) def wrapper(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return func(*args, **kwargs) return wrapper@args_as_intsdef funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*zprint(funny_function("3", 4.0, z="5"))# 22help(funny_function)# Help on function funny_function in module __main__:## funny_function(x, y, z=3)# Computes x*y + 2*z functools.wraps() is available at least since Python 2.5 but it does not preserve the signature there: help(funny_function)# Help on function funny_function in module __main__:## funny_function(*args, **kwargs)# Computes x*y + 2*z Notice: *args, **kwargs instead of x, y, z=3 . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/147816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163767/"
]
} |
147,821 | I'm creating an installation script for an application that I'm developing and need to create databases dynamically from within PHP. I've got it to create the database but now I need to load in several .sql files. I had planned to open the file and mysql_query it a line at a time - until I looked at the schema files and realised they aren't just one query per line. So, how do I load an sql file from within PHP (as phpMyAdmin does with its import command)? | I'm getting the feeling that everyone here who's answered this question doesn't know what it's like to be a web application developer who allows people to install the application on their own servers. Shared hosting, especially, doesn't allow you to use SQL like the "LOAD DATA" query mentioned previously. Most shared hosts also don't allow you to use shell_exec. Now, to answer the OP, your best bet is to just build out a PHP file that contains your queries in a variable and can just run them. If you're determined to parse .sql files, you should look into phpMyAdmin and get some ideas for getting data out of .sql files that way. Look around at other web applications that have installers and you'll see that, rather than use .sql files for their queries, they just package them up in PHP files and just run each string through mysql_query or whatever it is that they need to do. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
]
} |
147,824 | To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII.Anyone has a clue? | JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode. But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position: function isDoubleByte(str) { for (var i = 0, n = str.length; i < n; i++) { if (str.charCodeAt( i ) > 255) { return true; } } return false;} This might not be as fast as you would like. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23373/"
]
} |
147,891 | In Firefox I can get the stack trace of an exception by using exception.stack . Is there a way to get that in other browsers, too? Edit: I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger). | Place this line where you want to print the stack trace: console.log(new Error().stack); Note: tested by me on Chrome 24 and Firefox 18 May be worth taking a look at this tool as well. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4936/"
]
} |
147,902 | Are there any good configuration file reading libraries for C\C++ that can be used for applications written on the linux platform. I would like to have a simple configuration file for my application. At best i would like to steer clear of XML files that might potentially confuse users. | You could try glib's key-value-file-parser | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362/"
]
} |
147,908 | Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties. Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow. | There were a number of gotchas I discovered: Although it may appear like a double in XAML, the actual value for a *Definition's Height or Width is a 'GridLength' struct. All the properties of GridLength are readonly, you have to create a new one each time you change it. Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this. Thusly, I used the following code: private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto)public GridLength HorizontalInputRegionSize{ get { // If not yet set, get the starting value from the DataModel if (myHorizontalInputRegionSize.IsAuto) myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel); return myHorizontalInputRegionSize; } set { myHorizontalInputRegionSize = value; if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value) { // Set the value in the DataModel ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value; } OnPropertyChanged("HorizontalInputRegionSize"); }} And the XAML: <Grid.RowDefinitions> <RowDefinition Height="*" MinHeight="100" /> <RowDefinition Height="Auto" /> <RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" /></Grid.RowDefinitions> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/147908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
]
} |
147,920 | I miss it so much (used it a lot in C#). can you do it in C++? | Yes, you can. See here . #pragma region Region_Name//Your content.#pragma endregion Region_Name | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/147920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18426/"
]
} |
147,941 | I am trying to read an Http response stream twice via the following: HttpWebResponse response = (HttpWebResponse)request.GetResponse();stream = response.GetResponseStream();RssReader reader = new RssReader(stream);do{ element = reader.Read(); if (element is RssChannel) { feed.Channels.Add((RssChannel)element); }} while (element != null);StreamReader sr = new StreamReader(stream);feed._FeedRawData = sr.ReadToEnd(); However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually). Basically, I would like to parse the stream for XML and have access to the raw data (in string format). Any ideas? | Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like: Stream responseStream = CopyAndClose(resp.GetResponseStream());// Do something with the streamresponseStream.Position = 0;// Do something with the stream againprivate static Stream CopyAndClose(Stream inputStream){ const int readSize = 256; byte[] buffer = new byte[readSize]; MemoryStream ms = new MemoryStream(); int count = inputStream.Read(buffer, 0, readSize); while (count > 0) { ms.Write(buffer, 0, count); count = inputStream.Read(buffer, 0, readSize); } ms.Position = 0; inputStream.Close(); return ms;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/147941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10505/"
]
} |
147,969 | I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it? BTW, I know of the existence of the various Unit frameworks in Ruby - this is an exercise to learn the Ruby idioms, rather than to "get something done". | No it's not a best practice. The best analogy to assert() in Ruby is just raising raise "This is wrong" unless expr and you can implement your own exceptions if you want to provide for more specific exception handling | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/147969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
]
} |
148,004 | Is it possible to find out who called a stored procedure? For example, say I get an error in proc3 . From within that proc I want to know if it was called by proc1 or proc2 . | I would use an extra input parameter, to specify the source, if this is important for your logic. This will also make it easier to port your database to another platform, since you don't depend on some obscure platform dependent function. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16279/"
]
} |
148,005 | In SQL, how do update a table, setting a column to a different value for each row? I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use: update person set unique_number = (select nextval('number_sequence') ); but it seems that nextval is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead? | Don't use a subselect, rather use the nextval function directly, like this: update person set unique_number = nextval('number_sequence'); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
]
} |
148,042 | When using IF statements in Python, you have to do the following to make the "cascade" work correctly. if job == "mechanic" or job == "tech": print "awesome"elif job == "tool" or job == "rock": print "dolt" Is there a way to make Python accept multiple values when checking for "equals to"? For example, if job == "mechanic" or "tech": print "awesome"elif job == "tool" or "rock": print "dolt" | if job in ("mechanic", "tech"): print "awesome"elif job in ("tool", "rock"): print "dolt" The values in parentheses are a tuple. The in operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple. Note that when Python searches a tuple or list using the in operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a frozenset : AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])def func(): if job in AwesomeJobs: print "awesome" The use of frozenset over set is preferred if the list of awesome jobs does not need to be changed during the operation of your program. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
]
} |
148,057 | If you have Mathematica code in foo.m, Mathematica can be invoked with -noprompt and with -initfile foo.m (or -run "<<foo.m" )and the command line arguments are available in $CommandLine (with extra junk in there) but is there a way to just have some mathematica code like #!/usr/bin/env MathKernelx = 2+2;Print[x];Print["There were ", Length[ARGV], " args passed in on the command line."];linesFromStdin = readList[];etc. and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)? | MASH -- Mathematica Scripting Hack -- will do this. Since Mathematica version 6, the following perl script suffices: http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl For previous Mathematica versions, a C program is needed: http://ai.eecs.umich.edu/people/dreeves/mash/pre6 UPDATE: At long last, Mathematica 8 supports this natively with the "-script" command-line option: http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
]
} |
148,074 | Is the sorting algorithm used by .NET's Array.Sort() method a stable algorithm? | From MSDN : This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal. The sort uses introspective sort. (Quicksort in version 4.0 and earlier of the .NET framework). If you need a stable sort, you can use Enumerable.OrderBy . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
]
} |
148,084 | To deploy a new version of our website we do the following: Zip up the new code, and upload it to the server. On the live server, delete all the live code from the IIS website directory. Extract the new code zipfile into the now empty IIS directory This process is all scripted, and happens quite quickly, but there can still be a 10-20 second downtime when the old files are being deleted, and the new files being deployed. Any suggestions on a 0 second downtime method? | You need 2 servers and a load balancer. Here's in steps: Turn all traffic on Server 2 Deploy on Server 1 Test Server 1 Turn all traffic on Server 1 Deploy on Server 2 Test Server 2 Turn traffic on both servers Thing is, even in this case you will still have application restarts and loss of sessions if you are using "sticky sessions". If you have database sessions or a state server, then everything should be fine. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23393/"
]
} |
148,129 | I'm trying to find out whether I should be using business critical logic in a trigger or constraint inside of my database. So far I've added logic in triggers as it gives me the control over what happens next and means I can provide custom user messages instead of an error that will probably confuse the users. Is there any noticable performance gain in using constraints over triggers and what are the best practices for determining which to use. | Constraints hands down! With constraints you specify relational principles, i.e. facts about your data. You will never need to change your constraints, unless some fact changes (i.e. new requirements). With triggers you specify how to handle data (in inserts, updates etc.). This is a "non-relational" way of doing things. To explain myself better with an analogy: the proper way to write a SQL query is to specify "what you want" instead of "how to get it" – let the RDBMS figure out the best way to do it for you. The same applies here: if you use triggers you have to keep in mind various things like the order of execution, cascading, etc... Let SQL do that for you with constraints if possible. That's not to say that triggers don't have uses. They do: sometimes you can't use a constraint to specify some fact about your data. It is extremely rare though. If it happens to you a lot , then there's probably some issue with the schema. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
]
} |
148,130 | Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this? Answer - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus. | For a general InputStream, I would wrap it in a BufferedInputStream and do something like this: BufferedInputStream bis = new BufferedInputStream(inputStream);bis.mark(2);int byte1 = bis.read();int byte2 = bis.read();bis.reset();// note: you must continue using the BufferedInputStream instead of the inputStream | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
]
} |
148,143 | When you open a solution in Visual Studio 2008 (or ealier versions for that matter), it opens all the documents that you did not close before you closed Visual Studio. Is there anyway to turn this functionality off, or a plugin that fixes this behavior? It takes forever to load a solution with 50 files open? | You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting. In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents: Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing DTE.ExecuteCommand("Window.CloseAllDocuments") End Sub Visual Studio 2008 appears to support the same events so I'm sure this would work there too. I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11559/"
]
} |
148,157 | I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case.Both activities have the same correlation token (modification) and the same owner (the owning state).Has anybody an idea why the link is not removed and how to remove the modification link? Thank you in advance, Stefan! | You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting. In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents: Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing DTE.ExecuteCommand("Window.CloseAllDocuments") End Sub Visual Studio 2008 appears to support the same events so I'm sure this would work there too. I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21729/"
]
} |
148,185 | C++ preprocessor #define is totally different. Is the PHP define() any different than just creating a var? define("SETTING", 0); $something = SETTING; vs $setting = 0; $something = $setting; | 'define' operation itself is rather slow - confirmed by xdebug profiler. Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html : pure 'define' 380.785 fetches/sec 14.2647 mean msecs/first-response constants defined with 'hidef' extension 930.783 fetches/sec 6.30279 mean msecs/first-response broken link update The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine . Here is another similar article . The libraries the author references can be found here (apc_define_constants) and here (hidef extension) . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21240/"
]
} |
148,190 | I have a legacy VB6 application that was built using MSDE. As many client's database grow towards the MSDE 2 GB limit they are upgraded to SQL 2005 Express. This has proven very successful until today. I have spent the entire day troubleshooting a client's network on which our application runs unacceptably slowly, when connecting the a SQL 2005 Express named instance across the "network". I say "network" because it is only two XP SP2 machines - there is no dedicated server here. No AD. In trying to isolate this problem I have installed SQL 2005 Express on both machines and placed copies of our database on both machines. I have even completely reinstalled our application using the SQL2005 Express install routine we now have. It makes no difference whether I restore an old MSDE database or use a newly created SQL 2005 Express one. When running our application and connecting to either machine's local server performance is fine. Once you connect our application on either PC to the server on the other PC, it is unworkably slow. (Regardless of the combination). Now, I have rebuilt statistics (exec sp_updatestats), rebuilt ALL indexes, disabled (temporarily) firewalls and virus software and clutched and countless other straws. I have resorted to running FileMon and ProcessMon on both machines and have even written a little test application to simply connect and query a table in the database. It too runs slowly - (takes about 5 - 6 seconds to connect). The monitors (File and Process) show delays when SQL Server is writing to a log file (c:\program files\microsoft sql server\mssql.1\log files\log_12.trc). Other tools though, like SQL Management Studio Express and even SSEUtil (a SQL Server Express Diagnostic Utility I found) run perfectly when connecting from the client to the server. Queries (even large ones) run as you would expect. I feel sure this problem is environmental as we have so many sites running what would appear to be the same setup, with no such problems. Can someone tell me what I should be doing to isolate this problem or even offer any clues or suggestions that could help solve this? | 'define' operation itself is rather slow - confirmed by xdebug profiler. Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html : pure 'define' 380.785 fetches/sec 14.2647 mean msecs/first-response constants defined with 'hidef' extension 930.783 fetches/sec 6.30279 mean msecs/first-response broken link update The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine . Here is another similar article . The libraries the author references can be found here (apc_define_constants) and here (hidef extension) . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
]
} |
148,225 | Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it. Particular order doesn't matter much here. I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask. | #include <stdint.h>#include <stdio.h>union ui64 { uint64_t one; uint16_t four[4];};intmain(){ union ui64 number = {0x123456789abcdef0}; printf("%x %x %x %x\n", number.four[0], number.four[1], number.four[2], number.four[3]); return 0;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
]
} |
148,298 | Okay, we know that the following two lines are equivalent - (0 == i) (i == 0) Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='. My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method? In particular, this question popped into my mind when I saw the following code - if(DialogResult.OK == MessageBox.Show("Message")) ... In my opinion, I would never recommend the above. Any second opinions? | I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6621/"
]
} |
148,361 | I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events. Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus? Here's a simplified sample to illustrate the problem: <html><head></head><body><div id="outer" style="background-color:#eeeeee;padding:10px">outer <div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;"> want to be able to focus this element and pick up keypresses </div></div><script language="Javascript">function onClick(){ document.getElementById('inner').innerHTML="clicked"; document.getElementById('inner').focus();}//this handler is never calledfunction onKeypressDiv(){ document.getElementById('inner').innerHTML="keypress on div";}function onKeypressDoc(){ document.getElementById('inner').innerHTML="keypress on doc";}//install event handlersdocument.getElementById('inner').addEventListener("click", onClick, false);document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false);document.addEventListener("keypress", onKeypressDoc, false);</script></body></html> On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener. Do I simply need to implement an application-specific notion of keyboard focus? I should add I only need this to work in Firefox. | Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example <div id="inner" tabindex="0"> this div can now have focus and receive keyboard events</div> Information gleaned from http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/148361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6521/"
]
} |
148,373 | I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function. How do I retrict the template function to only use numbers? (int, double etc.) #include <vector>#include <iostream>using namespace std; template <typename T>T sum(vector<T>& a){ T result = 0; int size = a.size(); for(int i = 0; i < size; i++) { result += a[i]; } return result;}int main(){ vector<int> int_values; int_values.push_back(2); int_values.push_back(3); cout << "Integer: " << sum(int_values) << endl; vector<double> double_values; double_values.push_back(1.5); double_values.push_back(2.1); cout << "Double: " << sum(double_values); return 0;} | The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have. So, you construct with an int, use + and +=, call a copy constructor, etc. Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it? If you want to restrict it more, use more functions that only are defined for the type you want. Another way to implement this is by creating a traits template -- something like this template<class T>SumTraits{public: const static bool canUseSum = false;} And then specialize it for the classes you want to be ok: template<>class SumTraits<int>{ public: const static bool canUseSum = true;}; Then in your code, you can write if (!SumTraits<T>::canUseSum) { // throw something here} edit: as mentioned in the comments, you can use BOOST_STATIC_ASSERT to make it a compile-time check instead of a run-time one | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22040/"
]
} |
148,398 | In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level) | Same question was asked on MSDN Forums: Varchar(max) vs Varchar(255) From the original post (much more information there): When you store data to a VARCHAR(N) column, the values are physically stored in the same way. But when you store it to a VARCHAR(MAX) column, behind the screen the data is handled as a TEXT value. So there is some additional processing needed when dealing with a VARCHAR(MAX) value. (only if the size exceeds 8000) VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored... | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/148398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21379/"
]
} |
148,403 | Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library. | I've asked this question 5 years ago. This thread was very helpful for me back then, I came to a conclusion, then I moved on with my project. It is funny that I needed something similar recently, totally unrelated to that project from the past. As I was researching for possible solutions, I stumbled upon my own question :) The solution I chose now is based on C++11. The boost libraries that Constantin mentions in his answer are now part of the standard. If we replace std::wstring with the new string type std::u16string, then the conversions will look like this: UTF-8 to UTF-16 std::string source;...std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;std::u16string dest = convert.from_bytes(source); UTF-16 to UTF-8 std::u16string source;...std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;std::string dest = convert.to_bytes(source); As seen from the other answers, there are multiple approaches to the problem. That's why I refrain from picking an accepted answer. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22764/"
]
} |
148,407 | Why does the code below return true only for a = 1? main(){int a = 10;if (true == a) cout<<"Why am I not getting executed";} | When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to: main(){ int a = 10; if (1 == a) cout<<"y i am not getting executed"; } This is part of the C++ standard , so it's something you would expect to happen with every C++ standards compliant compiler. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
]
} |
148,441 | If I have a script tag like this: <script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"></script> I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case. | Do you want to get the contents of the file http://www.example.com/script.js ? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23423/"
]
} |
148,451 | I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. How do I get sed to replace just the first occurrence of a string in a file rather than replacing every occurrence? If I use sed s/#include/#include "newfile.h"\n#include/ it replaces all #includes. Alternative suggestions to achieve the same thing are also welcome. | A sed script that will only replace the first occurrence of "Apple" by "Banana" Example Input: Output: Apple Banana Apple Apple Orange Orange Apple Apple This is the simple script: Editor's note: works with GNU sed only. sed '0,/Apple/{s/Apple/Banana/}' input_filename The first two parameters 0 and /Apple/ are the range specifier. The s/Apple/Banana/ is what is executed within that range. So in this case "within the range of the beginning ( 0 ) up to the first instance of Apple , replace Apple with Banana . Only the first Apple will be replaced. Background: In traditional sed the range specifier is also "begin here" and "end here" (inclusive). However the lowest "begin" is the first line (line 1), and if the "end here" is a regex, then it is only attempted to match against on the next line after "begin", so the earliest possible end is line 2. So since range is inclusive, smallest possible range is "2 lines" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU sed adds its own extension of allowing specifying start as the "pseudo" line 0 so that the end of the range can be line 1 , allowing it a range of "only the first line" if the regex matches the first line. Or a simplified version (an empty RE like // means to re-use the one specified before it, so this is equivalent): sed '0,/Apple/{s//Banana/}' input_filename And the curly braces are optional for the s command, so this is also equivalent: sed '0,/Apple/s//Banana/' input_filename All of these work on GNU sed only. You can also install GNU sed on OS X using homebrew brew install gnu-sed . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/148451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5022/"
]
} |
148,478 | I'm in the process of writing a Java 2D game. I'm using the built-in Java 2D drawing libraries, drawing on a Graphics2D I acquire from a BufferStrategy from a Canvas in a JFrame (which is sometimes full-screened). The BufferStrategy is double-buffered. Repainting is done actively, via a timer. I'm having some performance issues though, especially on Linux. And Java2D has so very many ways of creating graphics buffers and drawing graphics that I just don't know if I'm doing the right thing. I've been experimenting with graphics2d.getDeviceConfiguration().createCompatibleVolatileImage, which looks promising, but I have no real proof it it's going to be any faster if I switch the drawing code to that. In your experience, what is the fastest way to render 2D graphics onto the screen in Java 1.5+? Note that the game is quite far ahead, so I don't want to switch to a completely different method of drawing, like OpenGL or a game engine. I basically want to know how to get the fastest way of using a Graphics2D object to draw stuff to the screen. | I'm having the same issues as you are I think. Check out my post here: Java2D Performance Issues It shows the reason for the performance degradation and how to fix it. It's not guaranteed to work well on all platforms though. You'll see why in the post. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
]
} |
148,511 | Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such: LimitedValue< float, 0, 360 > someAngle( 45.0 );someTrigFunction( someAngle ); so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid). Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do: LimitedValue< float, 0, 90 > smallAngle( 45.0 );LimitedValue< float, 0, 360 > anyAngle( smallAngle ); and have that operation checked at compile-time, so this next example gives an error: LimitedValue< float, -90, 0 > negativeAngle( -45.0 );LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR! Is this possible? Is there some practical way of doing this, or any examples out there which approach this? | You can do this using templates -- try something like this: template< typename T, int min, int max >class LimitedValue { template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other ) { static_assert( min <= min2, "Parameter minimum must be >= this minimum" ); static_assert( max >= max2, "Parameter maximum must be <= this maximum" ); // logic }// rest of code}; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23434/"
]
} |
148,518 | It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me. What is the most efficient way to stop after the first replacement? | From MSDN : Replace(String, String, Int32) Within a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string. Isn't this what you want? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
]
} |
148,540 | I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge. I want some help working out how to create an iterator for a class I have created. I have a class 'Shape' which has a container of Points. I have a class 'Piece' which references a Shape and defines a position for the Shape.Piece does not have a Shape it just references a Shape. I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added. I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers. | /EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I'm letting the code below stand because it can be useful in similar circumstances. Is an own iterator actually necessary here? Perhaps it's sufficient to forward all required definitions to the container holding the actual Points: // Your class `Piece`class Piece {private: Shape m_shape;public: typedef std::vector<Point>::iterator iterator; typedef std::vector<Point>::const_iterator const_iterator; iterator begin() { return m_shape.container.begin(); } const_iterator begin() const { return m_shape.container.begin(); } iterator end() { return m_shape.container.end(); } const_iterator end() const { return m_shape.const_container.end(); }} This is assuming you're using a vector internally but the type can easily be adapted. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23435/"
]
} |
148,570 | I have seen a few (old) posts on the 'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has their own way of doing it. What is the best way of doing it currently? | There is a third party CMake module named 'Cotire' which automates the use of precompiled headers for CMake based build systems and also supports unity builds. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23439/"
]
} |
148,601 | Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template? I would like to be able to write something like this: #if ($a lt Long.MAX_VALUE) but this is apparently not the right syntax. | There are a number of ways. 1) You can put the values directly in the context. 2) You can use the FieldMethodizer to make all public static fields in a class available. 3) You can use a custom Uberspect implementation that includes public static fields in the lookup order. 4) You can use the FieldTool from VelocityTools. I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4728/"
]
} |
148,648 | i work with sql server, but i must migrate to an application with Oracle DB.for trace my application queries, in Sql Server i use wonderful Profiler tool. is there something of equivalent for Oracle? | You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks. See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955 Go to Instance -> sessions and watch the SQL Tab of each session. There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19261/"
]
} |
148,669 | This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated. //The constructorpublic Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value";} The value that is output is the second value "Modified" . What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later? [Edit]: Given some of the comments, changing the original sentence some... | currentValue is no longer a local variable: it is a captured variable. This compiles to something like: class Foo { public string currentValue; // yes, it is a field public void SomeMethod(object sender, EventArgs e) { Response.Write(currentValue); }}...public Page_Index() { Foo foo = new Foo(); foo.currentValue = "This is the FIRST value"; this.Load += foo.SomeMethod; foo.currentValue = "This is the MODIFIED value";} Jon Skeet has a really good write up of this in C# in Depth , and a separate (not as detailed) discussion here . Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers. This is different to java: in java the value of a variable is captured. In C#, the variable itself is captured. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17091/"
]
} |
148,670 | I don't see what all this fuss is about Microsoft's decision to support JQuery within ASP.NET MVC. There were signs that open-minded people are starting to have some say in the matters of marketing for a while now. And even the way MS does business has started to change. But at it's core it's still acting in response to customers' requests. I for one don't know what to make of it, except that it brings back to Microsoft's sphere of influence a very visible product. | Its the first time MS is shipping an open source component they didn't write with one of their products. This doesn't seem like a big deal, but its almost nuclear in its implications. Think about it... They are saying "we support this." In an OSS product, MS has no control over the code. So, they are putting their livelihood (in some small way) into the hands of people who don't work for MS. I think jQuery's popularity, the fact that it's not mission critical code, and that the codebase is so small all came together to make for favorable circumstances for MS to dip their toe in the water. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4204/"
]
} |
148,676 | I'm writing a Windows Forms application which is supposed to play three sound files and at the end of each sound file, it's to change the source of an image. I can get it to play the sounds using System.Media.SoundPlayer . However, it seems to play the sound in a different thread, continuing on. The net effect of this is that only the last sound is played and all the images are changed. I've tried Thread.Sleep , but it sleeps the whole GUI and after the sleep period everything happens at once and the last sound it played. UPDATE I thought PlaySynch was working, but it seems to freeze my GUI which is less than ideal. What else can I do? | Did you try SoundPlayer.PlaySync Method ? From the help: The PlaySync method uses the current thread to play a .wav file, preventing the thread from handling other messages until the load is complete. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
]
} |
148,678 | .NET developers out there! Need your opinion here! I am now using Visual Assist X , a decent piece of software, indeed. But the .NET bloggers seem to prefer Resharper more. I might want to consider a switch over, but before that I want your guys opinion first. | Resharper is much better for C# code (and supposedly VB.Net, but I haven't tried that).Unfortunately there is no support for C/C++, so if you need that, you might want to keep Visual Assist around. They don't coexist very well, unfortunately, so you may need to unload one, then load the other, when switching between C/C++ and C#. To see the magic of Resharper, I would recommend watching the "Resharper Jedi" video . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
148,681 | I have a custom class loader so that a desktop application can dynamically start loading classes from an AppServer I need to talk to. We did this since the amount of jars that are required to do this are ridiculous (if we wanted to ship them). We also have version problems if we don't load the classes dynamically at run time from the AppServer library. Now, I just hit a problem where I need to talk to two different AppServers and found that depending on whose classes I load first I might break badly... Is there any way to force the unloading of the class without actually killing the JVM? Hope this makes sense | The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo. One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server. This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it. If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file. And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own. If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class. I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/148681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13469/"
]
} |
148,689 | Is there an iSeries command to export the data in a table to CSV format? I know about the Windows utilities, but since this needs to be run automatically I need to run this from a CL program. | You can use CPYTOIMPF and specify the TOSTMF option to place a CSV file on the IFS.Example: CPYTOIMPF FROMFILE(DBFILE) TOSTMF('/outputfile.csv') STMFCODPAG(*PCASCII) RCDDLM(*CRLF) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23447/"
]
} |
148,729 | I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel. However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus. On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still exist , just not display in the way it does now. Any suggestions? :-) | Is this the effect you are looking for? public class NoFocusCueButton : Button{ protected override bool ShowFocusCues { get { return false; } }} You can use this custom button class just like a regular button, but it won't give you an extra rectangle on focus. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
148,742 | In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy? | The method GetDrives() returns a DriveInfo class which has a property DriveType that corresponds to the enumeration of System.IO.DriveType: public enum DriveType{ Unknown, // The type of drive is unknown. NoRootDirectory, // The drive does not have a root directory. Removable, // The drive is a removable storage device, // such as a floppy disk drive or a USB flash drive. Fixed, // The drive is a fixed disk. Network, // The drive is a network drive. CDRom, // The drive is an optical disc device, such as a CD // or DVD-ROM. Ram // The drive is a RAM disk. } Here is a slightly adjusted example from MSDN that displays information for all drives: DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}, Type {1}", d.Name, d.DriveType); } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13341/"
]
} |
148,747 | What is the difference between a framework and a library ? I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a framework on the other hand as a collection of libraries centered on a particular methodology (i.e. MVC) and which covers all areas of application development. | Actually these terms can mean a lot of different things depending the context they are used. For example, on Mac OS X frameworks are just libraries, packed into a bundle. Within the bundle you will find an actual dynamic library (libWhatever.dylib). The difference between a bare library and the framework on Mac is that a framework can contain multiple different versions of the library. It can contain extra resources (images, localized strings, XML data files, UI objects, etc.) and unless the framework is released to public, it usually contains the necessary .h files you need to use the library. Thus you have everything within a single package you need to use the library in your application (a C/C++/Objective-C library without .h files is pretty useless, unless you write them yourself according to some library documentation), instead of a bunch of files to move around (a Mac bundle is just a directory on the Unix level, but the UI treats it like a single file, pretty much like you have JAR files in Java and when you click it, you usually don't see what's inside, unless you explicitly select to show the content). Wikipedia calls framework a "buzzword". It defines a software framework as A software framework is a re-usable design for a software system (or subsystem). A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API.. So I'd say a library is just that, "a library". It is a collection of objects/functions/methods (depending on your language) and your application "links" against it and thus can use the objects/functions/methods. It is basically a file containing re-usable code that can usually be shared among multiple applications (you don't have to write the same code over and over again). A framework can be everything you use in application development. It can be a library, a collection of many libraries, a collection of scripts, or any piece of software you need to create your application. Framework is just a very vague term. Here's an article about some guy regarding the topic " Library vs. Framework ". I personally think this article is highly arguable. It's not wrong what he's saying there, however, he's just picking out one of the multiple definitions of framework and compares that to the classic definition of library. E.g. he says you need a framework for sub-classing. Really? I can have an object defined in a library, I can link against it, and sub-class it in my code. I don't see how I need a "framework" for that. In some way he rather explains how the term framework is used nowadays. It's just a hyped word, as I said before. Some companies release just a normal library (in any sense of a classical library) and call it a "framework" because it sounds more fancy. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/148747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20023/"
]
} |
148,828 | There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException? | Here's an implementation of as, as suggested by @Omar Kooheji: public static <T> T as(Class<T> clazz, Object o){ if(clazz.isInstance(o)){ return clazz.cast(o); } return null;}as(A.class, new Object()) --> nullas(B.class, new B()) --> B | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23424/"
]
} |
148,838 | I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails. Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps? | EDIT: At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks. You could also look at proxying to Thin in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here! Configuring Apache + Mongrel on Windows is not significantly different from *nix. Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this: LoadModule proxy_module modules/mod_proxy.soLoadModule proxy_http_module modules/mod_proxy_http.so<VirtualHost localhost:80> ServerName www.myapp.comm DocumentRoot "C:/web/myapp/public" ProxyPass / http://www.myapp.com:3000/ ProxyPassReverse / http://www.myapp.com:3000/ ProxyPreserveHost On</VirtualHost> Stick this in your httpd.conf (or httpd-vhost.conf if you're including it). It assumes you're going to run mongrel on port 3000, your Rails root is in C:\web\myapp , and you'll access the app at www.myapp.com. To run the rails app in production mode: mongrel_rails start -p 3000 -e production And away you go (actually mongrel defaults to port 3000 so you could skip -p 3000 if you want). The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the mongrel_service gem. Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109/"
]
} |
148,857 | I have a function, parseQuery, that parses a SQL query into an abstract representation of that query. I'm about to write a function that takes an abstract representation of a query and returns a SQL query string. What should I call the second function? | I think the verb you want is 'compose'. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/148857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
]
} |
148,875 | In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level. DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change. | The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say: EXCEPT({DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)},{DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)}) This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this: EXCEPT({the set i want}, {a set of members i dont want}) You shouldnt need to worry about the third (optional) argument: http://msdn.microsoft.com/en-us/library/ms144900.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
]
} |
148,879 | My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive? I tried checking for "Full trust" like so: try{ // Demand full trust permissions PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted ); fullTrust.Demand(); // Perform normal application logic}catch( SecurityException ){ // Report that permissions were not full trust MessageBox.Show( "This application requires full-trust security permissions to execute." );} However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas? | It indeed has to do with the fact the apps on a network location are less trusted then on your local hdd (due to the default policy of the .NET framework). If I'm not mistaken Microsoft finally corrected this annoyance in .NET 3.5 SP1 (after a lot of developers complaining). I google'd it: .NET Framework 3.5 SP1 Allows managed code to be launched from a network share! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23461/"
]
} |
148,901 | I've always handled optional parameters in JavaScript like this: function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff} Is there a better way to do it? Are there any cases where using || like that is going to fail? | Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } Or an alternative idiom: optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; Use whichever idiom communicates the intent best to you! | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/148901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
148,902 | I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later? Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later? | I think Philips method would be something like the following, assuming the last "good" revision was at 100 and you are now at 130, to create the new branch: svn copy -r100 svn://repos/trunk svn://repos/branches/newbranchsvn merge -r 100:130 svn://repos/trunk svn://repos/branches/newbranch Note the idea is to preserve the changes made in those revisions so you can apply them back to trunk. To revert trunk: svn merge -r130:100 .svn ci -m 'reverting to r100 (undoing changes in r100-130)' . (It wouldn't matter which order you performed these in, so you could revert trunk before creating the branch.) Then you could switch to the new branch you created in the repo: svn switch svn://repos/branches/newbranch workdir | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
]
} |
148,908 | I am thinking about using Microsoft Unity for my Dependency Injection tool in our User Interface. Our Middle Tier already uses Castle Windsor, but I am thinking I should stick with Microsoft. Does anyone have any thoughts about what the best Dependency Injection tool is? Autofac Castle MicroKernel/Windsor PicoContainer.NET Puzzle.NFactory Spring.NET StructureMap Ninject Unity Simple Injector NauckIT.MicroKernel WINTER4NET ObjectBuilder | Having recently spiked the use of 6 of these ( Windsor , Unity , Spring.Net , Autofac , Ninject , StructureMap ) I can offer a quick summary of each, our selection criteria and our final choice. Note: we did not look at PicoContainer.Net as one of our team considered the .Net port to be quite poor from the Java version. We also did not look at ObjectBuilder, as Unity is built on top of ObjectBuilder2 and was considered to be a superior choice by default. Firstly, I can say that more or less all of them are all pretty similar and it really comes down to what really works best for you, and your specific requirements. Our requirements included: Requirements Constructor based injection (we intend not to use property, field or method injection) Programmable configuration ( not XML) container hierarchies (one per application, per request and per session to more implicitly bind component lifetimes scope to container) component lifetime management (for more granular scoping eg transient / singleton) injection from interface to type or concrete instance (eg ILogger -> typeof(FileLogger) or ILogger -> new FileLogger() ) advanced component creation / "creaton event mechanism" for pre/post initialisation correct disposal of IDisposable components on container tear down well documented and/or online information readily available Note: whilst performance was a requirement it was not factored in the selection as it seemed that all containers reviewed were similar according to this benchmark Test Each container was used in a typical Asp.Net webforms project (as this was our target application type). We used a single simple page with with a single simple user control, each inheriting from a base page / base control respectively. We used 1 container on the BasePage for a "per request" scope container and 1 on the global.asax for an "application" scope and attempted to chain them together so dependencies could be resolved from both containers. Each web application shared a contrived set of domain objects simulating multi-levels of dependency, scope type (singleton/transient) and also of managed and unmanaged classes ( IDisposable required). The "top level" dependency components were manually injected from the methods on the BasePage . Results Windsor - Satisfied all the criteria and has a good case history, blogger community and online documentation. Easy to use and probably the defacto choice. Advanced component creation through Factory facility. Also allowed chaining of individually created containers. Spring.Net - Verbose and unhelpful documentation and no-obvious / easy for programmable configuration. Did not support generics. Not chosen Ninject - Easy to use with good clear documentation. Powerful feature set fulfilling all our requirements except container hierarchies so unfortunately was not chosen. StructureMap - Poorly documented, although had quite an advanced feature set that met all of our requirements, however there was no built-in mechanism for container hierarchies although could be hacked together using for loops see here The lambda expression fluent interface did seem a little over complicated at first, although could be encapsulated away. Unity - Well documented, easy to use and met all our selection criteria and has an easy extension mechanism to add the pre/post creation eventing mechanism we required. Child containers had to be created from a parent container. Autofac - Well documented and relatively easy to use, although lambda expression configuration does seem a little over complicated however, again, can be easily encapsulated away. Component scoping is achieved through a "tagging" mechanism and all components are configured up front using a builder which was a little inconvenient. Child containers were created from a parent and assigned components from a "tag". Allowed generic injection. Conclusion Our final choice was between Windsor and Unity, and this time around we chose Unity due to its ease of use, documentation, extension system and with it being in "production" status. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/148908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
]
} |
148,951 | I'm trying to use mysqldump to dump a schema, and it mostly works but I ran into one curiosity: the -p or --password option seems like it is doing something other than setting the password (as the man page and --help output say it should). Specifically, it looks like it's doing what is indicated here: http://snippets.dzone.com/posts/show/360 - that is, setting the database to dump. To support my somewhat outlandish claim, I can tell you that if I do not specify the --password (or -p ) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the --password option is dumped (or an error is given in the usual case that a password not matching any database name was specified). Here's a transcript: $ mysqldump -u test -h myhost --no-data --tables --password lose Enter password: -- MySQL dump 10.10 mysqldump: Got error: 1044: Access denied for user 'test'@'%' to database 'lose' when selecting the database So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using expect ??? I'm using mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486) . | From man mysqldump: --password[=password], -p[password] The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the password. If you omit the password value following the --password or -p option on the command line, you are prompted for one. Specifying a password on the command line should be considered insecure. See Section 6.6, "Keeping Your Password Secure". Syntactically, you are not using the --password switch correctly. As such, the command line parser is seeing your use of "lose" as a stand-alone argument which mysqldump interprets as the database name as it would if you were to attempt a simpler command like mysqldump lose To correct this, try using --password=lose or -plose or simply use -p or --password and type the password when prompted. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/148951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
]
} |
148,963 | Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. Here's a good discussion of how to do this in wxPython. To summarize, there are 3 ways: Use threads Use wxYield Chunk the work and do it in the IDLE event handler Which method have you found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome. | Threads. They're what I always go for because you can do it in every framework you need. And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/148963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.