source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
170,337
I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this: def Review(models.Model) ...fields... overall_score = models.FloatField(blank=True)def Score(models.Model) review = models.ForeignKey(Review) question = models.TextField() grade = models.IntegerField() A Review is has several "scores", the overall_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher?
Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models. One common task in overridden save methods is automated generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a pre_save signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness. Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it. With django-mptt , for example, I used the pre_save signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the pre_delete signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify save or delete methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/170337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24630/" ] }
170,346
Has someone ever measured performance of Sequential Guid vs. Standard Guid when used as Primary Keys inside a database? I do not see the need for unique keys to be guessable or not, passing them from a web UI or in some other part seems a bad practice by itself and I do not see, if you have security concerns, how using a guid can improve things (if this is the matter use a real random number generator using the proper crypto functions of the framework). The other items are covered by my approach, a sequential guid can be generated from code without need for DB access (also if only for Windows) and it's unique in time and space. And yes, question was posed with the intent of answering it, to give people that have choosen Guids for their PK a way to improve database usage (in my case has allowed the customers to sustain a much higher workload without having to change servers). It seems that security concerns are a lot, in this case do not use Sequential Guid or, better still, use standard Guid for PK that are passed back and forward from your UI and sequential guid for everything else. As always there is no absolute truth, I've edited also main answer to reflect this.
GUID vs.Sequential GUID A typical pattern it's to use Guid as PK for tables, but, as referred in other discussions (see Advantages and disadvantages of GUID / UUID database keys )there are some performance issues. This is a typical Guid sequence f3818d69-2552-40b7-a403-01a6db4552f7 7ce31615-fafb-42c4-b317-40d21a6a3c60 94732fc7-768e-4cf2-9107-f0953f6795a5 Problems of this kind of data are:< - Wide distributions of values Almost randomically ones Index usage is very, very, very bad A lot of leaf moving Almost every PK need to be at leaston a non clustered index Problem happens both on Oracle andSQL Server A possible solution is using Sequential Guid, that are generated as follows: cc6466f7-1066-11dd-acb6-005056c00008 cc6466f8-1066-11dd-acb6-005056c00008 cc6466f9-1066-11dd-acb6-005056c00008 How to generate them From C# code: [DllImport("rpcrt4.dll", SetLastError = true)]static extern int UuidCreateSequential(out Guid guid);public static Guid SequentialGuid(){ const int RPC_S_OK = 0; Guid g; if (UuidCreateSequential(out g) != RPC_S_OK) return Guid.NewGuid(); else return g;} Benefits Better usage of index Allow usage of clustered keys (to beverified in NLB scenarios) Less disk usage 20-25% of performance increase at aminimum cost Real life measurement: Scenario: Guid stored as UniqueIdentifiertypes on SQL Server Guid stored as CHAR(36) on Oracle Lot of insert operations, batchedtogether in a single transaction From 1 to 100s of inserts dependingon table Some tables > 10 millions rows Laboratory Test – SQL Server VS2008 test, 10 concurrent users, no think time, benchmark process with 600 inserts in batch for leaf table Standard Guid Avg. Process duration: 10.5 sec Avg. Request for second: 54.6 Avg. Resp. Time: 0.26 Sequential Guid Avg. Process duration: 4.6 sec Avg. Request for second: 87.1 Avg. Resp. Time: 0.12 Results on Oracle (sorry, different tool used for test) 1.327.613 insert on a table with a Guid PK Standard Guid , 0.02 sec. elapsed time for each insert, 2.861 sec. of CPU time, total of 31.049 sec. elapsed Sequential Guid , 0.00 sec. elapsed time for each insert, 1.142 sec. of CPU time, total of 3.667 sec. elapsed The DB file sequential read wait time passed from 6.4 millions wait events for 62.415 seconds to 1.2 million wait events for 11.063 seconds. It's important to see that all the sequential guid can be guessed, so it's not a good idea to use them if security is a concern, still using standard guid. To make it short... if you use Guid as PK use sequential guid every time they are not passed back and forward from a UI, they will speed up operation and do not cost anything to implement.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/170346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11673/" ] }
170,394
Where can I find a free, very quick, and reliable implementation of FFT in C#? That can be used in a product? Or are there any restrictions?
AForge.net is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/ ComplexImage.cs for usage, Sources/Math/ FourierTransform.cs for implemenation)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044/" ] }
170,415
Do you know what may cause memory leaks in JavaScript?I am interested in browsers: IE 7, FireFox 3, Safari 3
There is a nice article about JavaScript and memory leaks . It does not specific about on browser, it rather describes the whole problematic of memory leaks and JavaScript. JavaScript and memory leaks Introducing the closure More leakage patterns Conclusion I think it is a better approach to be as browser unspecific as possible insted of optimizing for a few browsers, when developing a website for the public.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24938/" ] }
170,426
On a question of just performance, how does Python 3 compare to Python 2.x?
3.0 is slower than 2.5 on official benchmarks. From "What’s New in Python 3.0" : The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There’s room for improvement, but it will happen after 3.0 is released!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1915/" ] }
170,467
I want to experiment with GCC whole program optimizations. To do so I have to pass all C-files at once to the compiler frontend. However, I use makefiles to automate my build process, and I'm not an expert when it comes to makefile magic. How should I modify the makefile if I want to compile (maybe even link) using just one call to GCC? For reference - my makefile looks like this: LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32CFLAGS = -WallOBJ = 64bitmath.o \ monotone.o \ node_sort.o \ planesweep.o \ triangulate.o \ prim_combine.o \ welding.o \ test.o \ main.o%.o : %.c gcc -c $(CFLAGS) $< -o $@test: $(OBJ) gcc -o $@ $^ $(CFLAGS) $(LIBS)
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32CFLAGS = -Wall# Should be equivalent to your list of C files, if you don't build selectivelySRC=$(wildcard *.c)test: $(SRC) gcc -o $@ $^ $(CFLAGS) $(LIBS)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/170467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ] }
170,578
On some Microsoft Access queries, I get the following message: Operation must use an updatable query. (Error 3073). I work around it by using temporary tables, but I'm wondering if there's a better way. All the tables involved have a primary key. Here's the code: UPDATE CLOG SET CLOG.NEXTDUE = ( SELECT H1.paidthru FROM CTRHIST as H1 WHERE H1.ACCT = clog.ACCT AND H1.SEQNO = ( SELECT MAX(SEQNO) FROM CTRHIST WHERE CTRHIST.ACCT = Clog.ACCT AND CTRHIST.AMTPAID > 0 AND CTRHIST.DATEPAID < CLOG.UPDATED_ON ))WHERE CLOG.NEXTDUE IS NULL;
Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join. I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround. BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4. --
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4873/" ] }
170,584
I have read on Stack Overflow some people that have converting to C#2.0 to C#3, but is it really worth it? I have a project that is done at 75% before going in maintenance phase. I am asking to myself if it is worth it to switch to C#3.0? Update: The project will have a web interface now so before entering the maintenance phase we have to develop the web part (all was done for internal purposes with Windows Forms). Most parts will be resused (back-end). Most people have said that it wasn't worth it in the past because it was already at 75%... but now do you still think it's not worth it? What have been done finally Finally since we are continuing the project with the web interface we will update to 3.5 for the new year. Thank you everybody for all your input.
No, I would advise not. I would advise starting 3.5 on new projects only, unless there is a specific reason otherwise. You will not have any benefit from 3.5 by just recompiling, since your code is already written (or at least 75% of it). If you need to migrate to 3.5 in the future, you can easily do it. Of course, you will have code in 2.0 style, but what is done is done. Be conservative, don't do something unless you need it. An application which is 75% in C#2.0 and 25% in C#3.0 is not exactly a nice beast to maintain. A 100% C#2.0 application is certainly more maintainable. When you are going to start a new project, then by all means switch! The new framework version is very interesting and the switch is hotly recommended.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ] }
170,600
I realize that since UNIX sockets are platform-specific, there has to be some non-Java code involved. Specifically, we're interested in using JDBC to connect to a MySQL instance which only has UNIX domain sockets enabled. It doesn't look like this is supported, but from what I've read it should be at least possible to write a SocketFactory for JDBC based on UNIX sockets if we can find a decent implementation of UNIX sockets for Java. Has anyone tried this? Does anyone know of such an implementation?
Checkout the JUDS library. It is a Java Unix Domain Socket library... https://github.com/mcfunley/juds
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ] }
170,601
I have a somewhat messily-formatted Objective-C code base. Is there a way to have Xcode reformat an entire project to conform to a coding standard (i.e., properly indent, spaces v. tabs, etc.)? Are there other tools that might accomplish this?
Uncrustify: http://uncrustify.sourceforge.net/ Source Code Beautifier for C, C++, C#, ObjectiveC, D, Java, Pawn and VALA If you want something simpler, you could probably get some way by simply stripping out all the white-space/line-breaks, and adding a new line-break on ; { } , and manually re-indenting the code. It won't be anywhere near perfectly laid out code, and reindenting could be a pain on large code, but it will be consistent.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1967/" ] }
170,617
This might sound like a little bit of a crazy question, but how can I find out (hopefully via an API/registry key) the install time and date of Windows? The best I can come up with so far is to look at various files in C:\Windows and try to guess... but that's not exactly a nice solution.
In regedit.exe go to: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.) To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this Unix Time Conversion online tool .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/170617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849/" ] }
170,624
Does anyone know how to resize images proportionally using JavaScript? I have tried to modify the DOM by adding attributes height and width on the fly, but seems did not work on IE6.
To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto. image.style.width = '50%'image.style.height = 'auto' This will ensure that its aspect ratio remains the same. Bear in mind that browsers tend to suck at resizing images nicely - you'll probably find that your resized image looks horrible.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/170624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19463/" ] }
170,649
That's the question. Give only one reason you think why have OODB failed or why many systems nowadays still use relational databases.
Can we answer more than once? Another reason is that relational DB's have a strong foundation in mathematics: from the definition of a relation, right through to the normal forms, the theory is rock solid. It is true that the relational model does not map well to OO, but IMHO the benefits and stability of that model outweigh the mapping problem.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876/" ] }
170,660
I have a web site using apache httpd as the server and mysql as the backend. It publishes a "thought for the day" that has gotten so popular that the server is crashing due to the number of requests. Since the same page is been requested (the thought only changes once a day), is it possible to put a caching server in front of my main server, so that when the same request is made by different clients, the caching server returns the page without having to go to the database?
For slow changing pages, a cache will definitely reduce CPU usage; but in your extreme case, where the page changes once a day, and it's perfectly predictable, it would be far easier to use a simple and fast static file server ( lighthttp , nginx , etc) and a cron job to change your "thought of the day" every night. In fact, a lot of non-interactive web pages can be done this way: periodically rebuild html files from database or any other source, and use simple, fast static web servers.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25139/" ] }
170,665
Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0. I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all. So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure. I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about. Then I'd do this for strings. And Dates. Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc.
There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception. Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type: public static T SafeConvert<T>(string s, T defaultValue){ if ( string.IsNullOrEmpty(s) ) return defaultValue; return (T)Convert.ChangeType(s, typeof(T));} Use: SafeConvert(null, 0.0) == 0.0;SafeConvert("", 0.0) == 0.0;SafeConvert("0", 0.0) == 0.0; This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass 0 and you'd get an In32 back. Pass 0L , Int64 . And so on...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ] }
170,686
I am looking for a simple, clean, correct XML parser to use in my C++ project. Should I write my own?
How about RapidXML ? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments, computer games, or any other applications where available memory or CPU processing power comes at a premium. RapidXML is licensed under Boost Software License and its source code is freely available. Features Parsing speed (including DOM treebuilding) approaching speed ofstrlen function executed on thesame data. On a modern CPU (as of 2008) theparser throughput is about 1 billioncharacters per second. SeePerformance section in the OnlineManual. Small memory footprint of the codeand created DOM trees. A headers-only implementation,simplifying the integration process. Simple license that allows use foralmost any purpose, both commercialand non-commercial, without anyobligations. Supports UTF-8 and partially UTF-16,UTF-32 encodings. Portable source code with nodependencies other than a very smallsubset of C++ Standard Library. This subset is so small that it canbe easily emulated manually if useof standard library is undesired. Limitations The parser ignores DOCTYPEdeclarations. There is no support for XML namespaces. The parser does not check forcharacter validity. The interface of the parser does notconform to DOM specification. The parser does not check forattribute uniqueness. Source: wikipedia.org://Rapidxml Depending on you use, you may use an XML Data Binding? CodeSynthesis XSD is an XML Data Binding compiler for C++ developed by Code Synthesis and dual-licensed under the GNU GPL and a proprietary license. Given an XML instance specification (XML Schema), it generates C++ classes that represent the given vocabulary as well as parsing and serialization code. One of the unique features of CodeSynthesis XSD is its support for two different XML Schema to C++ mappings: in-memory C++/Tree and stream-oriented C++/Parser. The C++/Tree mapping is a traditional mapping with a tree-like, in-memory data structure. C++/Parser is a new, SAX-like mapping which represents the information stored in XML instance documents as a hierarchy of vocabulary-specific parsing events. In comparison to C++/Tree, the C++/Parser mapping allows one to handle large XML documents that would not fit in memory, perform stream-oriented processing, or use an existing in-memory representation. Source: wikipedia.org://CodeSynthesis XSD
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/170686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25142/" ] }
170,689
I've been trying to consider how Row Level Security could be implemented with the Entity Framework. The idea is to have a database agnostic means that would offer methods to restrict the rows coming from the ObjectContext. Some of my inital ideas have involved modifying the partial classes created by the EDMGEN tool and that has offered some limited support. Users are still able to get around this solution by using their own eSQL statements and a QueryObject. I've been looking for a comprehensive solution that would exist above the database providers so that it would remain agnostic.
Sure you can do it. The important thing to do is to block direct access to the object context (preventing users from building their own ObjectQuery), and instead give the client a narrower gateway within which to access and mutate entities. We do it with the Entity Repository pattern . You can find an example implementation of this pattern for the entity framework in this blog post . Again, the key is blocking access to the object context. Note that the object context class is partial. So you should be able to prevent "unauthorized" means of instantiating it, namely, outside of your repository assembly. However, there are subtleties to consider. If you implement row-level view security on a certain entity type via the repository pattern, then you must consider other means by which a client could access the same entities. For example, via navigational relationships. You may need to make some of those relationships private, which you can do in your model. You also have the option of specifying a custom query or stored procedure for loading/saving entities. Stored procedures tend to be DB server specific, but SQL can be written in a generic manner. While I don't agree that this cannot be done with the Entity Framework, I do agree with the "do it on the DB server" comments insofar as you should implement defense in depth .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15439/" ] }
170,772
It seems that C# 3 hit me without me even noticing, could you guys tell me about good in depth guides to C# 3? from lambda to linq to everything else that was introduced with the third version of the language. Printed books would be nice, but online guides would be even better!
ScottGu has some great posts on C# 3: The C# ?? null coalescing operator (and using it with LINQ) LINQ to SQL: Part 8 (this is an 8 part series, check the top of the post for links to the first 7) Automatic Properties, Object Initializers, and Collection Initializers Extension Methods Lambda Expressions Query Syntax Anonymous Types Some more useful links: MSDN: Overview of C# 3.0 David Hayden: C# 3.0 Tutorials and Examples
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23020/" ] }
170,791
I'm creating a .net custom control and it should be able to load multiple text files. I have a public property named ListFiles with those properties set : [Browsable(true), Category("Configuration"), Description("List of Files to Load")]public string ListFiles { get { return m_oList; } set { m_oList = value; } } Depending upon the type of object, (string, string[], List, ...), the property grid will allow the user to enter some data.. My goal would be to have a filtered openfiledialog in the Properties Grid of my component that would enable the user to choose multiple files and return it as an array or string (or something else...). Sooo... Here's my question : How can I get an OpenFileDialog in a custom control's property grid? Thanks a lot!
You can do this by adding a UITypeEditor . Here is an example of a UITypeEditor that gives you the OpenFileDialog for chossing a filename.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25152/" ] }
170,800
I'm trying to embed a window from my process into the window of an external process using the SetParent function and have encountered a few problems that I'm hoping someone can help me out with. First off, here is an outline of what I am currently doing to embed my window into the application: HWND myWindow; //Handle to my application windowHWND externalWindow; //Handle to external application windowSetParent(myWindow,externalWindow);//Remove WS_POPUP style and add WS_CHILD styleDWORD style = GetWindowLong(myWindow,GWL_STYLE);style = style & ~(WS_POPUP);style = style | WS_CHILD;SetWindowLong(myWindow,GWL_STYLE,style); This code works and my window appears in the other application, but introduces the following issues: When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color) Keyboard shortcut commands of the main application do not work while my window has focus Does anybody know a workaround for this? I would like my window to be treated as just another child window of the main application.
Well, I finally found the answer to my question. To fix the issue with the main app losing focus you need to use the AttachThreadInput function to attach the embedded window thread to the main app thread. Also, one can use the TranslateAccelerator function in response to WM_KEYDOWN messages to ensure accelerator messages of the main app are triggered.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25149/" ] }
170,866
I sometimes need to use Visual Studio when I have limited screen real estate (remote desktopping from a laptop for example). It would be really useful to be able to make the currently selected code tab maximise to take the whole screen for a limited time. Is that possible? Is there a keyboard shortcut?
View->Full Screen (Shift + Alt + Enter) Does that work?
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ] }
170,907
I have seen a few mentions of this idiom (including on SO ): // Deliberately empty subscriberpublic event EventHandler AskQuestion = delegate {}; The upside is clear - it avoids the need to check for null before raising the event. However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?
The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/170907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ] }
170,931
I have a list of things (I'll call it L), an index(N) and a new thing(NEW). If I want to replace the thing in L at N with NEW, what is the best way to do this? Should I get the sublist up to N and from N to the end of the list and then glue together a new list from the first part, NEW, and the last part using list? Or is there a better way to do this?
(setf (nth N L) NEW) should do the trick.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/170931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ] }
170,956
I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?
Use the RUBY_PLATFORM constant, and optionally wrap it in a module to make it more friendly: module OS def OS.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil end def OS.mac? (/darwin/ =~ RUBY_PLATFORM) != nil end def OS.unix? !OS.windows? end def OS.linux? OS.unix? and not OS.mac? end def OS.jruby? RUBY_ENGINE == 'jruby' endend It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/170956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
170,961
I tried committing files with CRLF-ending lines, but it failed. I spent a whole work day on my Windows computer trying different strategies and was almost drawn to stop trying to use Git and instead try Mercurial . How to properly handle CRLF line endings?
Almost four years after asking this question, I have finallyfound an answer that completely satisfies me ! See the details in github:help 's guide to Dealing with line endings . Git allows you to set the line ending properties for a repo directly using the text attribute in the .gitattributes file. This file is committed into the repo and overrides the core.autocrlf setting, allowing you to ensure consistent behaviour for all users regardless of their git settings. And thus The advantage of this is that your end of line configuration now travels with your repository and you don't need to worry about whether or not collaborators have the proper global settings. Here's an example of a .gitattributes file # Auto detect text files and perform LF normalization* text=auto*.cs text diff=csharp*.java text diff=java*.html text diff=html*.css text*.js text*.sql text*.csproj text merge=union*.sln text merge=union eol=crlf*.docx diff=astextplain*.DOCX diff=astextplain# absolute paths are ok, as are globs/**/postinst* text eol=lf# paths that don't start with / are treated relative to the .gitattributes folderrelative/path/*.txt text eol=lf There is a convenient collection of ready to use .gitattributes files for the most popular programming languages. It's useful to get you started. Once you've created or adjusted your .gitattributes , you should perform a once-and-for-all line endings re-normalization . Note that the GitHub Desktop app can suggest and create a .gitattributes file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended .gitattributes and if you agree, the app will also perform a normalization of all the files in your repository. Finally, the Mind the End of Your Line articleprovides more background and explains how Git has evolvedon the matters at hand. I consider this required reading . You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments: This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372 One trick might be to have them commit their changes in another client, say SourceTree . Our team back then preferred that tool to Eclipse's EGit for many use cases. Who said software is easy? :-/
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/170961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25167/" ] }
170,962
I notice sometimes with my parent/child objects or many-to-many relationships, I need to call either SaveOrUpdate or Merge . Usually, when I need to call SaveOrUpdate , the exception I get on calling Merge has to do with transient objects not being saved first. Please explain the difference between the two.
This is from section 10.7. Automatic state detection of the Hibernate Reference Documentation: saveOrUpdate() does the following: if the object is already persistent in this session, do nothing if another object associated with the session has the same identifier, throw an exception if the object has no identifier property, save() it if the object's identifier has the value assigned to a newly instantiated object, save() it if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it otherwise update() the object and merge() is very different: if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance the persistent instance is returned the given instance does not become associated with the session, it remains detached You should use Merge() if you are trying to update objects that were at one point detached from the session, especially if there might be persistent instances of those objects currently associated with the session. Otherwise, using SaveOrUpdate() in that case would result in an exception.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/170962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ] }
170,986
What is the best method for adding options to a <select> from a JavaScript object using jQuery? I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there. This is what I did: selectValues = { "1": "test 1", "2": "test 2" };for (key in selectValues) { if (typeof (selectValues[key] == 'string') { $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>'); }} A clean/simple solution: This is a cleaned up and simplified version of matdumsa's : $.each(selectValues, function(key, value) { $('#mySelect') .append($('<option>', { value : key }) .text(value));}); Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
The same as other answers, in a jQuery fashion: $.each(selectValues, function(key, value) { $('#mySelect') .append($("<option></option>") .attr("value", key) .text(value)); });
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/170986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ] }
170,997
What is the best method for removing a table row with jQuery?
You're right: $('#myTableRow').remove(); This works fine if your row has an id , such as: <tr id="myTableRow"><td>blah</td></tr> If you don't have an id , you can use any of jQuery's plethora of selectors .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/170997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ] }
171,000
I want to recreate the the update panel postback without using an update panel to do the postback. What is the generic method for doing this? For example, on Stackoverflow, when you vote up or down on a question it does a postback to update the database and I would bet they didn't use an update panel. What do I have? I have a table with table data. When I click on the td item as a whole column, I want to do an update to the database and also update a gridview on the page itself. The gridview shows all the currently clicked items in the table because it was updated via "our method". Looking for a good generic method I could use for a lot of async postbacks without update panel.
The way that Stack Overflow works differs in two important ways from that CodeProject article. Stack Overflow is making its AJAX request against an ASP.NET MVC controller action, not a standalone ASPX page. You might consider this as the MVC analogue of an ASP.NET AJAX page method. In both cases, the ASPX method will lag behind in terms of performance. Stack Overflow's AJAX request returns a JSON serialized result, not arbitrary plaintext or HTML. This makes handling it on the client side more standardized and generally cleaner. For example: when I voted this question up an XmlHttpRequest request was made to /questions/171000/vote, with a "voteTypeId" of 2 in the POST data. The controller that handled the request added my vote to a table somewhere and then responded with this JSON: {"Success":true,"NewScore":1,"Message":"","LastVoteTypeId":2} Using that information, this JavaScript takes care of updating the client-side display: var voteResult = function(jClicked, postId, data) { if (data.Success) { jClicked.parent().find("span.vote-count-post").text(data.NewScore); if (data.Message) showFadingNotification(jClicked, data.Message); } else { showNotification(jClicked, data.Message); reset(jClicked, jClicked); if (data.LastVoteTypeId) { selectPreviousVote(jClicked, data.LastVoteTypeId); } }}; If you're using WebForms, the example of calling page methods that you found on my blog is definitely in the right ballpark. However, I would suggest that you consider a web service for any centralized functionality (like this voting example), instead of page methods. Page methods seem to be slightly easier to write, but they also have some reuse drawbacks and tend to provide an illusion of added security that isn't really there. This is an example of doing the same thing you found, but with web services (the comments on this post actually led to the post you found): http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ] }
171,027
I'm using jQuery to add an additional row to a table as the last row. I have done it this way: $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>'); Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?
The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example: <table id="myTable"> <tbody> <tr>...</tr> <tr>...</tr> </tbody></table> You would end up with the following: <table id="myTable"> <tbody> <tr>...</tr> <tr>...</tr> </tbody> <tr>...</tr></table> I would therefore recommend this approach instead: $('#myTable tr:last').after('<tr>...</tr><tr>...</tr>'); You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above. Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself. DaRKoN_ suggests appending to the tbody rather than adding content after the last tr . This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them. Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup. I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements): $('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/171027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ] }
171,173
I'm trying to perform a bitwise NOT in SQL Server. I'd like to do something like this: update fooset Sync = NOT @IsNew Note: I started writing this and found out the answer to my own question before I finished. I still wanted to share with the community, since this piece of documentation was lacking on MSDN (until I added it to the Community Content there, too).
Yes, the ~ operator will work. update fooset Sync = ~@IsNew
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/171173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73794/" ] }
171,205
I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6). java -Xmx1400m ... Today I tried the same option on a new Windows XP machine using Java 1.5_16 and 1.6.0_07 and got the error: Error occurred during initialization of VMCould not reserve enough space for object heapCould not create the Java virtual machine. Through trial and error it seems 1200 megabytes is the most I can allocate on this machine. Any ideas why one machine would allow 1400 and another only 1200? Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.
Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous in its address space . So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space). You could try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate... Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have much more contiguous virtual address space, and allocating 2GB contiguously would be trivial.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/171205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ] }
171,213
I need to make sure that user can run only one instance of my program at a time. Which means, that I have to check programatically, whether the same program is already running, and quit in such case. The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it. The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work.In case of, say, power outage, the lock file remains in place and the program can't be started again. To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process. If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file. This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low. But it still doesn't feel right (there is a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either. So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and *nix alike. If it cannot be done platform-independently, Linux/Unix is a priority for me.
There are several methods you can use to accomplish only allowing one instance of your application: Method 1: Global synchronization object or memory It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running. For example in windows you could do: #define APPLICATION_INSTANCE_MUTEX_NAME "{BA49C45E-B29A-4359-A07C-51B65B5571AD}" //Make sure at most one instance of the tool is running HANDLE hMutexOneInstance(::CreateMutex( NULL, TRUE, APPLICATION_INSTANCE_MUTEX_NAME)); bool bAlreadyRunning((::GetLastError() == ERROR_ALREADY_EXISTS)); if (hMutexOneInstance == NULL || bAlreadyRunning) { if(hMutexOneInstance) { ::ReleaseMutex(hMutexOneInstance); ::CloseHandle(hMutexOneInstance); } throw std::exception("The application is already running"); } Method 2: Locking a file, second program can't open the file, so it's open You could also exclusively open a file by locking it on application open. If the file is already exclusively opened, and your application cannot receive a file handle, then that means the program is already running. On windows you'd simply not specify sharing flags FILE_SHARE_WRITE on the file you're opening with CreateFile API. On linux you'd use flock . Method 3: Search for process name: You could enumerate the active processes and search for one with your process name.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2239/" ] }
171,251
I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to: var obj1 = { food: 'pizza', car: 'ford' }var obj2 = { animal: 'dog' }obj1.merge(obj2);//obj1 now has three properties: food, car, and animal Is there a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.
ECMAScript 2018 Standard Method You would use object spread : let merged = {...obj1, ...obj2}; merged is now the union of obj1 and obj2 . Properties in obj2 will overwrite those in obj1 . /** There's no limit to the number of objects you can merge. * Later properties overwrite earlier properties with the same name. */const allRules = {...obj1, ...obj2, ...obj3}; Here is also the MDN documentation for this syntax. If you're using babel you'll need the babel-plugin-transform-object-rest-spread plugin for it to work. ECMAScript 2015 (ES6) Standard Method /* For the case in question, you would do: */Object.assign(obj1, obj2);/** There's no limit to the number of objects you can merge. * All objects get merged into the first object. * Only the object in the first argument is mutated and returned. * Later properties overwrite earlier properties with the same name. */const allRules = Object.assign({}, obj1, obj2, obj3, etc); (see MDN JavaScript Reference ) Method for ES5 and Earlier for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1 . If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty , but that code will work for 99% of cases. Example function: /** * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 * @param obj1 * @param obj2 * @returns obj3 a new object based on obj1 and obj2 */function merge_options(obj1,obj2){ var obj3 = {}; for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; } return obj3;}
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/171251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ] }
171,267
Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?
Eshell is a Bash-like shell in Emacs Lisp. IPython can be used as a system shell , though the syntax is a bit weird (supporting all of Python plus basic sh constructs). fish has a core written in C, but much of its functionality is implemented in itself. Unlike many rare shells, it can be used as your login shell. Hotwire deserves another mention. Its basic design appears to be "PowerShell in Python," but it also does some clever things with UI. The last release was in 2008. Zoidberg is written in Perl and uses Perl syntax. A nice-looking project, shame it seems to have stalled. Scsh would be a pain to use as a login shell (an example command from the docs: (run/strings (find "." -name *.c -print)) ), but it looks like a good "Perl in Scheme."
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14739/" ] }
171,279
How to I get the Fixnum returned by the following: "abc"[2] Back into a character?
This will do it (if n is an integer): n.chr
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ] }
171,301
int x = n / 3; // <-- make this faster// for instanceint a = n * 3; // <-- normal integer multiplicationint b = (n << 1) + n; // <-- potentially faster multiplication
This is the fastest as the compiler will optimize it if it can depending on the output processor. int a;int b;a = some value;b = a / 3;
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/171301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200558/" ] }
171,318
I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand. The code is sorta like the following in structure: <?php $lots of = "php";?><xml> <morexml><?php while(){?> <somegeneratedxml><?php } ?><lastofthexml><?php ?><html> <pre> The XML for the user to preview </pre> <form> <input id="xml" value="theXMLagain" /> </form></html> My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value). My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?
<?php ob_start(); ?><xml/><?php $xml = ob_get_clean(); ?><input value="<?php echo $xml ?>" />͏͏͏͏͏͏
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/171318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ] }
171,326
I have a bad habit of using the cursor keys of my keyboard to navigate source code. It's something I've done for 15 years and this of course means that my navigating speed is limited by the speed of the keyboard. On both Vista and OS X (I dual boot a MacBook), I have my key repeat rate turned all the way up. But in Visual Studio, and other apps, the rate is still much slower than I would prefer. How can I make the key repeat rate faster in Visual Studio and other text editors?
On Mac OS X, open the Global Preferences plist open ~/Library/Preferences/.GlobalPreferences.plist Then change the KeyRepeat field. Smaller numbers will speed up your cursor rate. The settings dialog will only set it to a minimum of 2, so if you go to 0 or 1, you'll get a faster cursor. I had to reboot for this to take effect.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ] }
171,332
I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is: FieldInfo[] _fields = typeof(ButtonedForm.TitleButton).GetFields( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);Console.WriteLine("{0} fields:", _fields.Length);foreach (FieldInfo fi in _fields){ Console.WriteLine(fi.Name);} This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?
It would be more appropriate to use the InternalsVisibleTo attribute to grant access to the internal members of the assembly to your unit test assembly. Here is a link with some helpful additional info and a walk through: The Wonders Of InternalsVisibleTo To actually answer your question... Internal and protected are not recognized in the .NET Reflection API. Here is a quotation from MSDN : The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ] }
171,399
For intense number-crunching i'm considering using fixed point instead of floating point. Of course it'll matter how many bytes the fixed point type is in size, on what CPU it'll be running on, if i can use (for Intel) the MMX or SSE or whatever new things come up... I'm wondering if these days when floating point runs faster than ever, is it ever worth considering fixed point? Are there general rules of thumb where we can say it'll matter by more than a few percent? What is the overview from 35,000 feet of numerical performance? (BTW, i'm assuming a general CPU as found in most computers, not DSP or specialized embedded systems.)
It's still worth it. Floating point is faster than in the past, but fixed-point is also. And fixed is still the only way to go if you care about precision beyond that guaranteed by IEEE 754.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10468/" ] }
171,400
I'd like to know if anyone has any first-hand experience with this dichotomy. A few blogs say the mysql extension is faster than mysqli. Is this true? And I'm only asking about speed. I know mysqli has features that are not present in the older extension.
The MySQL extension is very slightly faster than MySQLi in most benchmarks I've seen reported. The difference is so slight, however, that this should probably not be your criterion for deciding between the two. Other factors dwarf the difference in performance between mysql and mysqli. Using mod_php or FastCGI, a bytecode cache like APC, or using data caching judiciously to reduce database hits, are far more beneficial for overall performance of PHP scripts than the choice of MySQL extension. Don't be penny wise and pound foolish! :-)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3351/" ] }
171,412
I basically have an xml column, and I need to find and replace one tag value in each record.
For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution: You can use CAST to turn that xml column into a regular varchar, and then do your normal replace. UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]') That same technique also makes searching XML a snap when you need to just run a quick query to find something, and don't want to deal with xpaths. SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%' Edit: Just want to update this a bit, if you get a message along the lines of Conversion of one or more characters from XML to target collation impossible , then you only need to use nvarchar which supports unicode. CAST( xmlCol as nvarchar(max) )
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ] }
171,435
I know that the #warning directive is not standard C /C++, but several compilers support it, including gcc/g++. But for those that don't support it, will they silently ignore it or will it result in a compile failure? In other words, can I safely use it in my project without breaking the build for compilers that don't support it?
It is likely that if a compiler doesn't support #warning, then it will issue an error. Unlike #pragma, there is no recommendation that the preprocessor ignore directives it doesn't understand. Having said that, I've used compilers on various different (reasonably common) platforms and they have all supported #warning.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78437/" ] }
171,480
I have a value like this: "Foo Bar" "Another Value" something else What regex will return the values enclosed in the quotation marks (e.g. Foo Bar and Another Value )?
I've been using the following with great success: (["'])(?:(?=(\\?))\2.)*?\1 It supports nested quotes as well. For those who want a deeper explanation of how this works, here's an explanation from user ephemient : ([""']) match a quote; ((?=(\\?))\2.) if backslash exists, gobble it, and whether or not that happens, match a character; *? match many times (non-greedily, as to not eat the closing quote); \1 match the same quote that was use for opening.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/171480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4646/" ] }
171,506
I've been unsuccessfully searching for a way to install make utility on my CentOS 5.2. I've looked through some RPM repositories and online, with no avail. Installing gcc , gcc-c++ didn't help! Package build-essential is not made for CentOS/RHEL. I have RPMFORGE repo enabled in YUM.
yum groupinstall "Development Tools" or yum install gcc gcc-c++ kernel-devel
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406/" ] }
171,519
I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 ( adLDAP does it on Apache). Anyone had done anything similar, with success? Edit: I'd prefer a library/class with code that's ready to go... It'd be silly to invent the wheel when someone has already done so.
Importing a whole library seems inefficient when all you need is essentially two lines of code... $ldap = ldap_connect("ldap.example.com");if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) { // log them in!} else { // error message}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/171519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406/" ] }
171,550
See also: How can I see which Git branches are tracking which remote / upstream branch? How can I find out which remote branch a local branch is tracking? Do I need to parse git config output, or is there a command that would do this for me?
Here is a command that gives you all tracking branches (configured for 'pull'), see: $ git branch -vv main aaf02f0 [main/master: ahead 25] Some other commit* master add0a03 [jdsumsion/master] Some commit You have to wade through the SHA and any long-wrapping commit messages, but it's quick to type and I get the tracking branches aligned vertically in the 3rd column. If you need info on both 'pull' and 'push' configuration per branch, see the other answer on git remote show origin . Update Starting in git version 1.8.5 you can show the upstream branch with git status and git status -sb
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/171550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
171,565
Is there a tool/plugin/function for Firefox that'll dump out a memory usage of Javascript objects that you create in a page/script? I know about Firebug's profiler but I'd like something more than just times. Something akin to what Yourkit has for Java profiling of memory usage. Reason is that a co-worker is using id's for "keys" in an array and is creating 1000's of empty slots when he does this. He's of the opinion that this is harmless whereas my opinion differs. I'd like to offer some proof to prove whether I'm right or not.
I haven't tried the Sofware verify tools, but Mozilla has tools that track overall memory consumed by firefox for the purpose of stemming leaks: http://www.mozilla.org/performance/tools.html and: https://wiki.mozilla.org/Performance:Leak_Tools There's also this guy saying to avoid large arrays in the context of closures, towards article bottom http://ajax.sys-con.com/node/352585
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8590/" ] }
171,588
If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?
You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution. Create a file named resetvars.vbs containing this code, and save it on the path: Set oShell = WScript.CreateObject("WScript.Shell")filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")Set objFileSystem = CreateObject("Scripting.fileSystemObject")Set oFile = objFileSystem.CreateTextFile(filename, TRUE)set oEnv=oShell.Environment("System")for each sitem in oEnv oFile.WriteLine("SET " & sitem)nextpath = oEnv("PATH")set oEnv=oShell.Environment("User")for each sitem in oEnv oFile.WriteLine("SET " & sitem)nextpath = path & ";" & oEnv("PATH")oFile.WriteLine("SET PATH=" & path)oFile.Close create another file name resetvars.bat containing this code, same location: @echo off%~dp0resetvars.vbscall "%TEMP%\resetvars.bat" When you want to refresh the environment variables, just run resetvars.bat Apologetics : The two main problems I had coming up with this solution were a. I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and b. the PATH environment variable is a concatenation of the user and the system PATH variables. I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically. I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs. Note : this script does not delete variables. This can probably be improved. ADDED If you need to export the environment from one cmd window to another, use this script (let's call it exportvars.vbs ): Set oShell = WScript.CreateObject("WScript.Shell")filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")Set objFileSystem = CreateObject("Scripting.fileSystemObject")Set oFile = objFileSystem.CreateTextFile(filename, TRUE)set oEnv=oShell.Environment("Process")for each sitem in oEnv oFile.WriteLine("SET " & sitem)nextoFile.Close Run exportvars.vbs in the window you want to export from , then switch to the window you want to export to , and type: "%TEMP%\resetvars.bat"
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/171588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ] }
171,633
When using one's own iPhone for development it's easy enough to access any crash logs via XCode->Organizer->Crash Logs. How does one access crash logs on another person's phone if they don't have it set up for development in XCode, as would likely be the case if you were distributing your app to them via ad hoc distribution for beta testing?
Two ways: iTunes syncs all crash reports during a regular sync. They can be found in Library/Logs/CrashReporter/MobileDevice on a Mac and probably somewhere in %APPDATA% on Windows. You can use the iPhone Configuration Utility for Mac OS X on any Mac to access the phone's console and crash logs. Note: the iPhone Web Configuration Utility, which is available for Windows and Mac (note the "web" in the name) does not allow this kind of access and only provides a portion of the Configuration Utility's features . Er, no you can't. Xcode provides this facility in the Organizer (from the Window menu), but not iPCU.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ] }
171,641
When maintaining a COM interface should an empty BSTR be treated the same way as NULL ?In other words should these two function calls produce the same result? // Empty BSTR CComBSTR empty(L""); // Or SysAllocString(L"") someObj->Foo(empty); // NULL BSTR someObj->Foo(NULL);
Yes - a NULL BSTR is the same as an empty one. I remember we had all sorts of bugs that were uncovered when we switched from VS6 to 2003 - the CComBSTR class had a change to the default constructor that allocated it using NULL rather than an empty string. This happens when you for example treat a BSTR as a regular C style string and pass it to some function like strlen , or try to initialise a std::string with it. Eric Lippert discusses BSTR's in great detail in Eric's Complete Guide To BSTR Semantics : Let me list the differences first andthen discuss each point inexcruciating detail. A BSTR must have identicalsemantics for NULL and for "". A PWSZfrequently has different semantics forthose. A BSTR must be allocated and freedwith the SysAlloc* family offunctions. A PWSZ can be anautomatic-storage buffer from thestack or allocated with malloc, new,LocalAlloc or any other memoryallocator. A BSTR is of fixed length. A PWSZmay be of any length, limited only bythe amount of valid memory in itsbuffer. A BSTR always points to the firstvalid character in the buffer. A PWSZmay be a pointer to the middle or endof a string buffer. When allocating an n-byte BSTR youhave room for n/2 wide characters.When you allocate n bytes for a PWSZyou can store n / 2 - 1 characters --you have to leave room for the null. A BSTR may contain any Unicode dataincluding the zero character. A PWSZnever contains the zero characterexcept as an end-of-string marker.Both a BSTR and a PWSZ always have azero character after their last validcharacter, but in a BSTR a validcharacter may be a zero character. A BSTR may actually contain an oddnumber of bytes -- it may be used formoving binary data around. A PWSZ isalmost always an even number of bytesand used only for storing Unicodestrings.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ] }
171,765
Here's the very dumb way: def divisorGenerator(n): for i in xrange(1,n/2+1): if n%i == 0: yield i yield n The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-) I can find prime factors and their multiplicity fast enough. I've an generator that generates factor in this way: (factor1, multiplicity1) (factor2, multiplicity2) (factor3, multiplicity3) and so on... i.e. the output of for i in factorGenerator(100): print i is: (2, 2)(5, 2) I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make for i in divisorGen(100): print i output this: 124510202550100 UPDATE: Many thanks to Greg Hewgill and his "smart way" :)Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D UPDATE 2: Stop saying this is a duplicate of this post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.
Given your factorGenerator function, here is a divisorGen that should work: def divisorGen(n): factors = list(factorGenerator(n)) nfactors = len(factors) f = [0] * nfactors while True: yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1) i = 0 while True: f[i] += 1 if f[i] <= factors[i][1]: break f[i] = 0 i += 1 if i >= nfactors: return The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/171765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21384/" ] }
171,776
I've looked at this explanation on Wikipedia , specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example? What I can make from the answers so far, it seems to me to be just a more complex way of doing this: have an abstract class: MoveAlong with a virtual method: DoIt()have class Car inherit from MoveAlong, implementing DoIt() { ..start-car-and-drive..}have class HorseCart inherit from MoveAlong, implementing DoIt() { ..hit-horse..}have class Bicycle inherit from MoveAlong, implementing DoIt() { ..pedal..}now I can call any function taking MoveAlong as parm passing any of the three classes and call DoItIsn't this what Strategy intents? (just simpler?) [Edit-update]The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.) [Edit-update] Conclusion The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!).
The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface: class IClockDisplay{ public: virtual void Display( int hour, int minute, int second ) = 0;}; Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like: class Clock{ protected: IClockDisplay* mDisplay; int mHour; int mMinute; int mSecond; public: Clock( IClockDisplay* display ) { mDisplay = display; } void Start(); // initiate the timer void OnTimer() { mDisplay->Display( mHour, mMinute, mSecond ); } void ChangeDisplay( IClockDisplay* display ) { mDisplay = display; }}; Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface. So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ] }
171,778
Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle). Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order? Based on the answer to the question referenced by nickf the answer is: select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty
The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface: class IClockDisplay{ public: virtual void Display( int hour, int minute, int second ) = 0;}; Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like: class Clock{ protected: IClockDisplay* mDisplay; int mHour; int mMinute; int mSecond; public: Clock( IClockDisplay* display ) { mDisplay = display; } void Start(); // initiate the timer void OnTimer() { mDisplay->Display( mHour, mMinute, mSecond ); } void ChangeDisplay( IClockDisplay* display ) { mDisplay = display; }}; Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface. So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3509/" ] }
171,785
When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them. How do you keep everything manageable?
My advice: Read Installing Python Modules . Read Distributing Python Modules . Start using easy_install from setuptools . Read the documentation for setuptools. Always use virtualenv . My site-packages directory contains setuptools and virtualenv only . Check out Ian Bicking's new project pyinstall . Follow everything Ian Bicking is working on. It is always goodness. When creating your own packages, use distutils/setuptools. Consider using paster create (see http://pythonpaste.org ) to create your initial directory layout.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/171785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672/" ] }
171,824
I have a plug-in to an Eclipse RCP application that has a view. After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu. I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere.
You are probably looking for this: PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("viewId");
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/171824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/725/" ] }
171,849
I have a program that spits out an Excel workbook in Excel 2003 XML format. It works fine with one problem, I cannot get the column widths to set automatically. A snippet of what I produce: <Table > <Column ss:AutoFitWidth="1" ss:Width="2"/> <Row ss:AutoFitHeight="0" ss:Height="14.55"> <Cell ss:StyleID="s62"><Data ss:Type="String">Database</Data></Cell> This does not set the column to autofit. I have tried not setting width, I have tried many things and I am stuck. Thanks.
Only date and number values are autofitted :-(quote: "... We do not autofit textual values" http://msdn.microsoft.com/en-us/library/aa140066.aspx#odc_xmlss_ss:column
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ] }
171,862
When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace: namespace Lib {class A {};A operator+(const A&, const A&);} // namespace Lib or the global namespace namespace Lib {class A {};} // namespace LibLib::A operator+(const Lib::A&, const Lib::A&); From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?
You should define them in the library namespace.The compiler will find them anyway through argument dependant lookup. No need to pollute the global namespace.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78437/" ] }
171,876
I am studying how two-phase commit works across a distributed transaction. It is my understanding that in the last part of the phase the transaction coordinator asks each node whether it is ready to commit. If everyone agreed, then it tells them to go ahead and commit. What prevents the following failure? All nodes respond that they areready to commit The transactioncoordinator tells them to "go aheadand commit" but one of the nodescrashes before receiving thismessage All other nodes commit successfully, but now the distributed transaction is corrupt It is my understanding that when the crashed node comes back, its transaction will have been rolled back (since it never got the commit message) I am assuming each node is running a normal database that doesn't know anything about distributed transactions. What did I miss?
No, they are not instructed to roll back because in the original poster's scenario, some of the nodes have already committed. What happens is when the crashed node becomes available, the transaction coordinator tells it to commit again. Because the node responded positively in the "prepare" phase, it is required to be able to "commit", even when it comes back from a crash.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ] }
171,878
Is there an app or way to browse a directory that requires different login credentials without using a mapped drive? The issue is given one login credential Windows Explorer only allows you to map it to one drive and disallows using the same login credential to map to a different drive.
No, they are not instructed to roll back because in the original poster's scenario, some of the nodes have already committed. What happens is when the crashed node becomes available, the transaction coordinator tells it to commit again. Because the node responded positively in the "prepare" phase, it is required to be able to "commit", even when it comes back from a crash.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25254/" ] }
171,924
Is it possible to check a bash script syntax without executing it? Using Perl, I can run perl -c 'script name' . Is there any equivalent command for bash scripts?
bash -n scriptname Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/171924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ] }
171,928
I am using the jquery-ui-dialog plugin I am looking for way to refresh the page when in some circumstances when the dialog is closed. Is there a way to capture a close event from the dialog? I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner.
I have found it! You can catch the close event using the following code: $('div#popup_content').on('dialogclose', function(event) { alert('closed'); }); Obviously I can replace the alert with whatever I need to do. Edit: As of Jquery 1.7, the bind() has become on()
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/171928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ] }
171,948
I've been hearing a lot about about how the new version of VMWare Fusion can run virtual operating systems in "headless mode". A Google search makes it clear that other virtualisation products also have similar features, however, I have not been able to find a good description of what this actually means? What is happening when you do this?
Headless mode means that the virtual machine is running in the background without any foreground elements visible (like the Vmware Fusion application) You would have no screen to see running the front end; i.e. the screen/console would not be visible, even though the operating system is running, and would typically have to access the machine via SSH.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/171948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ] }
171,952
Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect? To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed. Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed. I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this.
Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. There is an inherited method called finalize , but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error). There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/171952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18500/" ] }
171,970
When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod() , but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.
Try this: using System.Diagnostics;// Get call stackStackTrace stackTrace = new StackTrace(); // Get calling method nameConsole.WriteLine(stackTrace.GetFrame(1).GetMethod().Name); one-liner: (new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name It is from Get Calling Method using Reflection [C#] .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/171970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470/" ] }
172,018
Is there a way to exclude all svn externals when doing a recursive update? Is there a way to exclude only 1 of all of the svn externals when doing a recursive update? Basically I'd like to cut down the svn update time, and a couple of the SVN externals that I have will just about never get updated.
Yes, there is an option for this (to ignore all): > svn update --ignore-externals I don't know of any option to specifically ignore one or some externals while updating the rest.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
172,040
I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app. Does such an OpenID dev server exist? Is this the best way to go about it?
The libraries at OpenID Enabled ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of this test provider .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039/" ] }
172,060
I've written a small test application using the .Net FileSystemWatcher to keep an eye on a directory. When I copy a large-ish (a few Mb) file into that directory I get the following events listed (see screenshot - and ignore the Delete event to begin with). alt text http://robinwilson.homelinux.com/FSW.png I get a created event (as expected), but then two changed events (about 0.7 seconds apart). Why is this? This would cause major problems in the application I am planning to develop - as I'd try and do things with the file twice (presumably once before it has finished being written to!). Is there anything I can do to stop this happening? From what I've read on StackOverflow and elsewhere, you should just get one changed event once the file has been changed and then closed. Why am I getting two?
According to the documentation (see the first bullet point under Events and Buffer Sizes ): Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ] }
172,065
At work, we're using ClearCase right now. However, there's a lot of overhead required, especially when someone does something stupid (like erase a view with multiple reserved check-outs on the trunk...). Since we're trying to lower our overhead and be as lightweight as possible, we've through about the possibility of ditching CC and going for something lighter (Subversion or Mercurial), seeing as how we don't use 90% of CC's features anyway. Does this sound reasonable or will we be trading our Ferrari in for a station wagon?
From my experience, ClearCase has indeed a lot of overhead and we managed greatly with SVN. I vote, "downgrade" (actually its an UPGRADE). ;)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23202/" ] }
172,095
I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc. I'm using the web reference in a console application. I often change something, recompile and run. Compilation is fast, but newing up the web service reference is very slow, taking some 15-20 seconds: CrmService service = new CrmService(); Profiling reveals that all time is spent in the SoapHttpClientProtocol constructor. The culprit is apparently the fact that the XML serialization code (not included in the 90k loc mentioned above) is generated at run time, before being JIT'ed. This happens during the constructor call. The wait is rather frustrating when playing around and trying things out. I've tried various combinations of sgen.exe, ngen and XGenPlus (which takes several hours and generates 500MB of additional code) but to no avail. I've considered implementing a Windows service that have few CrmService instances ready to dish out when needed but that seems excessive. Any ideas?
The following is ripped from this thread on the VMWare forums: Hi folks, We've found that sgen.exe does work. It'just that there is a couple of additional steps beyond pre-generating the serializer dll's that we missed in this thread. Here is the detailed instruction PROBLEM When using the VIM 2.0 SDK from .NET requires long time to instantiate the VimService class. (The VimService class is the proxy class generated by running 'wsdl.exe vim.wsdl vimService.wsdl') In other words, the following line of code: _service = new VimService(); Could take about 50 seconds to execute. CAUSE Apparently, the .NET XmlSerializer uses the System.Xml.Serialization.* attributes annotating the proxy classes to generate serialization code in run time. When the proxy classes are many and large, as is the code in VimService.cs, the generation of the serialization code can take a long time. SOLUTION This is a known problem with how the Microsoft .NET serializer works. Here are some references that MSDN provides about solving this problem: http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx Unfortunately, none of the above references describe the complete solution to the problem. Instead they focus on how to pre-generate the XML serialization code. The complete fix involves the following steps: Create an assembly (a DLL) with the pre-generated XML serializer code Remove all references to System.Xml.Serialization.* attributes from the proxy code (i.e. from the VimService.cs file) Annotate the main proxy class with the XmlSerializerAssemblyAttribute to point it to where the XML serializer assembly is. Skipping step 2 leads to only 20% improvement in the instantiation time for the VimService class. Skipping either step 1 or 3 leads to incorrect code. With all three steps 98% improvement is achieved. Here are step-by-step instructions: Before you begin, makes sure you are using .NET verison 2.0 tools. This solution will not work with version 1.1 of .NET because the sgen tool and the XmlSerializationAssemblyAttribute are only available in version 2.0 of .NET Generate the VimService.cs file from the WSDL, using wsdl.exe: wsdl.exe vim.wsdl vimService.wsdl This will output the VimService.cs file in the current directory Compile VimService.cs into a library csc /t:library /out:VimService.dll VimService.cs Use the sgen tool to pre-generate and compile the XML serializers: sgen /p VimService.dll This will output the VimService.XmlSerializers.dll in the current directory Go back to the VimService.cs file and remove all System.Xml.Serialization.* attributes. Because the code code is large, the best way to achieve that is by using some regular expression substitution tool. Be careful as you do this because not all attributes appear on a line by themselves. Some are in-lined as part of a method declaration. If you find this step difficult, here is a simplified way of doing it: Assuming you are writing C#, do a global replace on the following string: [System.Xml.Serialization.XmlIncludeAttribute and replace it with: // [System.Xml.Serialization.XmlIncludeAttribute This will get rid of the Xml.Serialization attributes that are the biggest culprits for the slowdown by commenting them out. If you are using some other .NET language, just modify the replaced string to be prefix-commented according to the syntax of that language. This simplified approach will get you most of the speedup that you can get. Removing the rest of the Xml.Serialization attributes only achieves an extra 0.2 sec speedup. Add the following attribute to the VimService class in VimService.cs: [System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")] You should end up with something like this: // ... Some code here ...[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")]public partial class VimService : System.Web.Services.Protocols.SoapHttpClientProtocol {// ... More code here Regenerate VimSerice.dll library by csc /t:library /out:VimService.dll VimService.cs Now, from your application, you can add a reference to VimSerice.dll library. Run your application and verify that VimService object instanciation time is reduced. ADDITIONAL NOTES The sgen tool is a bit of a black box and its behavior varies depending on what you have in your Machine.config file. For example, by default it is supposed to ouptut optimized non-debug code, but that is not always the case. To get some visibility into the tool, use the /k flag in step 3, which will cause it to keep all its temporary generated files, including the source files and command line option files it generated. Even after the above fix the time it takes to instantiate the VimService class for the first time is not instantaneous (1.5 sec). Based on empirical observation, it appears that the majority of the remaining time is due to processing the SoapDocumentMethodAttribute attributes. At this point it is unclear how this time can be reduced. The pre-generated XmlSerializer assembly does not account for the SOAP-related attributes, so these attributes need to remain in the code. The good news is that only the first instantiation of the VimService class for that app takes long. So if the extra 1.5 seconds are a problem, one could try to do a dummy instantiation of this class at the beginning of the application as a means to improve user experience of login time.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2942/" ] }
172,110
How can I elegantly print the date in RFC822 format in Perl?
use POSIX qw(strftime);print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ] }
172,111
Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible?
use POSIX qw(strftime);print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ] }
172,133
I've managed to mostly ignore all this multi-byte character stuff, but now I need to do some UI work and I know my ignorance in this area is going to catch up with me! Can anyone explain in a few paragraphs or less just what I need to know so that I can localize my applications? What types should I be using (I use both .Net and C/C++, and I need this answer for both Unix and Windows).
Check out Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) EDIT 20140523 : Also, watch Characters, Symbols and the Unicode Miracle by Tom Scott on YouTube - it's just under ten minutes, and a wonderful explanation of the brilliant 'hack' that is UTF-8
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/172133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886/" ] }
172,262
What is the difference between #include and #import in C++?
Import in VC++: #import is for type libraries or .tlbs (COM stuff). The content of the type library is converted into C++ classes, mostly describing the COM interfaces for you automatically, and then it is included into your file. The #import directive was introduced by Microsoft as an extension to the C++ language. You can read about it at this MSDN article . The #import directive is also used with .NET / CLI stuff. Import in gcc: The import in gcc is different from the import in VC++. It is a simple way to include a header at most once only. (In VC++ and GCC you can do this via #pragma once as well) The #import directive was officially undeprecated by the gcc team in version 3.4 and works fine 99% of the time in all previous versions of gcc which support Include: #include is for mostly header files, but to prepend the content to your current file. #include is part of the C++ standard. You can read about it at this MSDN article .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/172262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ] }
172,265
I've got a WCF Web Service method whose prototype is: [OperationContract]Response<List<Customer>> GetCustomers(); When I add the service reference to a client, Visual Studio (2005) creates a type called "ResponseOfArrayOfCustomerrleXg3IC" that is a wrapper for "Response<List<Customer>>". Is there any way I can control the wrapper name? ResponseOfArrayOfCustomerrleXg3IC doesn't sound very appealing...
You can define your own name in the DataContract attribute like this: [DataContract(Name = "ResponseOf{0}")]public class Response<T> Note that in your example the {0} will be replaced and your proxy reference type will be ResponseOfArrayOfCustomer . More info here: WCF: Serialization and Generics
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ] }
172,303
Is it possible to detect a valid regular expression with another regular expression? If so please give example code below.
/^ # start of string( # first group start (?: (?:[^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis, with recursive content | \(\? (?:R|[+-]?\d+) \) # recursive matching ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content) # end first group$ # end of string/ This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it. Without whitespace and comments: /^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/ .NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups: ^ # start of string(?: (?: [^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!] | \?<[=!] | \?> | \?<[^\W\d]\w*> | \?'[^\W\d]\w*' )? # opening of group (?<N>) # increment counter | \) # closing of group (?<-N>) # decrement counter ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers| \| # alternative)* # repeat content$ # end of string(?(N)(?!)) # fail if counter is non-zero. Compacted: ^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!)) From the comments: Will this validate substitutions and translations? It will validate just the regex part of substitutions and translations. s/<this part>/.../ It is not theoretically possible to match all valid regex grammars with a regex. It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more. Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes. "In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions. using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor. Regex itself "is not a regular language and hence cannot be parsed by regular expression..." This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task. I see where you're matching []()/\ . and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$ , but not ^abcdefg$ . That's a valid regex. [^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal ( a - z ), and certain special characters ( ^ , $ , . ).
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/172303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10950/" ] }
172,306
I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction: Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished? Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?
Here's the general plan for Twisted. I was originally going to blog this, but then I thought: why blog about it when I could get points for it? Wait until somebody cares. Right now, nobody has Python 3. We're not going to spend a bunch of effort until at least one actual user has come forth and said "I need Python 3.0 support", and has a good reason for it aside from the fact that 3.0 looks shiny. Wait until our dependencies have migrated. A large system like Twisted has a number of dependencies. For starters, ours include: Zope Interface PyCrypto PyOpenSSL pywin32 PyGTK (though this dependency is sadly very light right now, by the time migration rolls around, I hope Twisted will have more GUI tools) pyasn1 PyPAM gmpy Some of these projects have their own array of dependencies so we'll have to wait for those as well. Wait until somebody cares enough to help . There are, charitably, 5 people who work on Twisted - and I say "charitably" because that's counting me, and I haven't committed in months. We have over 1000 open tickets right now, and it would be nice to actually fix some of those — fix bugs, add features, and generally make Twisted a better product in its own right — before spending time on getting it ported over to a substantially new version of the language. This potentially includes sponsors caring enough to pay for us to do it, but I hope that there will be an influx of volunteers who care about 3.0 support and want to help move the community forward. Follow Guido's advice. This means we will not change our API incompatibly , and we will follow the transitional development guidelines that Guido posted last year. That starts with having unit tests, and running the 2to3 conversion tool over the Twisted codebase. Report bugs against, and file patches for, the 2to3 tool . When we get to the point where we're actually using it, I anticipate that there will be a lot of problems with running 2to3 in the future. Running it over Twisted right now takes an extremely long time and (last I checked, which was quite a while ago) can't parse a few of the files in the Twisted repository, so the resulting output won't import. I think there will have to be a fair amount of success stories from small projects and a lot of hammering on the tool before it will actually work for us. However, the Python development team has been very helpful in responding to our bug reports, and early responses to these problems have been encouraging, so I expect that all of these issues will be fixed in time. Maintain 2.x compatibility for several years. Right now, Twisted supports python 2.3 to 2.5. Currently, we're working on 2.6 support (which we'll obviously have to finish before 3.0!). Our plan is to we revise our supported versions of Python based on the long-term supported versions of Ubuntu - release 8.04, which includes Python 2.5, will be supported until 2013. According to Guido's advice we will need to drop support for 2.5 in order to support 3.0, but I am hoping we can find a way around that (we are pretty creative with version-compatibility hacks). So, we are planning to support Python 2.5 until at least 2013. In two years, Ubuntu will release another long-term supported version of Ubuntu: if they still exist, and stay on schedule, that will be 10.04. Personally I am guessing that this will ship with Python 2.x, perhaps python 2.8, as /usr/bin/python , because there is a huge amount of Python software packaged with the distribution and it will take a long time to update it all. So, five years from then , in 2015, we can start looking at dropping 2.x support. During this period, we will continue to follow Guido's advice about migration: running 2to3 over our 2.x codebase, and modifying the 2.x codebase to keep its tests passing in both versions. The upshot of this is that Python 3.x will not be a source language for Twisted until well after my 35th birthday — it will be a target runtime (and a set of guidelines and restrictions) for my python 2.x code. I expect to be writing programs in Python 2.x for the next ten years or so. So, that's the plan. I'm hoping that it ends up looking laughably conservative in a year or so; that the 3.x transition is easy as pie, and everyone rapidly upgrades. Other things could happen, too: the 2.x and 3.x branches could converge, someone might end up writing a 3to2 , or another runtime (PyPy comes to mind) might allow for running 2.x and 3.x code in the same process directly, making our conversion process easier. For the time being, however, we're assuming that, for many years, we will have people with large codebases they're maintaining (or people writing new code who want to use other libraries which have not yet been migrated) who still want new features and bug fixes in Twisted. Pretty soon I expect we will also have bleeding-edge users that want to use Twisted on python 3. I'd like to provide all of those people with a positive experience for as long as possible.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/172306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ] }
172,372
I am wondering about what the difference between logging and tracing is. Is the difference basically that tracing is more detailed log giving developers a tool to debug applications at runtime? I have been experimenting with log4net and doing logging. Now I am wondering if I should be doing tracing as well and if I could/should use log4net for that purpose. Should I be doing tracing with log4net and is there some trace level for log4net loggers? Should I use a different log level for debug and trace purposes or is it ok to use the same?Can you give a simple example on how I would do logging and tracing for a simple method? Edit:Despite a few helpful answers below I am still unsure how I should be doing tracing versus logging. I have the following method in my Business layer and I want to add logging/tracing to it. I am wondering how to do it efficiently. Is the following method acceptable in terms of logging/tracing? Should the log messages be of type Info instead of Debug? Are the Debug messages I am logging considered trace? How would you change it? IEnumerable<Car> GetCars(){ try { logger.Debug("Getting cars"); IEnumerable<Car> cars = CarAccessor.GetCars().ConvertAll(DataAccessToBusinessConverter); logger.Debug("Got total of " + cars.Count + " cars"); } catch (Exception e) { logger.Error("Error when getting cars", e); throw new Exception("Unexpected error when getting cars"); }}
Logging is the generic term for recording information - tracing is the specific form of logging used to debug. In .NET the System.Diagnostics.Trace and System.Diagnostics.Debug objects allow simple logging to a number of "event listeners" that you can configure in app.config. You can also use TraceSwitches to configure and filter (between errors and info levels, for instance). private void TestMethod(string x){ if(x.Length> 10) { Trace.Write("String was " + x.Length); throw new ArgumentException("String too long"); }} In ASP.NET, there is a special version of Trace (System.Web.TraceContext) will writes to the bottom of the ASP page or Trace.axd.In ASP.NET 2+, there is also a fuller logging framework called Health Monitoring. Log4Net is a richer and more flexible way of tracing or logging than the in-built Trace, or even ASP Health Monitoring. Like Diagnostics.Trace you configure event listeners ("appenders") in config. For simple tracing, the use is simple like the inbuilt Trace. The decision to use Log4Net is whether you have more complicated requirements. private void TestMethod(string x){ Log.Info("String length is " + x.Length); if(x.Length> 10) { Log.Error("String was " + x.Length); throw new ArgumentException("String too long"); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ] }
172,388
I understand that they are both supposed to be small, but what are the key differences between the two?
Exokernel is an operating system from MIT (and a class of it's variants) which handles relatively little hardware abstraction. In exokernel, the low-level responsibilities of controlling hardware (particularly memory allocation ) are often left in the hands of the developer. Many developers would probably prefer to have the OS take more responsibility of such low-level tasks, because most developers are just writing applications. An exokernel just allocates physical hardware resources to programs . This allows the program to use library operating systems, which are linked in to provide some of the abstraction that the exokernel isn't providing. The developer can then choose between abstraction models, or roll their own. Given the application, this may have great performance benefits. If you don't know what you're doing, you can also write programs that will explode when they crash. Most kernels will do more to abstract physical hardware resources into some kind of theoretical model . A developer interfaces with this model, which handles the finer points of dealing with hardware internally. The term nanokernel is used to describe a specific type of kernel . The prefix "pico-", or "nano-", "micro-" is usually denoting the "size" of the kernel.. Bigger kernels are more built with more features, and handle more hardware abstraction . Nanokernels are relatively small kernels which provide hardware abstraction , but lack system services . Modern microkernels also lack system services, so the terms have become analogous. The names of kernels usually stem from a specific batch of research which yielded a new kind of kernel, for example the kernel developed at at Carnegie Mellon called "Mach", which was one of the first examples of a modern "microkernel". Sidenote: The real benefit of exokernel is choice. Most of the time, a lot of abstraction means fewer catastrophic bugs. In some applications, you might want to use a different abstraction model, or you might want to handle everything yourself. If we wanted to scrap the OS abstraction for a particular project, we'd have to cut out the operating system and commit a piece of hardware to the job. In the case of exokernel, this isn't necessary. We can program directly "to the metal", but also choose to link in an abstraction model whenever we like. It's a very powerful concept. Sidenote : Dealing with memory on such a low level is unnecessary for most application developers. There are usually several layers of operating system built on top of a kernel, and your application will run on the highest level of the OS. When writing in javascript, you're higher up still, interfacing with a model implemented in an application which runs on an operating system, etc. etc. Addressing memory, while it shouldn't be ignored, might mean something entirely different to a developer who is writing on such a high level of abstraction.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ] }
172,439
I have a multi-line string that I want to do an operation on each line, like so: inputString = """Line 1Line 2Line 3""" I want to iterate on each line: for line in inputString: doStuff()
inputString.splitlines() Will give you a list with each item, the splitlines() method is designed to split each line into a list element.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/172439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1546/" ] }
172,443
I'm looking for a getopt library for c#. So far I found a few ( phpguru , XGetOptCS , getoptfordotnet ) but these look more like unfinished attempts that only support a part of C's getopt.Is there a full getopt c# implementation?
Miguel de Icaza raves about Mono.Options . You can use the nuget package , or just copy the single C# source file into your project.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798/" ] }
172,484
I recently added -pedantic and -pedantic-errors to my make GCC compile options to help clean up my cross-platform code. All was fine until it found errors in external-included header files. Is there a way to turn off this error checking in external header files, i.e.: Keep checking for files included like this: #include "myheader.h" Stop checking for include files like this: #include <externalheader.h> Here are the errors I am getting: g++ -Wall -Wextra -Wno-long-long -Wno-unused-parameter -pedantic --pedantic-errors-O3 -D_FILE_OFFSET_BITS=64 -DMINGW -I"freetype/include" -I"jpeg" -I"lpng128" -I"zlib"-I"mysql/include" -I"ffmpeg/libswscale" -I"ffmpeg/libavformat" -I"ffmpeg/libavcodec"-I"ffmpeg/libavutil" -o omingwd/kguimovie.o -c kguimovie.cppIn file included from ffmpeg/libavutil/avutil.h:41, from ffmpeg/libavcodec/avcodec.h:30, from kguimovie.cpp:44:ffmpeg/libavutil/mathematics.h:32: error: comma at end of enumerator listIn file included from ffmpeg/libavcodec/avcodec.h:30, from kguimovie.cpp:44:ffmpeg/libavutil/avutil.h:110: error: comma at end of enumerator listIn file included from kguimovie.cpp:44:ffmpeg/libavcodec/avcodec.h:277: error: comma at end of enumerator listffmpeg/libavcodec/avcodec.h:303: error: comma at end of enumerator listffmpeg/libavcodec/avcodec.h:334: error: comma at end of enumerator listffmpeg/libavcodec/avcodec.h:345: error: comma at end of enumerator listffmpeg/libavcodec/avcodec.h:2249: warning: `ImgReSampleContext' is deprecated(declared at ffmpeg/libavcodec/avcodec.h:2243)ffmpeg/libavcodec/avcodec.h:2259: warning: `ImgReSampleContext' is deprecated(declared at ffmpeg/libavcodec/avcodec.h:2243)In file included from kguimovie.cpp:45:ffmpeg/libavformat/avformat.h:262: error: comma at end of enumerator listIn file included from ffmpeg/libavformat/rtsp.h:26, from ffmpeg/libavformat/avformat.h:465, from kguimovie.cpp:45:ffmpeg/libavformat/rtspcodes.h:38: error: comma at end of enumerator listIn file included from ffmpeg/libavformat/avformat.h:465, from kguimovie.cpp:45:ffmpeg/libavformat/rtsp.h:32: error: comma at end of enumerator listffmpeg/libavformat/rtsp.h:69: error: comma at end of enumerator list
Using the -Wsystem-headers option, GCC will print warning messages associated with system headers, which are normally suppressed. However, you're looking to have GCC basically treat these files as system headers, so you might try passing "-isystem /usr/local/ffmpeg" (or wherever you installed that package) to get GCC to ignore errors from files included in these directories as well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ] }
172,486
I am looking for a (preferably pure) python library to do AES 256 encryption and decryption. This library should support the CBC cipher mode and use PKCS7 padding according to the answer to an earlier question of mine . The library should at least work on Mac OS X (10.4) and Windows XP. Ideally just by dropping it into the source directory of my project. I have seen this by Josh Davis , but am not sure about how good it is and if it does the required CBC cipher mode... Scanning the source suggests it doesn't
PyCrypto should be the one for you. Edit 02/10/2020: unfortunately I cannot delete this post, since it's the accepted answer. As people pointed out in the comments, this library is not mantained anymore and probably also vulnerable from a security point of view. So please, take a look to the below answers instead.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ] }
172,544
I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops. How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list? try{ if (cbSubFolders.Checked == false) { string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath); foreach (string fileName in files) ProcessFile(fileName); } else { string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories); foreach (string fileName in files) ProcessFile(fileName); } lblNumberOfFilesDisplay.Enabled = true;}catch (UnauthorizedAccessException) { }finally {}
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array): using System;using System.IO;static class Program{ static void Main() { string path = ""; // TODO ApplyAllFiles(path, ProcessFile); } static void ProcessFile(string path) {/* ... */} static void ApplyAllFiles(string folder, Action<string> fileAction) { foreach (string file in Directory.GetFiles(folder)) { fileAction(file); } foreach (string subDir in Directory.GetDirectories(folder)) { try { ApplyAllFiles(subDir, fileAction); } catch { // swallow, log, whatever } } }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/172544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2493/" ] }
172,587
What is the difference between g++ and gcc? Which one of them should be used for general c++ development?
gcc and g++ are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler ). Even though they automatically determine which backends ( cc1 cc1plus ...) to call depending on the file-type, unless overridden with -x language , they have some differences. The probably most important difference in their defaults is which libraries they link against automatically. According to GCC's online documentation link options and how g++ is invoked , g++ is equivalent to gcc -xc++ -lstdc++ -shared-libgcc (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v option (it displays the backend toolchain commands being run).
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/172587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
172,598
I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods. I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C. Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them? As for my findings so far. It is possible to use categories [e.g. MyClass (Private)] defined in MyClass.m file to group private methods. This approach has 2 issues: Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo". The first issue can be worked around with empty category [e.g. MyClass ()]. The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.
There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass () ) called Class Extension . What's unique about a class extension is that the method implementations must go in the same @implementation MyClass as the public methods. So I structure my classes like this: In the .h file: @interface MyClass { // My Instance Variables}- (void)myPublicMethod;@end And in the .m file: @interface MyClass()- (void)myPrivateMethod;@end@implementation MyClass- (void)myPublicMethod { // Implementation goes here}- (void)myPrivateMethod { // Implementation goes here}@end I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/172598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20294/" ] }
172,600
When I try this with a generic class where this.value is T: if (this.value.GetType() == typeof(int)){ ((int)this.value)++;}else{ throw new InvalidOperationException ("T must be an int to perform this operation");} I get a compile-time error: "Cannot convert type 'T' to 'int'" What should I do to perform an integral operation on this.value when it's an int? Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T.
Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types): int i = (int)(object)this.value;i++;this.value = (T)(object)i; Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic, here . The Operator class is part of MiscUtil ; at the simplest level, I suspect AddAlternative would work very well: this.value = Operator.AddAlternative(this.value, 1); This should infer the implicit <T,int> automatically, or you can add them yourself: this.value = Operator.AddAlternative<T,int>(this.value, 1); Benefit : This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)". I think there is also a ChangeType hiding around somewhere in there... [edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless really necessary. That said (as per my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix<T> [for T in decimal/float/int/double/etc] is often highly valuable.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ] }
172,614
On OS X, does Objective-C compile to native code or byte-code? Can Objective-C programs be compiled on Linux?
Objective-C is compiled to native code by either GCC or LLVM[*]. You can compile ObjC programs on Linux (the generic GCC will happily support ObjC, though it uses a different runtime library than either of the Apple ones). For a cross-platform API similar to Cocoa (i.e. derived from Cocoa) which will happily work on Linux and let you port some code between OS X and Linux, check out GNUstep: http://www.gnustep.org [*]In fact, LLVM internally compiles the Objective-C to an internal bitcode representation, then to code for the target machine, so perhaps the answer is "both"…
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
172,648
I have a photo website and i want to support tags as my original category bucketing is starting to fail (some pictures are family and vacations, or school and friends). Is there an agreed tagging db schema? I still want to support having photos as part of an album. Right now i have a few tables: Photos PhotoID PhotoAlbumID Caption Date Photo Album AlbumID AlbumName AlbumDate
There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows: http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/ http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/ Personally, I like having a tag table and a link table which associates tags with items, as it's denormalized (no duplication of tag names) and I can store additional information in the link table (such as when the item was tagged) when necessary. You can also add some denormalised data if you're feeling frisky and want simple selects at the cost of the additional data maintenance required by storing usage counts in the tag table, or storing tag names which were used in the item table itself to avoid hitting the link table and tag table for each item, which is useful for displaying multiple items with all their tags and for simple tag versioning... if you're into that sort of thing ;)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ] }
172,653
Is there any way (maybe directly editing resource files) to configure a Tab Control (add/remove tabs and their captions and contents) at design time with Visual Studio 2008 without SP1 (I heard that SP1 has such feature)?P.S.: I use c++ with wtl
There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows: http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/ http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/ Personally, I like having a tag table and a link table which associates tags with items, as it's denormalized (no duplication of tag names) and I can store additional information in the link table (such as when the item was tagged) when necessary. You can also add some denormalised data if you're feeling frisky and want simple selects at the cost of the additional data maintenance required by storing usage counts in the tag table, or storing tag names which were used in the item table itself to avoid hitting the link table and tag table for each item, which is useful for displaying multiple items with all their tags and for simple tag versioning... if you're into that sort of thing ;)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ] }
172,658
I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class. Specifically, given StringBuilder sb , I'd like sb += "text" to become equivalent to sb.Append("text") . Here's the syntax for creating an extension method for StringBuilder : public static class sbExtensions{ public static StringBuilder blah(this StringBuilder sb) { return sb; }} It successfully adds the blah extension method to the StringBuilder . Unfortunately, operator overloading does not seem to work: public static class sbExtensions{ public static StringBuilder operator +(this StringBuilder sb, string s) { return sb.Append(s); }} Among other issues, the keyword this is not allowed in this context. Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?
This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads. But the feature is being discussed for some future release of C# . Mads talked a bit more about implementing it in this video from 2017 . On why it isn't currently implemented, Mads Torgersen, C# Language PM says: ...for the Orcas release we decided totake the cautious approach and addonly regular extension methods, asopposed to extention properties,events, operators, static methods, etcetc. Regular extension methods werewhat we needed for LINQ, and they hada syntactically minimal design thatcould not be easily mimicked for someof the other member kinds. We are becoming increasingly awarethat other kinds of extension memberscould be useful, and so we will returnto this issue after Orcas. Noguarantees, though! Further below in the same article: I am sorry to report that we will notbe doing this in the next release. Wedid take extension members veryseriously in our plans, and spent alot of effort trying to get themright, but in the end we couldn't getit smooth enough, and decided to giveway to other interesting features. This is still on our radar for futurereleases. What will help is if we geta good amount of compelling scenariosthat can help drive the right design.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/172658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388/" ] }
172,720
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: Firstly : Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization? Secondly : When writing a program from scratch in python, what are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions. In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this: result = u""for item in my_list: result += unicode (item) will copy the entire string twice per iteration. This has been well-covered, and the solution is to use "".join : result = "".join (unicode (item) for item in my_list) Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list. Finally, don't be afraid to rewrite bits in C! Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module. My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ] }
172,748
Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This: window.open(src, 'newWin', 'fullscreen="yes"') apparently only worked for old version of IE.
Use screen.availWidth and screen.availHeight to calculate a suitable size for the height and width parameters in window.open() Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/172748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3037/" ] }
172,753
just wondering if anyone has ever tried embedding and actually integrating any js engine into the .net environment. I could find and actually use (after a LOT of pain and effort, since it's pretty outdated and not quite finished) spidermonkey-dotnet project. Anyone with experience in this area? Engines like SquirrelFish, V8.. Not that I'm not satisfied with Mozilla's Spidermonkey (using it for Rails-like miniframework for custom components inside the core ASP.NET application), but I'd still love to explore a bit further with the options. The command-line solutions are not what I'd need, I cannot rely on anything else than CLR, I need to call methods from/to JavaScript/C# objects. // c# classpublic class A{ public string Hello(string msg) { return msg + " whatewer"; }}// js snippetvar a = new A();console.log(a.Hello('Call me')); // i have a console.log implemented, don't worry, it's not a client-side code :) Just to clarify - I'm not trying to actually program the application itself in server-side javascript. It's used solely for writing custom user subapplications (can be seen as some sort of DSL). It's much easier (and safer) to allow normal people programming in js than C#.
The open source JavaScript interpreter Jint ( http://jint.codeplex.com ) does exactly what you are looking for. Edit: The project has been entirely rewritten and is now hosted on Github at https://github.com/sebastienros/jint
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/172753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25339/" ] }
172,781
My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working. However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again. Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there?
There is - it's called an "in-place import", and it's covered in the Subversion FAQ here: http://subversion.tigris.org/faq.html#in-place-import What you're really doing is creating a new empty project in the repository, checking out the empty project your local folder - which turns your folder into a working copy - and then adding all your (existing) files to that 'empty' project, so they're added to the repository when you do an svn commit.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21406/" ] }
172,798
I have experimented with Lisp (actually Scheme) and found it to be a very beautiful language that I am interested in learning more about. However, it appears that Lisp is never used in serious projects, and I haven't seen it listed as a desired skill on any job posting. I am interested in hearing from anyone who has used Lisp or seen it used in the "real world", or who knows whether it is considered a purely academic language.
Franz, Inc. provides an inexhaustive list of success stories on their website. However: Please don't assume Lisp is only useful for Animation and Graphics, AI, Bioinformatics, B2B and E-Commerce, Data Mining, EDA/Semiconductor applications, Expert Systems, Finance, Intelligent Agents, Knowledge Management, Mechanical CAD, Modeling and Simulation, Natural Language, Optimization, Research, Risk Analysis, Scheduling, Telecom, and Web Authoring just because these are the only things they happened to list. — Kent Pitman We can find other success stories here: http://lisp-lang.org/success/ and a list of current companies using Common Lisp: https://github.com/azzamsa/awesome-lisp-companies
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/172798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18091/" ] }
172,812
I have the following style in an external CSS file called first.css table { width: 100%; } This makes the tables fill their container. If there are only two small columns they appear too far from each other. To force the columns to appear nearer I have added this style table { width: 50%; } to a new file called second.css and linked it into the html file. Is there any way to override the width property in first.css without the need to specify a width in second.css? I would like the html behave as if there has never been a width property, but I do not want to modify first.css
You can use: table { width: auto; } in second.css, to strictly make "the html behave as if there was never been a width property". But I'm not 100% sure this is exactly what you want - if not, please clarify!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ] }
172,821
I've got a div that contains some content that's being added and removed dynamically, so its height is changing often. I also have a div that is absolutely positioned directly underneath with javascript, so unless I can detect when the height of the div changes, I can't reposition the div below it. So, how can I detect when the height of that div changes? I assume there's some jQuery event I need to use, but I'm not sure which one to hook into.
I wrote a plugin sometime back for attrchange listener which basically adds a listener function on attribute change. Even though I say it as a plugin, actually it is a simple function written as a jQuery plugin.. so if you want.. strip off the plugin specfic code and use the core functions. Note: This code doesn't use polling check out this simple demo http://jsfiddle.net/aD49d/ $(function () { var prevHeight = $('#test').height(); $('#test').attrchange({ callback: function (e) { var curHeight = $(this).height(); if (prevHeight !== curHeight) { $('#logger').text('height changed from ' + prevHeight + ' to ' + curHeight); prevHeight = curHeight; } } }).resizable();}); Plugin page: http://meetselva.github.io/attrchange/ Minified version: (1.68kb) (function(e){function t(){var e=document.createElement("p");var t=false;if(e.addEventListener)e.addEventListener("DOMAttrModified",function(){t=true},false);else if(e.attachEvent)e.attachEvent("onDOMAttrModified",function(){t=true});else return false;e.setAttribute("id","target");return t}function n(t,n){if(t){var r=this.data("attr-old-value");if(n.attributeName.indexOf("style")>=0){if(!r["style"])r["style"]={};var i=n.attributeName.split(".");n.attributeName=i[0];n.oldValue=r["style"][i[1]];n.newValue=i[1]+":"+this.prop("style")[e.camelCase(i[1])];r["style"][i[1]]=n.newValue}else{n.oldValue=r[n.attributeName];n.newValue=this.attr(n.attributeName);r[n.attributeName]=n.newValue}this.data("attr-old-value",r)}}var r=window.MutationObserver||window.WebKitMutationObserver;e.fn.attrchange=function(i){var s={trackValues:false,callback:e.noop};if(typeof i==="function"){s.callback=i}else{e.extend(s,i)}if(s.trackValues){e(this).each(function(t,n){var r={};for(var i,t=0,s=n.attributes,o=s.length;t<o;t++){i=s.item(t);r[i.nodeName]=i.value}e(this).data("attr-old-value",r)})}if(r){var o={subtree:false,attributes:true,attributeOldValue:s.trackValues};var u=new r(function(t){t.forEach(function(t){var n=t.target;if(s.trackValues){t.newValue=e(n).attr(t.attributeName)}s.callback.call(n,t)})});return this.each(function(){u.observe(this,o)})}else if(t()){return this.on("DOMAttrModified",function(e){if(e.originalEvent)e=e.originalEvent;e.attributeName=e.attrName;e.oldValue=e.prevValue;s.callback.call(this,e)})}else if("onpropertychange"in document.body){return this.on("propertychange",function(t){t.attributeName=window.event.propertyName;n.call(e(this),s.trackValues,t);s.callback.call(this,t)})}return this}})(jQuery)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/172821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384/" ] }
172,831
If you have the following: $var = 3; // we'll say it's set to 3 for this exampleif ($var == 4) { // do something} else if ($var == 5) { // do something} else if ($var == 2) { // do something} else if ($var == 3) { // do something} else { // do something} If say 80% of the time $var is 3, do you worry about the fact that it's going through 4 if cases before finding the true case? I'm thinking on a small site it's not a big deal, but what about when that if statement is going to run 1000s of times a second? I'm working in PHP, but I'm thinking the language doesn't matter.
Here's how we did it when I used to write software for radar systems. (Speed matters in radar. It's one of the few places where "real time" actually means "real" instead of "fast".) [I'll switch to Python syntax, it's easier for me and I'm sure you can interpret it.] if var <= 3: if var == 2: # do something elif var == 3: # do something else: raise Exceptionelse: if var == 4: # do something elif var == 5: # do something else: raise Exception Your if-statements form a tree instead of a flat list. As you add conditions to this list, you jiggle around the center of the tree. The flat sequence of n comparisons takes, on average, n /2 steps. The tree leads to a sequence of comparisons that takes log( n ) comparisons.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/172831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ] }