source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
98,695
What principles do you generally follow when doing class design?
Principles Of Object Oriented Class Design (the "SOLID" principles) SRP: The Single ResponsibilityPrinciple A class should have one,and only one, reason to change. OCP: The Open Closed Principle Youshould be able to extend a classesbehavior, without modifying it. LSP: The Liskov SubstitutionPrinciple Derived classes must besubstitutable for their baseclasses. ISP: The Interface SegregationPrinciple Make fine grainedinterfaces that are client specific. DIP: The DependencyInversion Principle Depend onabstractions, not on concretions. Source: http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod Video (Uncle Bob): Clean Coding By Robert C. Martin ( Uncle Bob )
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/98695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18175/" ] }
98,705
I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g. class object{ int get_value(int n) const { ... }...object x;int a = x.get_value(1); ...int b = x.get_value(1); then the compiler could optimize the second call away and either use the value in a register or simply do b = a; Is this true?
const is about program semantics and not about implementation details. You should mark a member function const when it does not change the visible state of the object, and should be callable on an object that is itself const . Within a const member function on a class X , the type of this is X const * : pointer to constant X object. Thus all member variables are effectively const within that member function (except mutable ones). If you have a const object, you can only call const member functions on it. You can use mutable to indicate that a member variable may change even within a const member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the const member functions) or use counters. class X{ int data; mutable boost::mutex m;public: void set_data(int i) { boost::lock_guard<boost::mutex> lk(m); data=i; } int get_data() const // we want to be able to get the data on a const object { boost::lock_guard<boost::mutex> lk(m); // this requires m to be non-const return data; }}; If you hold the data by pointer rather than directly (including smart pointers such as std::auto_ptr or boost::shared_ptr ) then the pointer becomes const in a const member function, but not the pointed-to data, so you can modify the pointed-to data. As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function effectively only being called once. The next version of the C++ Standard (C++0x) will have a new keyword constexpr . Functions tagged constexpr return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/98705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ] }
98,768
I can understand that imposing a minimum length on passwords makes a lot of sense (to save users from themselves), but my bank has a requirement that passwords are between 6 and 8 characters long, and I started wondering... Wouldn't this just make it easier for brute force attacks? (Bad) Does this imply that my password is being stored unencrypted? (Bad) If someone with (hopefully) some good IT security professionals working for them are imposing a max password length, should I think about doing similar? What are the pros/cons of this?
Passwords are hashed to 32, 40, 128, whatever length. The only reason for a minimum length is to prevent easy to guess passwords. There is no purpose for a maximum length. The obligatory XKCD explaining why you're doing your user a disservice if you impose a max length:
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/98768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ] }
98,774
I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this. // Quick, and very dirtySystem.IO.File.WriteAllBytes(filename, new byte[f.Length]); It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops. So, with a little more enlightenment, I set out with the following algorithm. using (FileStream outFile = System.IO.File.Create(filename)){ // 4194304 = 4MB; loops from 1 block in so that we leave the loop one // block short byte[] buff = new byte[4194304]; for (int i = buff.Length; i < f.Length; i += buff.Length) { outFile.Write(buff, 0, buff.Length); } outFile.Write(buff, 0, f.Length % buff.Length);} This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk. The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct).
FileStream.SetLength is the one you want. The syntax: public override void SetLength( long value)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/98774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ] }
98,878
I've always been wondering how people use CRC (class responsiblity collaboration) cards. I've read about them in books, found vague information on the internet, but never grasped it really. I think someone ought to make a youtube video showing a session with CRC cards, since one of my books described it as being very hard to formulate in text, that it should be "taught by someone who already masters it". Sadly, I know noone around here who uses CRC cards and I'd like to learn more. UPDATE Any links to videos showing people elaborating with this technique would be appreciated.
I'll try to give an answer.So CRC cards are generally used for modelling in a Object-Oriented environment to get a better understanding of the system that has to be developed (but that I think you'll know already).CRC cards come at the very end, when you arrive just before the actual implementation. The different steps to reach that level could be the following: The starting point is to do the requirement elicitation. Involving the customer early and continuously is suggested here (take a look at Agile approaches, i.e. Extreme Programming) The requirements can then be modeled either with Use Case diagrams (UML) or with User stories (agile extreme programming approach). The key problem here is to find the right involved objects. This depends very much on the domain you're in, of course. If you go the "hard" way, you can apply techniques like "noun extraction". So you parse the specification document and extract all nouns (including composite names and those with adjectives). Analyze all of them and discard the irrelevant ones. Once you have the right nouns -> objects you can start creating your CRC cards. So what is done in a CRC session? The main task is to find and assign the responsibilities of your (previously) found objects which are then put down on small index cards (our CRC cards). "Responsibilities" are mainly the core functionalities of a specific object and the "collaboration" part are the needed other objects for fulfilling certain functionalities (these are the dependencies among the different objects in your model). Important points for assigning the responsibilities is that the responsibilities are distributed well on the whole system in some kind of balanced way. Another very important point is to avoid any duplication of responsibilities among the objects (this is where the CRC cards help). A CRC session should start with a brainstorming meeting, having an active discussion among the developers and it should be performed on the actual index cards directly. I hope I was able to somehow help you. Regards, Juri
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/98878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166173/" ] }
99,056
If given the choice, which path would you take? ASP.NET Webforms + ASP.NET AJAX or ASP.NET MVC + JavaScript Framework of your Choice Are there any limitations that ASP.NET Webforms / ASP.NET AJAX has vis-a-vis MVC?
I've done both lately, I would take MVC nine times out of ten. I really dislike the implementation of the asp.net ajax controls, I've run into a lot of issues with timing, events, and debugging postback issues. I learned a lot from http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/ The asp.net project we used the MVP pattern http://www.codeplex.com/aspnetmvp , and the pattern worked great. However we ended up with a lot of code in the view because we were directly interacting with the server side controls (i.e a lot of gridview manipulations). This code is nearly untestable with the unit test frameworks. We should have been more diligent about keeping code out of the view, but in some instances it was just easier and less messy. The one time I would choose using asp.net forms development would be to use the gridview control. We are using jquery for our javascript framework with MVC and have not yet found a very good gridview like control. We have something that is functional, but the amount of time we have sunk into learning, tweaking, and debugging it vs using asp.net server side controls has been substantial. One looses all of the nice widgets Microsoft provides out of the box doing non asp.net form development. The loss of those widgets is freeing, and scary at the same time when you first start. At the end of the day I'm happy we are doing MVC development. My team and I have learned a new framework, (we were only asp.net developers before), and have gotten our hands dirty with html and javascript. These are skills we can take onto other projects or other languages if we ever need to.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ] }
99,098
What is the best way to generate a current datestamp in Java? YYYY-MM-DD:hh-mm-ss
Using the standard JDK, you will want to use java.text.SimpleDateFormat Date myDate = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");String myDateString = sdf.format(myDate); However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat Date myDate = new Date();FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss");String myDateString = fdf.format(myDate); FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example: SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");Date yourDate = sdf.parse("2008-09-18:22-03-15");
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3020/" ] }
99,117
My question: Is the MIPS programming language that beneficial to know? I'm a CS student and am taking an assembly class which focuses on MIPS. I'm very comfortable writing in high level languages, but MIPS has me a little bit down. Is MIPS something that I should really focus on and try to completely grasp? Will it help me in future?
At one point (in the 90s) MIPS-derived processors were the best selling processors in the world, dwarfing sales of Intel x86 processors. This was because of their huge presence in the embedded market. I think now ARM-based processors may have taken over that title, but there are still tons of embedded systems out there using MIPS. Even if you never program a MIPS chip in assembler in your career, assembly language can be useful to learn. It can help you write more efficient high level code if you have some idea of what the compiler is going to emit. Other areas where it is still used include compilers (writing your own), device drivers, and multimedia programming (where code requiring MMX or SSE is usually still written by hand in assembler). Each CPU type has a different instruction set but there's enough commonality that once you learn one dialect of assembly (MIPS in your case) the others should be easy to pick up.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17083/" ] }
99,132
I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it. I mainly use mingw/msys but would like something that works across other shells/systems too. I tried this but it didn't work, any ideas? ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))-mkdir $(OBJDIR)endif
On UNIX Just use this: mkdir -p $(OBJDIR) The -p option to mkdir prevents the error message if the directory exists.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/99132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ] }
99,161
I search for "nurple" in a file. I found it, great. But now, every occurrence of "nurple" is rendered in sick black on yellow. Forever. Forever, that is, until I search for something I know won't be found, such as "asdhfalsdflajdflakjdf" simply so it clears the previous search highlighting. Can't I just hit a magic key to kill the highlights when I'm done searching?
:noh (short for nohighlight ) will temporarily clear the search highlight. The next search will still be highlighted.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/99161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ] }
99,164
I often see code like: Iterator i = list.iterator();while(i.hasNext()) { ...} but I write that (when Java 1.5 isn't available or for each can't be used) as: for(Iterator i = list.iterator(); i.hasNext(); ) { ...} because It is shorter It keeps i in a smaller scope It reduces the chance of confusion. (Is i used outside thewhile? Where is i declared?) I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better? From: http://jamesjava.blogspot.com/2006/04/iterating.html
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/99164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ] }
99,211
I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an aplication.html.haml or index.html.haml for a view, I just receive errors. I am using NetBeans as my IDE.
Haml with Rails 3 For Rails 3 all you need to do is add gem "haml", '3.0.25' to your Gemfile . No need to install plugin or run haml --rails . . Just: $ cd awesome-rails-3-app.git$ echo 'gem "haml"' >> Gemfile And you're done.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
99,279
I want to parse a web page in Groovy and extract all of the href links and the associated text with it. If the page contained these links: <a href="http://www.google.com">Google</a><br /><a href="http://www.apple.com">Apple</a> the output would be: Google, http://www.google.com<br />Apple, http://www.apple.com I'm looking for a Groovy answer. AKA. The easy way!
Assuming well-formed XHTML, slurp the xml, collect up all the tags, find the 'a' tags, and print out the href and text. input = """<html><body><a href = "http://www.hjsoft.com/">John</a><a href = "http://www.google.com/">Google</a><a href = "http://www.stackoverflow.com/">StackOverflow</a></body></html>"""doc = new XmlSlurper().parseText(input)doc.depthFirst().collect { it }.findAll { it.name() == "a" }.each { println "${it.text()}, ${[email protected]()}"}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
99,297
We all know what virtual functions are in C++, but how are they implemented at a deep level? Can the vtable be modified or even directly accessed at runtime? Does the vtable exist for all classes, or only those that have at least one virtual function? Do abstract classes simply have a NULL for the function pointer of at least one entry? Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
How are virtual functions implemented at a deep level? From "Virtual Functions in C++" : Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions. The object of the class containing the virtual function contains a virtual pointer that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve to the function address. An object of the class that contains one or more virtual functions contains a virtual pointer called the vptr at the very beginning of the object in the memory. Hence the size of the object in this case increases by the size of the pointer. This vptr contains the base address of the virtual table in memory. Note that virtual tables are class specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains. This virtual table in turn contains the base addresses of one or more virtual functions of the class. At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call. Can the vtable be modified or even directly accessed at runtime? Universally, I believe the answer is "no". You could do some memory mangling to find the vtable but you still wouldn't know what the function signature looks like to call it. Anything that you would want to achieve with this ability (that the language supports) should be possible without access to the vtable directly or modifying it at runtime. Also note, the C++ language spec does not specify that vtables are required - however that is how most compilers implement virtual functions. Does the vtable exist for all objects, or only those that have at least one virtual function? I believe the answer here is "it depends on the implementation" since the spec doesn't require vtables in the first place. However, in practice, I believe all modern compilers only create a vtable if a class has at least 1 virtual function. There is a space overhead associated with the vtable and a time overhead associated with calling a virtual function vs a non-virtual function. Do abstract classes simply have a NULL for the function pointer of at least one entry? The answer is it is unspecified by the language spec so it depends on the implementation. Calling the pure virtual function results in undefined behavior if it is not defined (which it usually isn't) (ISO/IEC 14882:2003 10.4-2). In practice it does allocate a slot in the vtable for the function but does not assign an address to it. This leaves the vtable incomplete which requires the derived classes to implement the function and complete the vtable. Some implementations do simply place a NULL pointer in the vtable entry; other implementations place a pointer to a dummy method that does something similar to an assertion. Note that an abstract class can define an implementation for a pure virtual function, but that function can only be called with a qualified-id syntax (ie., fully specifying the class in the method name, similar to calling a base class method from a derived class). This is done to provide an easy to use default implementation, while still requiring that a derived class provide an override. Does having a single virtual function slow down the whole class or only the call to the function that is virtual? This is getting to the edge of my knowledge, so someone please help me out here if I'm wrong! I believe that only the functions that are virtual in the class experience the time performance hit related to calling a virtual function vs. a non-virtual function. The space overhead for the class is there either way. Note that if there is a vtable, there is only 1 per class , not one per object . Does the speed get affected if the virtual function is actually overridden or not, or does this have no effect so long as it is virtual? I don't believe the execution time of a virtual function that is overridden decreases compared to calling the base virtual function. However, there is an additional space overhead for the class associated with defining another vtable for the derived class vs the base class. Additional Resources: http://www.codersource.net/published/view/325/virtual_functions_in.aspx (via way back machine) http://en.wikipedia.org/wiki/Virtual_table http://www.codesourcery.com/public/cxx-abi/abi.html#vtable
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/99297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
99,318
Possible Duplicate: What does map(&:name) mean in Ruby? I was watching a railscast and saw this code. [Category, Product].(&:delete_all) In regards to clearing a database. I asked about the line in IRC and was told (&:delete_all) was a shortcut for {|model| model.delete_all} I tested this with the following class ClassOne def class_method puts 1 endendclass ClassTwo def class_method puts 2 endend[ClassOne, ClassTwo].each(&:class_method) I received an error saying Wrong Argument type Symbol (expected Proc) I also tried one = ClassOne.newtwo = ClassTwo.new[one, two].each(&:class_method) But that still failed. If I modified it to read [one, two].each{|model| model.class_method} Everything worked as expected. So, what does &:delete_all actually do? The docs say delete_all is a method, so I am confused as to what is going on here.
This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following: class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } endend I believe Rails defines this in ActiveSupport .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ] }
99,353
How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-right points.
The original poster wanted to DETECT an intersection between a line segment and a polygon. There was no need to LOCATE the intersection, if there is one. If that's how you meant it, you can do less work than Liang-Barsky or Cohen-Sutherland: Let the segment endpoints be p1=(x1 y1) and p2=(x2 y2). Let the rectangle's corners be (xBL yBL) and (xTR yTR). Then all you have to do is A. Check if all four corners of the rectangle are on the same side of the line.The implicit equation for a line through p1 and p2 is: F(x y) = (y2-y1)*x + (x1-x2)*y + (x2*y1-x1*y2) If F(x y) = 0, (x y) is ON the line. If F(x y) > 0, (x y) is "above" the line. If F(x y) < 0, (x y) is "below" the line. Substitute all four corners into F(x y). If they're all negative or all positive, there is no intersection. If some are positive and some negative, go to step B. B. Project the endpoint onto the x axis, and check if the segment's shadow intersects the polygon's shadow. Repeat on the y axis: If (x1 > xTR and x2 > xTR), no intersection (line is to right of rectangle). If (x1 < xBL and x2 < xBL), no intersection (line is to left of rectangle). If (y1 > yTR and y2 > yTR), no intersection (line is above rectangle). If (y1 < yBL and y2 < yBL), no intersection (line is below rectangle). else, there is an intersection. Do Cohen-Sutherland or whatever code was mentioned in the other answers to your question. You can, of course, do B first, then A. Alejo
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14385/" ] }
99,391
When I commit I get this error from Subversion: bash-2.05b$ svn commit -m "testing subversion, still"Adding bazsvn: Commit failed (details follow):svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com)
This happens when you have added a directory that someone else has also added and already committed. The error message on a commit is really confusing, but if you do an svn up instead you'll see this message: bash-2.05b$ svn upsvn: Failed to add directory 'baz': object of the same name already exists To resolve the issue, remove your directory (or move it aside) and do an svn update to get the version on the server and re-do your changes. As a general rule, be sure to do svn update since the error messages tend to be more helpful.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/99391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9594/" ] }
99,395
How to check if a folder (directory) exists in Cocoa using Objective-C?
Use NSFileManager 's fileExistsAtPath:isDirectory: method. See Apple's docs here .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/99395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ] }
99,460
Do you think that writing about software (i.e. having a blog) and speaking on software (and concepts) make you a better programmer?
Statistically speaking yes. You only retain about 20% of what you read and hear, but 80% of what you teach. By writing about something or teaching about it, you force yourself to understand the concepts on a much deeper level. UPDATE: I wanted to update this with some links to more concrete data to support the statistics that I have been taught numerous times about learning retention rates. However, it would appear there is some controversy surrounding these numbers , even though the NTL Institute for Applied Behavioral Science maintains that research was done to back them up.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18475/" ] }
99,474
What is the best way to handle a big team that has access to a stable but no so pretty code, that is easy to introduce bugs into? I'm looking for something along the lines of SVN locking the file(s).
Write unit tests if you don't have them already. Then start refactoring, and keep doing regression tests upon every commit.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
99,510
Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ... Does multiple inheritance slow down a class?
Non-virtual function-calls have absolutely no performance hit at run-time, in accordance with the c++ mantra that you shouldn't pay for what you don't use.In a virtual function call, you generally pay for an extra pointer lookup, no matter how many levels of inheritance, or number of base classes you have.Of course this is all implementation defined. Edit: As noted elsewhere, in some multiple inheritance scenarios, an adjustment to the 'this' pointer is required before making the call. Raymond Chen describes how this works for COM objects. Basically, calling a virtual function on an object that inherits from multiple bases can require an extra subtraction and a jmp instruction on top of the extra pointer lookup required for a virtual call.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
99,548
ZeroC's ICE (www.zeroc.com) looks interesting and I am interested in looking at it and comparing it to our existing software that uses WCF. In particular, our WCF app uses server callbacks (via HTTP). Anybody who's compared them? How did it go? I'm particularly interested in the performance aspect, since interoperability isn't much of a concern for us right now. Thanks!
I did a very terse review of ICE a few years ago, and although I haven't compared them directly before, having reasonable knowledge of WCF my thoughts might have some relevance. Firstly, it's not entierely fair to compare WCF with ICE as WCF as ICE is a specific remote communication mechanism and WCF is a higher level remote communications framework. While WCF is often thought of as implementing SOAP web services, and that is indeed its main use to date, it can also be used for implementing remote services using all manner of encodings and transport channels, which means it can theoretically be used for performant comms between applications. In comparison, ICE is a cross-platform remote communicaton mechanism that uses binary encoding for performant communications between applications. It's something of a simplified evolution of CORBA and is more directly comparable to CORBA, DCOM, .NET Remoting, and JNI. However, even though there's no direct correspondence between ICE and WCF, if you need your .NET app to communicate remotely then they're both contenders. Some of the decision points you might want to consider include: Resourcing. It'll be easier to find developers with WCF experience than ICE experience. Performance. If you want performance then ICE performs fast, but WCF can also be used in a performant configuration. Alternatively, .NET Remoting can provide very good performance, and whatever the MS-sponsored benchmarks say I've seen it outperform WCF by 10%. Cross-platform. If you need to communicate with non-Windows applications then you're limited with the WCF options you can use. In addition, since every SOAP stack seems to implement the standards differently it can be a pain creating truly generic Web Services (though WS-I helps) If you don't need every ounce of performance from day one, then I'd personally plump for WCF to start with, and then consider ICE if performance ever becomes critical. Even then it might be cheaper to scale out your service boxes than it is to move to ICE, and if you don't have any exotic cross-platform needs then you could always look at reconfiguring WCF for binary encoding etc
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6441/" ] }
99,552
I sometimes notice programs that crash on my computer with the error: "pure virtual function call". How do these programs even compile when an object cannot be created of an abstract class?
They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist. class Base{public: Base() { reallyDoIt(); } void reallyDoIt() { doIt(); } // DON'T DO THIS virtual void doIt() = 0;};class Derived : public Base{ void doIt() {}};int main(void){ Derived d; // This will cause "pure virtual function call" error} See also Raymond Chen's 2 articles on the subject
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/99552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
99,553
I'm wondering if it's possible to distribute a RoR app for production use without source code? I've seen this post on SO , but my situation is a little different. This would be an app administered by people with some clue, so I'm cool with still requiring an Apache/Mongrel/MySQL setup on the customer end. All I really want is for the source to be protected. Encoding seems a popular way to go for distributing PHP apps (eg: Helpspot ). I've found these potential solutions: Zenobfuscate - not all types of Ruby code is supported however, so that counts that out Ruby Encoder - may be the best option, as their PHP encoder looks alright (I haven't tried it however) but it's not available yet. I've used IONcube for PHP before and it worked well, but it doesn't seem that IONcube is interested yet . Slingshot - it was mentioned in the other SO post, but it solves a different problem to mine and the source is still visible. RubyScript2Exe - from the doco, it's not production ready, so that counts that out. I've heard that potentially using JRuby and distributing bytecode might be a way to achieve this, but I've never used JRuby so I'm not sure what's involved. Can anyone offer any ideas and/or known examples? Ideally I'd love to have some kind of automated build scenario as well.
Your best option right now is to use JRuby. A little bit of background: My company ( BitRock ) works with many proprietary and commercial open source vendors. We help them package their server software, which is typically based on PHP, Java or Ruby together with a web server or application server (Apache, Tomcat), the language runtime and a database (typically Postgres, MySQL) into a self-contained, easy to use installer. We have a large number of PHP-based customers (including HelpSpot, which you mention) but also several Rails-based ones. In the case of the RoR customers the norm is to use JRuby together with Tomcat or Glassfish although in some cases we also bundle a native Ruby interpreter to run specific scripts that rely on libraries not yet ported to JRuby (usually not core to the application). JRuby has matured quickly and in many cases it actually runs their code faster than regular Ruby. You will need to also consider that although porting your code to JRuby is fairly straightforward, you will need to invest some time on that. You may want to check JRuby Stack which is a free installer of everything you need to get started. Good luck!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14530/" ] }
99,623
I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window. Is this possible, using C++ / MFC?
Charlie hit on the answer with WM_NCPAINT . If you're using MFC, the code would look something like this: // in the message mapON_WM_NCPAINT()// ...void CMainFrame::OnNcPaint(){ // still want the menu to be drawn, so trigger default handler first Default(); // get menu bar bounds MENUBARINFO menuInfo = {sizeof(MENUBARINFO)}; if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) ) { CRect windowBounds; GetWindowRect(&windowBounds); CRect menuBounds(menuInfo.rcBar); menuBounds.OffsetRect(-windowBounds.TopLeft()); // horrible, horrible icon-drawing code. Don't use this. Seriously. CWindowDC dc(this); HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); ::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL); ::DestroyIcon(appIcon); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
99,643
After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li. Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing. I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).
YUI provides a base CSS file that will give consistent styles across all 'A-grade' browsers. They also provide a CSS reset file, so you could use that as well, but you say you've already reset the CSS. For further details go to the YUI website . This is what I've been using and it works really well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ] }
99,683
My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other. I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to. update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code.
For some languages (i.e. C++) Resources leak should not be a reason C++ is based on RAII. If you have code that could fail, return or throw (that is, most normal code), then you should have your pointer wrapped inside a smart pointer (assuming you have a very good reason to not have your object created on stack). Return codes are more verbose They are verbose, and tend to develop into something like: if(doSomething()){ if(doSomethingElse()) { if(doSomethingElseAgain()) { // etc. } else { // react to failure of doSomethingElseAgain } } else { // react to failure of doSomethingElse }}else{ // react to failure of doSomething} In the end, you code is a collection of idented instructions (I saw this kind of code in production code). This code could well be translated into: try{ doSomething() ; doSomethingElse() ; doSomethingElseAgain() ;}catch(const SomethingException & e){ // react to failure of doSomething}catch(const SomethingElseException & e){ // react to failure of doSomethingElse}catch(const SomethingElseAgainException & e){ // react to failure of doSomethingElseAgain} Which cleanly separate code and error processing, which can be a good thing. Return codes are more brittle If not some obscure warning from one compiler (see "phjr" 's comment), they can easily be ignored. With the above examples, assume than someone forgets to handle its possible error (this happens...). The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception. The error won't be ignored. Sometimes, you want it to not explode, though... So you must chose carefully. Return Codes must sometimes be translated Let's say we have the following functions: doSomething, which can return an int called NOT_FOUND_ERROR doSomethingElse, which can return a bool "false" (for failed) doSomethingElseAgain, which can return an Error object (with both the __LINE__, __FILE__ and half the stack variables. doTryToDoSomethingWithAllThisMess which, well... Use the above functions, and return an error code of type... What is the type of the return of doTryToDoSomethingWithAllThisMess if one of its called functions fail ? Return Codes are not a universal solution Operators cannot return an error code. C++ constructors can't, too. Return Codes means you can't chain expressions The corollary of the above point. What if I want to write: CMyType o = add(a, multiply(b, c)) ; I can't, because the return value is already used (and sometimes, it can't be changed). So the return value becomes the first parameter, sent as a reference... Or not. Exception are typed You can send different classes for each kind of exception. Ressources exceptions (i.e. out of memory) should be light, but anything else could be as heavy as necessary (I like the Java Exception giving me the whole stack). Each catch can then be specialized. Don't ever use catch(...) without re-throwing Usually, you should not hide an error. If you do not re-throw, at the very least, log the error in a file, open a messagebox, whatever... Exception are... NUKE The problem with exception is that overusing them will produce code full of try/catches. But the problem is elsewhere: Who try/catch his/her code using STL container? Still, those containers can send an exception. Of course, in C++, don't ever let an exception exit a destructor. Exception are... synchronous Be sure to catch them before they bring out your thread on its knees, or propagate inside your Windows message loop. The solution could be mixing them? So I guess the solution is to throw when something should not happen. And when something can happen, then use a return code or a parameter to enable to user to react to it. So, the only question is "what is something that should not happen?" It depends on the contract of your function. If the function accepts a pointer, but specifies the pointer must be non-NULL, then it is ok to throw an exception when the user sends a NULL pointer (the question being, in C++, when didn't the function author use references instead of pointers, but...) Another solution would be to show the error Sometimes, your problem is that you don't want errors. Using exceptions or error return codes are cool, but... You want to know about it. In my job, we use a kind of "Assert". It will, depending on the values of a configuration file, no matter the debug/release compile options: log the error open a messagebox with a "Hey, you have a problem" open a messagebox with a "Hey, you have a problem, do you want to debug" In both development and testing, this enable the user to pinpoint the problem exactly when it is detected, and not after (when some code cares about the return value, or inside a catch). It is easy to add to legacy code. For example: void doSomething(CMyObject * p, int iRandomData){ // etc.} leads a kind of code similar to: void doSomething(CMyObject * p, int iRandomData){ if(iRandomData < 32) { MY_RAISE_ERROR("Hey, iRandomData " << iRandomData << " is lesser than 32. Aborting processing") ; return ; } if(p == NULL) { MY_RAISE_ERROR("Hey, p is NULL !\niRandomData is equal to " << iRandomData << ". Will throw.") ; throw std::some_exception() ; } if(! p.is Ok()) { MY_RAISE_ERROR("Hey, p is NOT Ok!\np is equal to " << p->toString() << ". Will try to continue anyway") ; } // etc.} (I have similar macros that are active only on debug). Note that on production, the configuration file does not exist, so the client never sees the result of this macro... But it is easy to activate it when needed. Conclusion When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough. When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen". But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible". The macro I spoke above follow this philosophy.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/99683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ] }
99,688
One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes. I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc. Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?
It depends. This is one of those issues that must be decided pragmatically. Suppose I had a class for representing a point. I could have getters and setters for the X and Y coordinates, or I could just make them both public and allow free read/write access to the data. In my opinion, this is OK because the class is acting like a glorified struct - a data collection with maybe some useful functions attached. However, there are plenty of circumstances where you do not want to provide full access to your internal data and rely on the methods provided by the class to interact with the object. An example would be an HTTP request and response. In this case it's a bad idea to allow anybody to send anything over the wire - it must be processed and formatted by the class methods. In this case, the class is conceived of as an actual object and not a simple data store. It really comes down to whether or not verbs (methods) drive the structure or if the data does.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18210/" ] }
99,732
Using reflection in .Net, what is the differnce between: if (foo.IsAssignableFrom(typeof(IBar))) And if (foo.GetInterface(typeof(IBar).FullName) != null) Which is more appropriate, why? When could one or the other fail?
If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faster since IsAssignableFrom() does more internal checks than GetInterface(). It'll probably even faster to check the results of Type.GetInterfaces() which returns the same internal list that both of the other methods use anyway.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ] }
99,796
I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this: | BSP | Quadtree | Octree------------+----------------+-------Situation A | X | |Situation B | | X |Situation C | | | X What are A, B, and C?
There is no clear answer to your question. It depends entirely how your data is organized. Something to keep in mind: Quadtrees work best for data that is mostly two dimensional like map-rendering in navigation systems. In this case it's faster than octrees because it adapts better to the geometry and keeps the node-structures small. Octrees and BVHs (Bounding Volume Hierarchies) benefit if the data is three dimensional. It also works very well if your geometric entities are clustered in 3D space. (see Octree vs BVH ) (archived from original ) The benefit of Oc- and Quadtrees is that you can stop generating trees anytime you wish. If you want to render graphics using a graphic accelerator it allows you to just generate trees on an object level and send each object in a single draw-call to the graphics API. This performs much better than sending individual triangles (something you have to do if you use BSP-Trees to the full extent). BSP-Trees are a special case really. They work very very well in 2D and 3D, but generating good BSP-Trees is an art form on its own. BSP-Trees have the drawback that you may have to split your geometry into smaller pieces. This can increase the overall polygon-count of your data-set. They are nice for rendering, but they are much better for collision detection and ray-tracing. A nice property of the BSP-trees is that they decompose a polygon-soup into a structure that can be perfectly rendered back to front (and vice versa) from any camera position without doing an actual sort. The order from each viewpoint is part of the data-structure and done during BSP-Tree compilation. That, by the way, is the reason why they were so popular 10 years ago. Quake used them because it allowed the graphic engine / software rasterizer to not use a costly z-buffer. All the trees mentioned are just families of trees. There are loose octrees, kd-trees hybrid-trees and lots of other related structures as well.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/99796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ] }
99,807
Macs are renowned (or bemoaned) for having an extensive number of shortcuts. However, OS X itself pales in comparison to the shortcut lists in TextMate and its bundles. What are some useful keyboard shortcuts you use?
These are my favorite shortcuts: cmd + t Start typing name of a file to open it ctrl + w Select word cmd + r Run the ruby or php-script that is open cmd + opt + m Define a new macro cmd + shift + m Run the macro opt Switch to vertical selection mode cmd + opt + a Edit ends of selected lines
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167846/" ] }
99,827
I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code... exec sp_executesql N'SELECT [t0].[CustomerID]FROM [dbo].[Customers] AS [t0]WHERE [t0].[ContactName] LIKE @p0ORDER BY [t0].[CompanyName]','N'@p0 nvarchar(2)',@p0=N'c%' ...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable. Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing. var customers = from c in context.Customers where c.CompanyName.StartsWith("c") orderby c.CompanyName select c.CustomerID;foreach (var CustomerID in customers.TagWith("CustomerList4")){ Console.WriteLine(CustomerID);} If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.
These are my favorite shortcuts: cmd + t Start typing name of a file to open it ctrl + w Select word cmd + r Run the ruby or php-script that is open cmd + opt + m Define a new macro cmd + shift + m Run the macro opt Switch to vertical selection mode cmd + opt + a Edit ends of selected lines
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360388/" ] }
99,866
I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective? A couple things that we've seen/heard already include: Google not being able to index content CSS and styling in general seems to be a bit flaky Looking for any additional feedback on these items as well. Thanks!
I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome: Problem: Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute. Solution: Split your code into separate modules, and tell ant to only build it when it's changed. Also while developing, you can massively speed up compile times by only building for one browser. You can do this by putting this into your .gwt.xml file: <set-property name="user.agent" value="gecko1_8" /> Where gecko1_8 is Firefox 2+, ie6 is IE, etc. Problem: Hosted mode is very slow (on OS X at least) and does not come close to matching the 'live' changes you get when you edit things like JSPs or Rails pages and hit refresh in your browser. Solution: You can give the hosted mode more memory (I generally got for 512M) but it's still slow, I've found once you get good enough with GWT you stop using this. You make a large chunk of changes, then compile for just one browser (generally 20s worth of compile) and then just hit refresh in your browser. Update: With GWT 2.0+ this is no longer an issue, because you use the new 'Development Mode'. It basically means you can run code directly in your browser of choice, so no loss of speed, plus you can firebug/inspect it, etc. http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM Problem: GWT code is java, and has a different mentality to laying out a HTML page, which makes taking a HTML design and turning it into GWT harder Solution: Again you get used to this, but unfortunately converting a HTML design to a GWT design is always going to be slower than doing something like converting a HTML design to a JSP page. Problem: GWT takes a bit of getting your head around, and is not yet mainstream. Meaning that most developers that join your team or maintain your code will have to learn it from scratch Solution: It remains to be seen if GWT will take off, but if you're a company in control of who you hire, then you can always choose people that either know GWT or want to learn it. Problem: GWT is a sledgehammer compared to something like jquery or just plain javascript. It takes a lot more setup to get it happening than just including a JS file. Solution: Use libraries like jquery for smaller, simple tasks that are suited to those. Use GWT when you want to build something truly complex in AJAX, or where you need to pass your data back and forth via the RPC mechanism. Problem: Sometimes in order to populate your GWT page, you need to make a server call when the page first loads. It can be annoying for the user to sit there and watch a loading symbol while you fetch the data you need. Solution: In the case of a JSP page, your page was already rendered by the server before becoming HTML, so you can actually make all your GWT calls then, and pre-load them onto the page, for an instant load. See here for details: Speed up Page Loading by pre-serializing your GWT calls I've never had any problems CSS styling my widgets, out of the box, custom or otherwise, so I don't know what you mean by that being a pitfall? As for performance, I've always found that once compiled GWT code is fast, and AJAX calls are nearly always smaller than doing a whole page refresh, but that's not really unique to GWT, though the native RPC packets that you get if you use a JAVA back end are pretty compact.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/99866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18402/" ] }
99,876
I just wanted some opinions from people that have run Selenium ( http://selenium.openqa.org ) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it. If you have run selenium have you had a lot of success? I will be using .NET 3.5, does Selenium work well with it? Is the code produced clean or simply a list of all the interaction? ( http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx ) How well does the distributed testing suite fair? Any other gripes or compliments on the system would be greatly appreciated!
If you are using Selenium IDE to generate code, then you just get a list of every action that selenium will execute. To me, Selenium IDE is a good way to start or do a fast "try and see" test. But, when you think about maintainability and more readable code, you must write your own code. A good way to achieve good selenium code is to use the Page Object Pattern in a way that the code represents your navigation flow. Here is a good example that I see in Coding Dojo Floripa (from Brazil): public class GoogleTest { private Selenium selenium; @Before public void setUp() throws Exception { selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com/webhp?hl=en"); selenium.start(); } @Test public void codingDojoShouldBeInFirstPageOfResults() { GoogleHomePage home = new GoogleHomePage(selenium); GoogleSearchResults searchResults = home.searchFor("coding dojo"); String firstEntry = searchResults.getResult(0); assertEquals("Coding Dojo Wiki: FrontPage", firstEntry); } @After public void tearDown() throws Exception { selenium.stop(); }}public class GoogleHomePage { private final Selenium selenium; public GoogleHomePage(Selenium selenium) { this.selenium = selenium; this.selenium.open("http://www.google.com/webhp?hl=en"); if (!"Google".equals(selenium.getTitle())) { throw new IllegalStateException("Not the Google Home Page"); } } public GoogleSearchResults searchFor(String string) { selenium.type("q", string); selenium.click("btnG"); selenium.waitForPageToLoad("5000"); return new GoogleSearchResults(string, selenium); }}public class GoogleSearchResults { private final Selenium selenium; public GoogleSearchResults(String string, Selenium selenium) { this.selenium = selenium; if (!(string + " - Google Search").equals(selenium.getTitle())) { throw new IllegalStateException( "This is not the Google Results Page"); } } public String getResult(int i) { String nameXPath = "xpath=id('res')/div[1]/div[" + (i + 1) + "]/h2/a"; return selenium.getText(nameXPath); }} Hope that Helps
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ] }
99,880
I need to write a function that generates an id that is unique for a given machine running a Windows OS. Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use? Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric. However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen. For reference, these are the metrics I'm currently using: Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeedWin32_BIOS:ManufacturerWin32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,VersionWin32_DiskDrive:Model, Manufacturer, Signature, TotalHeadsWin32_BaseBoard:Model, Manufacturer, Name, SerialNumberWin32_VideoController:DriverVersion, Name
Parse the SMBIOS yourself and hash it to an arbitrary length. See the PDF specification for all SMBIOS structures available. To query the SMBIOS info from Windows you could use EnumSystemFirmwareEntries , EnumSystemFirmwareTables and GetSystemFirmwareTable . IIRC, the "unique id" from the CPUID instruction is deprecated from P3 and newer.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618/" ] }
99,927
Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures?
Global variables Every variable in Javascript is a named attribute of an object. For example:- var x = 1; x is added to the global object. The global object is provided by the script context and may already have a set of attributes. For example in a browser the global object is window. An equivalent to the above line in a browser would be:- window.x = 1; Local variables Now what if we change this to:- function fn(){ var x = 1;} When fn is called a new object is created called the execution context also referred to as the scope (I use these terms interchangeably). x is added as an attribute to this scope object. Hence each call to fn will get its own instance of a scope object and therefore its own instance of the x attribute attached to that scope object. Closure Now lets take this further:- function fnSequence(){ var x = 1; return function() { return x++; }}var fn1 = fnSequence();var fn2 = fnSequence();WScript.Echo(fn1())WScript.Echo(fn2())WScript.Echo(fn1())WScript.Echo(fn2())WScript.Echo(fn1())WScript.Echo(fn1())WScript.Echo(fn2())WScript.Echo(fn2()) Note: Replace WScript.Echo with whatever writes to stdout in your context. The sequence you should get is :- 1 1 2 2 3 4 3 4 So what has happened here? We have fnSequence which initialises a variable x to 1 and returns an anonymous function which will return the value of x and then increment it. When this function is first executed a scope object is created and an attribute x is added to that scope object with the value of 1. Also created in the same execution object is an anonymous function. Each function object will have a scope attribute which points to the execution context in which it is created. This creates what is know as a scope chain which we will come to later. A reference to this function is returned by fnSequence and stored in fn1 . Note that fn1 is now pointing at the anonymous function and that the anonymous function has a scope attribute pointing at a scope object that still has an x attribute attached. This is known as closure where the contents of an execution context is still reachable after the function it was created for has completed execution. Now this same sequence happens when assigning to fn2 . fn2 will be pointing at a different anonymous function that was created in a different execution context that was create when fnSequence was called this second time. Scope Chain What happens when the function held by fn1 is executed the first time? A new execution context is created for the execution of the anonymous function. A return value is to be found from the identifier x . The function's scope object is inspected for an x attribute but none is found. This is where the scope chain comes in. Having failed to find x in the current execution context JavaScript takes the object held by the function's scope attribute and looks for x there. It finds it since the functions scope was created inside an execution of fnSequence , retrieves its value and increments it. Hence 1 is output and the x in this scope is incremented to 2. Now when fn2 is executed it is ultimately attached to a different execution context whose x attribute is still 1. Hence executing fn2 also results in 1. As you can see fn1 and fn2 each generate their own independent sequence of numbers.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/99927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56663/" ] }
99,934
I'm looking for recommendations for a good program for 32-bit Windows Vista that will load any arbitrary binary file and display textual information or graphical visualization relevant to identifying what actual data the bits are supposed to represent. Is ther anything better than a hex editor for this kind of thing? One thing I'd like to do is say, look at the non-visible data in a Spore PNG file to get a clue as to what's actually being stored in there. Right now I'm using WordPad and all I get is something that looks like this: ‰PNG IHDR ¢ /Qã!$D4"Ž‚îvÚ°‰ÅØÃ ïjÃÞÉ_{!…‡ú 9¥Ý´îÁ6 ‰ms ^ I guess what I'm looking for is a souped up hex editor that acts more like an Excel for bits so I can slice and dice statistical patterns to get a better idea of what the bits might be doing.
Try HxD : HxD is a carefully designed and fast hex editor which, additionally to raw disk editing and modifying of main memory (RAM), handles files of any size. The easy to use interface offers features such as searching and replacing, exporting, checksums/digests, insertion of byte patterns, a file shredder, concatenation or splitting of files, statistics and much more.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/99934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ] }
100,003
What are metaclasses? What are they used for?
A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass. While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the better approach is to make it an actual class itself. type is the usual metaclass in Python. type is itself a class, and it is its own type. You won't be able to recreate something like type purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass type . A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal __init__ and __new__ methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely. When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it. However, metaclasses actually define the type of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. type.__subclasses__() is an example of a method on the type metaclass. You can also define the normal 'magic' methods, like __add__ , __iter__ and __getattr__ , to implement or change how the class behaves. Here's an aggregated example of the bits and pieces: def make_hook(f): """Decorator to turn 'foo' method into '__foo__'""" f.is_hook = 1 return fclass MyType(type): def __new__(mcls, name, bases, attrs): if name.startswith('None'): return None # Go over attributes and see if they should be renamed. newattrs = {} for attrname, attrvalue in attrs.iteritems(): if getattr(attrvalue, 'is_hook', 0): newattrs['__%s__' % attrname] = attrvalue else: newattrs[attrname] = attrvalue return super(MyType, mcls).__new__(mcls, name, bases, newattrs) def __init__(self, name, bases, attrs): super(MyType, self).__init__(name, bases, attrs) # classregistry.register(self, self.interfaces) print "Would register class %s now." % self def __add__(self, other): class AutoClass(self, other): pass return AutoClass # Alternatively, to autogenerate the classname as well as the class: # return type(self.__name__ + other.__name__, (self, other), {}) def unregister(self): # classregistry.unregister(self) print "Would unregister class %s now." % selfclass MyObject: __metaclass__ = MyTypeclass NoneSample(MyObject): pass# Will print "NoneType None"print type(NoneSample), repr(NoneSample)class Example(MyObject): def __init__(self, value): self.value = value @make_hook def add(self, other): return self.__class__(self.value + other.value)# Will unregister the classExample.unregister()inst = Example(10)# Will fail with an AttributeError#inst.unregister()print inst + instclass Sibling(MyObject): passExampleSibling = Example + Sibling# ExampleSibling is now a subclass of both Example and Sibling (with no# content of its own) although it will believe it's called 'AutoClass'print ExampleSiblingprint ExampleSibling.__mro__
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/100003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ] }
100,045
What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have \/:*?"<>| characters). I'd like to use it like the following: // Return true if string is invalid.if (Regex.IsMatch(szFileName, "<your regex string>")){ // Tell user to reformat their filename.}
As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions: if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1){ MessageBox.Show("The filename is invalid"); return;}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/100045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13115/" ] }
100,048
I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique. The elements can occur multiple times in both lists and they are originally unsorted. My function looks like this: (defun merge-lists (list-a list-b sort-fn) "Merges two lists of (x, y) coordinates sorting them and removing dupes" (let ((prev nil)) (remove-if (lambda (point) (let ((ret-val (equal point prev))) (setf prev point) ret-val)) (sort (merge 'list list-a list-b sort-fn) ;' sort-fn)))) Is there a better way to achieve the same? Sample call: [CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>) ==> (9 8 7 6 4 3 2 1)
Our neighbourhood friendly Lisp guru pointed out the remove-duplicates function . He also provided the following snippet: (defun merge-lists (list-a list-b sort-fn test-fn) (sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ] }
100,068
I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills. Here's what I've got, but it seems like there should be an easier way. public static TEntity InsertIfNotExists<TEntity>( DataContext db, Table<TEntity> table, Func<TEntity,bool> where, TEntity record) where TEntity : class{ TEntity existing = table.SingleOrDefault<TEntity>(where); if (existing != null) { return existing; } else { table.InsertOnSubmit(record); // Can't use table.Context.SubmitChanges() // 'cause it's read-only db.SubmitChanges(); } return record;}
public static void InsertIfNotExists<TEntity> (this Table<TEntity> table, TEntity entity, Expression<Func<TEntity,bool>> predicate) where TEntity : class{ if (!table.Any(predicate)) { table.InsertOnSubmit(record); table.Context.SubmitChanges(); } }table.InsertIfNotExists(entity, e=>e.BooleanProperty);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ] }
100,106
sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%@{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{$_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]} update: I thought the word "puzzle" would imply this, but: I know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it.
Here is how you figure out how to de-obfuscate this subroutine. Sorry for the length First let's tidy up the code, and add useful comments. sub foo { [ ( # ($#{$_[1]}) $#{ $_[ ! ( $| | $| ) # $OUTPUT_AUTOFLUSH === $| # $| is usually 0 # ! ( $| | $| ) # ! ( 0 | 0 ) # ! ( 0 ) # 1 ] } * # @{$_[1]} @{ $_[ !!$_ ^ !$_ # !! 1 ^ ! 1 # ! 0 ^ 0 # 1 ^ 0 # 1 # !! 0 ^ ! 0 # ! 1 ^ 1 # 0 ^ 1 # 1 ] } ) ? # @{$_[1]} @{ $_[ !$. . !!$. # $INPUT_LINE_NUMBER === $. # $. starts at 1 # !$. . !!$. # ! 1 . !! 1 # 0 . ! 0 # 0 . 1 # 01 ] } [ # $_[0] $_[ # @LAST_MATCH_START - @LAST_MATCH_END # 0 @- - @+ ] % # @{$_[1]} @{ $_[ $= =~ /(?=)/ / !$` #( fix highlighting )`/ # $= is usually 60 # /(?=)/ will match, returns 1 # $` will be '' # 1 / ! '' # 1 / ! 0 # 1 / 1 # 1 ] } .. # $#{$_[1]} $#{ $_[ $? ? !!$? : !$? # $CHILD_ERROR === $? # $? ? !!$? : !$? # 0 ? !! 0 : ! 0 # 0 ? 0 : 1 # 1 # 1 ? !! 1 : ! 1 # 1 ? 1 : 0 # 1 ] } , # ( 0 ) ( $) ? !$) : !!$) # $EFFECTIVE_GROUP_ID === $) # $) ? !$) : !!$) # 0 ? ! 0 : !! 0 # 0 ? 1 : 0 # 0 # 1 ? ! 1 : !! 1 # 1 ? 0 : 1 # 0 ) .. # $_[0] $_[ $- - $- # 0 # $LAST_PAREN_MATCH = $- # 1 - 1 == 0 # 5 - 5 == 0 ] % # @{$_[1]} @{ $_[ $] / $] # $] === The version + patchlevel / 1000 of the Perl interpreter. # 1 / 1 == 1 # 5 / 5 == 1 ] } - # ( 1 ) ( !!$+ + !$+ # !! 1 + ! 1 # ! 0 + 0 # 1 + 0 # 1 ) ] : # @{$_[1]} @{ $_[ !!$^^ ^ !$^^ # !! 1 ^ ! 1 # ! 0 ^ 0 # 1 ^ 0 # 1 # !! 0 ^ ! 0 # ! 1 ^ 1 # 0 ^ 1 # 1 ] } ]} Now let's remove some of the obfuscation. sub foo{ [ ( $#{$_[1]} * @{$_[1]} ) ? @{$_[1]}[ ( $_[0] % @{$_[1]} ) .. $#{$_[1]} , 0 .. ( $_[0] % @{$_[1]} - 1 ) ] : @{$_[1]} ]} Now that we have some idea of what is going on, let's name the variables. sub foo{ my( $item_0, $arr_1 ) = @_; my $len_1 = @$arr_1; [ # This essentially just checks that the length of $arr_1 is greater than 1 ( ( $len_1 -1 ) * $len_1 ) # ( ( $len_1 -1 ) * $len_1 ) # ( ( 5 -1 ) * 5 ) # 4 * 5 # 20 # 20 ? 1 : 0 == 1 # ( ( $len_1 -1 ) * $len_1 ) # ( ( 2 -1 ) * 2 ) # 1 * 2 # 2 # 2 ? 1 : 0 == 1 # ( ( $len_1 -1 ) * $len_1 ) # ( ( 1 -1 ) * 1 ) # 0 * 1 # 0 # 0 ? 1 : 0 == 0 # ( ( $len_1 -1 ) * $len_1 ) # ( ( 0 -1 ) * 0 ) # -1 * 0 # 0 # 0 ? 1 : 0 == 0 ? @{$arr_1}[ ( $item_0 % $len_1 ) .. ( $len_1 -1 ), 0 .. ( $item_0 % $len_1 - 1 ) ] : # If we get here, @$arr_1 is either empty or has only one element @$arr_1 ]} Let's refactor the code to make it a little bit more readable. sub foo{ my( $item_0, $arr_1 ) = @_; my $len_1 = @$arr_1; if( $len_1 > 1 ){ return [ @{$arr_1}[ ( $item_0 % $len_1 ) .. ( $len_1 -1 ), 0 .. ( $item_0 % $len_1 - 1 ) ] ]; }elsif( $len_1 ){ return [ @$arr_1 ]; }else{ return []; }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17389/" ] }
100,107
I'm investigating the following java.lang.VerifyError java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴MtÌ´MÚw€mçw€mp:”MŒŒ at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357) at java.lang.Class.getConstructor0(Class.java:2671) It occurs when the jboss server in which the servlet is deployed is started.It is compiled with jdk-1.5.0_11 and I tried to recompile it with jdk-1.5.0_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs. When I changed the method name and got the following error: java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources┬á├ÿ├àN|├ÿ├àN├Üw┬Çm├ºw┬ÇmX#├ûM|X├öM at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357 at java.lang.Class.getConstructor0(Class.java:2671) at java.lang.Class.newInstance0(Class.java:321) at java.lang.Class.newInstance(Class.java:303) You can see that more of the method signature is shown. The actual method signature is private PgasePdfTable getMonthData(int month, int year, Collection dayTypes, Collection calendarDays, HashMap bcSpecialDays, Collection activityPeriods, Locale locale, MessageResources resources) throws Exception { I already tried looking at it with javap and that gives the method signature as it should be. When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup. The rest of the application runs okay, only that one servlet is out of order.Any ideas where to look would be helpful.
java.lang.VerifyError can be the result when you have compiled against a different library than you are using at runtime. For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in org.apache.* namespace) were found at runtime, so ClassNotFoundException was not the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time. Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws VerifyError when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns String and then stores that return value in a field that holds a List .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/100107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15490/" ] }
100,123
I would like to create an application wide keyboard shortcut for a Java Swing application.Looping over all components and adding the shortcut on each, has focus related side effects, and seems like a brute force solution. Anyone has a cleaner solution?
Install a custom KeyEventDispatcher. The KeyboardFocusManager class is also a good place for this functionality. KeyEventDispatcher
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18591/" ] }
100,170
I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast. What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple. Is there a way to check if there are any symlinks pointing to a particular folder?
I'd use the find command. find . -lname /particular/folder That will recursively search the current directory for symlinks to /particular/folder . Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called "folder": find . -lname '*folder' From there you would need to weed out any false positives.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/100170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ] }
100,196
What is the difference between the AddRange and Concat functions on a generic List? Is one recommended over the other?
They have totally different semantics. AddRange modifies the list by adding the other items to it. Concat returns a new sequence containing the list and the other items, without modifying the list. Choose whichever one has the semantics you want.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/100196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ] }
100,210
Given a datetime.time value in Python, is there a standard way to add an integer number of seconds to it, so that 11:34:59 + 3 = 11:35:02 , for example? These obvious ideas don't work: >>> datetime.time(11, 34, 59) + 3TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time' In the end I have written functions like this: def add_secs_to_time(timeval, secs_to_add): secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second secs += secs_to_add return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60) I can't help thinking that I'm missing an easier way to do this though. Related python time + timedelta equivalent
You can use full datetime variables with timedelta , and by providing a dummy date then using time to just get the time value. For example: import datetimea = datetime.datetime(100,1,1,11,34,59)b = a + datetime.timedelta(0,3) # days, seconds, then other fields.print(a.time())print(b.time()) results in the two values, three seconds apart: 11:34:5911:35:02 You could also opt for the more readable b = a + datetime.timedelta(seconds=3) if you're so inclined. If you're after a function that can do this, you can look into using addSecs below: import datetimedef addSecs(tm, secs): fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second) fulldate = fulldate + datetime.timedelta(seconds=secs) return fulldate.time()a = datetime.datetime.now().time()b = addSecs(a, 300)print(a)print(b) This outputs: 09:11:55.775695 09:16:55
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/100210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5536/" ] }
100,228
I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements must be present, and there could be more than one of them. I tried doing the following, but XMLSpy complains that "The content model contains the elements <element name="DateConstant"> and <element name="DateConstant"> which cannot be uniquely determined.": <xs:choice> <xs:sequence> <xs:element name="DateConstant"/> <xs:element name="TimeConstant"/> </xs:sequence> <xs:element name="DateConstant"/> <xs:element name="TimeConstant"/> </xs:choice> Can this be done (and if so, how)? Some clarification:I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either.Gizmo's answer matches my requirements, but it's impractical for a larger number of elements.Hurst's answer allows two or more elements of the same name, which I don't want.
Try this: <xs:choice> <xs:sequence> <xs:element name="Elem1" /> <xs:element name="Elem2" minOccurs="0" /> <xs:element name="Elem3" minOccurs="0" /> </xs:sequence> <xs:sequence> <xs:element name="Elem2" /> <xs:element name="Elem3" minOccurs="0" /> </xs:sequence> <xs:element name="Elem3" /></xs:choice> Doing so, you force either to choose the first element and then the rest is optional, either the second element and the rest is optional, either the third element. This should do what you want, I hope. Of course, you could place the sub-sequences into groups, to avoid to duplicate an element in each sequence if you realize you miss one.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18603/" ] }
100,235
For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A FileWatcher is not required but it could be useful. class PersistentDictionary<T,V> : IDictionary<T,V>{ public PersistentDictionary(string filename) { } } Requirements: Open Source, with no dependency on native code (no sqlite) Ideally a very short and simple implementation When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value. Similar Questions Persistent Binary Tree / Hash table in .Net Disk backed dictionary/cache for c# PersistentDictionary<Key,Value>
bplustreedotnet The bplusdotnet package is a library of cross compatible data structure implementations in C#, java, and Python which are useful for applications which need to store and retrieve persistent information. The bplusdotnet data structures make it easy to store string keys associated with values permanently . ESENT Managed Interface Not 100% managed code but it's worth mentioning it as unmanaged library itself is already part of every windows XP/2003/Vista/7 box ESENT is an embeddable database storage engine (ISAM) which is part of Windows. It provides reliable, transacted, concurrent, high-performance data storage with row-level locking, write-ahead logging and snapshot isolation. This is a managed wrapper for the ESENT Win32 API. Akavache *Akavache is an asynchronous, persistent key-value cache created for writing native desktop and mobile applications in C#. Think of it like memcached for desktop apps. - The C5 Generic Collection Library C5 provides functionality and data structures not provided by the standard .Net System.Collections.Generic namespace, such as persistent tree data structures , heap based priority queues, hash indexed array lists and linked lists, and events on collection changes.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ] }
100,243
My developers are waging a civil war. In one camp, they've embraced Hibernate and Spring. In the other camp, they've denounced frameworks - they're considering Hibernate though. The question is: Are there any nasty surprises, weaknesses or pit-falls that newbie Hibernate-Spring converts are likely to stumble on? PS: We've a DAO library that's not very sophisticated. I doubt that it has Hibernate's richness, but it's reaching some sort of maturity (i.e. it's not been changed in the last few projects it's included).
I've used Hibernate a number of times in the past. Each time I've run into edge cases where determining the syntax devolved into a scavenger hunt through the documentation, Google, and old versions. It is a powerful tool but poorly documented (last I looked). As for Spring, just about every job I've interviewed for or looked at in the past few years involved Spring, it's really become the de-facto standard for Java/web. Using it will help your developers be more marketable in the future, and it'll help you as you'll have a large pool of people who'll understand your application. Writing your own framework is tempting, educational, and fun. Not so great on results.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428965/" ] }
100,247
I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels. What assembly and/or class should I use?
Bitmap class from System.Drawing.dll assembly: Bitmap bitmap = new Bitmap(@"C:\image.png");Color clr = bitmap.GetPixel(0, 0);
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18494/" ] }
100,248
AFAIK one of the objectives of Stack Overflow is to make sure anyone can come here and find good answers to her Perl related questions. Certainly beginners would ask what is the best online source to learn Perl but others might just want to ask a question. Probably the friendliest place is the Monastery of Perl Monks . It is a web site with a rating system similar to but more simple than Stack Overflow. You can find lots of good answers there and if you don't find an answer you can always ask. The other big resource would be the mailing list of your local Perl Mongers group. Where do you go when you are looking for an answer to a Perl related question?
It's worth noting that http://perlmonks.org , in addition to the fora, has the Chatterbox, where simple questions can be answered immediately in conversation with other users. It requires setting up an account and logging in before using the Chatterbox , though.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11827/" ] }
100,280
Has any one done this before? It would seem to me that there should be a webservice but i can't find one. I am writing an application for personal use that would just show basic info from IMDB.
There is no webservice available. But there are enough html scrapers written in every language to suit your needs! I've used the .NET 3.5 Imdb Services opensource project in a few personal projects. 1 minute google results: Perl: IMDB-Film Ruby: libimdb-ruby Python: IMDbPY
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5235/" ] }
100,284
I'm using the .NET TWAIN code from http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx in my application. When I try to scan an image when the scanner is not plugged in, the application freezes. How can I check if the device is plugged in, using the TWAIN driver?
Maybe I'm taking the question too literally, but using the TWAIN API, it is not possible to check if a device is plugged in i.e. connected and powered on. The TWAIN standard does define a capability for this purpose called CAP_DEVICEONLINE, but this feature is so poorly conceived and so few drivers implement it correctly that it is useless in practice. The closest you can get is this: Open the device (MSG_OPENDS): Almost all drivers will check for device-ready when they are opened, and will display an error dialog to the user. There is no TWAIN mechanism for suppressing or detecting this dialog Some drivers will allow the user to correct the problem and continue, in which case you (your app) will never know there was a problem. Some drivers will allow the user to cancel, in which case the MSG_OPENDS operation will fail, probably returning TWRC_CANCEL but maybe TWRC_FAILURE A few TWAIN drivers will open without error even though the device is off-line. Such a driver may return FALSE to a query of CAP_DEVICEONLINE. Such a driver will probably do the device-online check when you enable the device with MSG_ENABLEDS, and then if the device is not on-line, you get the error dialog to the user, and so on as above. Aside and IMPO: WIA is 'more modern' but also much less comprehensive for scanning than TWAIN, and in my experience unusable for multipage scanning from a document feeder. WIA's designers and maintainers seem not to understand or care about scanners other than low-end consumer flatbeds. It's good for cameras.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ] }
100,291
Imagine I have an function which goes through one million/billion strings and checks smth in them. f.ex: foreach (String item in ListOfStrings){ result.add(CalculateSmth(item));} it consumes lot's of time, because CalculateSmth is very time consuming function. I want to ask: how to integrate multithreading in this kinda process? f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items. Maybe anyone can show some examples or articles.. Forgot to mention I need it in .NET 2.0
You could try the Parallel extensions (part of .NET 4.0) These allow you to write something like: Parallel.Foreach (ListOfStrings, (item) => result.add(CalculateSmth(item));); Of course result.add would need to be thread safe.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5369/" ] }
100,298
I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed. Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like static analysis to spot suspicious (and thus likely erroneous) constructs. How might I go about constructing such a report?
For measuring cyclomatic complexity, there's a nice tool available at traceback.org . The page also gives a good overview of how to interpret the results. +1 for pylint . It is great at verifying adherence to coding standards (be it PEP8 or your own organization's variant), which can in the end help to reduce cyclomatic complexity.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14648/" ] }
100,376
Anyone know how to do picture overlay or appear on top of each other in HTML? The effect will be something like the marker/icon appear on Google Map where the user can specify the coordinate of the second picture appear on the first picture. Thanks.
You can use <div> containers to seperate content into multiple layers. Therefore the div containers have to be positioned absolutely and marked with a z-index. for instance: <div style="position: absolute; z-index:100">This is in background</div> <div style="position: absolute; z-index:5000">This is in foreground</div> Of course the content also can contains images, etc.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14790/" ] }
100,388
I would like to automatically convert between tabs and spaces for indentation when I commit/update code to/from our repository. I have found the AnyEdit plugin for eclipse, which can convert directories of files. Not bad for a start, but does anybody have more expierience on how to handle this? Or maybe know of an Ant script or something else?
Why not just use the code formatter and/or cleanup function? It has settings that take care of that stuff for you. You can even have it run automatically on save. Edit: As Peter Perháč points out in the comments, this only answers half the question. I don't have any practical experience, but you could try the Maven Eclipse Format Plugin to format from a Maven build. Unfortunately, that's Maven only, and I know of no light-weight command line formatter. But if you happen to use Maven, you can bind the format goal to the proper phase, and if you set Eclipse to auto-build, it would format on update. Depending on the SCM tool (git, svn, etc), you could also create a hook that runs the build (but it might be a bit too heavy-weight for that).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5739/" ] }
100,420
Visual Studio is such a massively big product that even after years of working with it I sometimes stumble upon a new/better way to do things or things I didn't even know were possible. For instance- Crtl + R , Ctrl + W to show white spaces. Essential for editing Python build scripts. Under "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor" Create a String called Guides with the value "RGB(255,0,0), 80" to have a red line at column 80 in the text editor. What other hidden features have you stumbled upon?
Make a selection with ALT pressed - selects a square of text instead of whole lines.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/100420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ] }
100,444
I'm trying to automate a gdb session using the --command flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this: set args /home/shlomi/conf/bugs/kde/font-break.txtb IA__FcFontMatchr However, I'm getting the following: shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb...GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0)Copyright (C) 2008 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Type "show copying"and "show warranty" for details.This GDB was configured as "i586-mandriva-linux-gnu"...(no debugging symbols found)Function "IA__FcFontMatch" not defined.Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal] So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load? I recall that I was able to do something, but cannot recall what.
Replying to myself, I'd like to give the answer that someone gave me on IRC: (gdb) apropos pendingactions -- Specify the actions to be taken at a tracepointset breakpoint -- Breakpoint specific settingsset breakpoint pending -- Set debugger's behavior regarding pending breakpointsshow breakpoint -- Breakpoint specific settingsshow breakpoint pending -- Show debugger's behavior regarding pending breakpoints And so set breakpoint pending on does the trick; it is used in cmds.gdb like e.g. set breakpoint pending onbreak <source file name>:<line number>
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/100444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7709/" ] }
100,469
Any good tutorial with source that will demonstrate how to develop neural network (step bay step for dummies ;-))
Here is good example: Brainnet 1 - A Neural Netwok Project - With Illustration And Code - Learn Neural Network Programming Step By Step And Develop a Simple Handwriting Detection System that will demonstrate some practical uses of neural network programming.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
100,504
Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.
MySQL 3 and 4 (and 5): desc tablename which is an alias for show fields from tablename SQL Server (from 2000) and MySQL 5: select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename' Completing the answer: like people below have said, in SQL Server you can also use the stored procedure sp_help exec sp_help 'tablename'
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/100504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856916/" ] }
100,543
On a class library project, I set the "Start Action" on the Debug tab of the project properties to "Start external program" ( NUnit in this case). I want to set an environment variable in the environment this program is started in. How do I do that? (Is it even possible?) EDIT: It's an environment variable that influences all .NET applications (COMplus_Version, it sets the runtime version) so setting it system wide really isn't an option. As a workaround I just forced NUnit to start in right .NET version (2.0) by setting it in nunit.exe.config , though unfortunately this also means all my .NET 1.1 unit tests are now also run in .NET 2.0. I should probably just make a copy of the executable so it can have its own configuration file... (I am keeping the question open (not accepting an answer) in case someone does happen to find out how (it might be useful for other purposes too after all...))
In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings. Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables. For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/100543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ] }
100,596
A rather comprehensive site explaining the difficulties and solutions involved in using a dll written in c/c++ and the conversion of the .h header file to delphi/pascal was posted to a mailing list I was on recently, so I thought I'd share it, and invite others to post other useful resources for this, whether they be links, conversion tools, or book/paper titles. One resource per answer please, so we'll end up with the most popular/best resources bubbling to the top.
Over at Rudy's Delphi Corner , he has an excellent article about the pitfalls of converting C/C++ to Delphi . In my opinion, this is essential information when attempting this task. Here is the description: This article is meant for everyone who needs to translate C/C++ headers to Delphi. I want to share some of the pitfalls you can encounter when converting from C or C++. This article is not a tutorial, just a discussion of frequently encountered problem cases. It is meant for the beginner as well as for the more experienced translator of C and C++. He also wrote a " Conversion Helper Package " that installs into the Delphi IDE which aids in converting C/C++ code to Delphi: (source: rvelthuis.de ) His other relevant articles on this topic include: Using C++ Objects in Delphi Using C object files in Delphi
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11820/" ] }
100,624
How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this almost works for me: proc1 = subprocess.Popen(['python','mytest.py'])proc2 = subprocess.Popen(['python','mytest.py']) proc1.wait()print "1 finished"proc2.wait()print "2 finished" The problem is that when proc2 finishes before proc1 , the parent process will still wait for proc1 . On Unix one would use waitpid(0) in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?
It might seem overkill, but, here it goes: import Queue, thread, subprocessresults= Queue.Queue()def process_waiter(popen, description, que): try: popen.wait() finally: que.put( (description, popen.returncode) )process_count= 0proc1= subprocess.Popen( ['python', 'mytest.py'] )thread.start_new_thread(process_waiter, (proc1, "1 finished", results))process_count+= 1proc2= subprocess.Popen( ['python', 'mytest.py'] )thread.start_new_thread(process_waiter, (proc2, "2 finished", results))process_count+= 1# etcwhile process_count > 0: description, rc= results.get() print "job", description, "ended with rc =", rc process_count-= 1
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12166/" ] }
100,631
After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration. Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets` Restarting the mongrels (not the MySQL server) fixes it. How can we fix this?
This is probably caused by the persistent connections to MySQL going away (time out is likely if it's happening over night) and Ruby on Rails is failing to restore the connection, which it should be doing by default: In the file vendor/rails/actionpack/lib/action_controller/dispatcher.rb is the code: if defined?(ActiveRecord) before_dispatch { ActiveRecord::Base.verify_active_connections! } to_prepare(:activerecord_instantiate_observers) {ActiveRecord::Base.instantiate_observers }end The method verify_active_connections! performs several actions, one of which is to recreate any expired connections. The most likely cause of this error is that this is because a monkey patch has redefined the dispatcher to not call verify_active_connections! , or verify_active_connections! has been changed, etc.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ] }
100,645
Are there any tools available for calculating Cyclomatic Complexity in Javascript? I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write.
I helped write a tool to perform software complexity analysis on JavaScript projects: complexity-report It reports a bunch of different complexity metrics: lines of code, number of parameters, cyclomatic complexity, cyclomatic density, Halstead complexity measures, the maintainability index, first-order density, change cost and core size. It is released under the MIT license and built using Node.js and the Esprima JavaScript parser. It can be installed via npm, like so: npm i -g complexity-report
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2932/" ] }
100,691
We have a large ASP classic code base but I'm looking to do future development in ASP.NET (and potentially in the future port across what we have). The natural choice of language seems to be VB (existing code is VBScript) but am I being too hasty? Does the choice of language, in the long run, even make a difference?
It's learning .Net (framework) that takes the time. The specific language doesn't matter and is more a matter of taste. I'd normally recommend trying a few play projects in both languages (and any others that may take your fancy), and then decide which one you're more comfortable with (or have more success with!)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984/" ] }
100,705
I recently heard of WSDL.Exe, but I am not sure where to find this program.Does anyone know where I can find or download it?
You'll get it as part of a Visual Studio install (if you included the SDK), or in a standalone SDK install. It'll live somewhere like C:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin If you don't already have it, you can download the .NET SDKs from http://msdn.microsoft.com/en-us/netframework/aa569263.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
100,707
I'm wondering, how expensive it is to have many threads in waiting state in java 1.6 x64. To be more specific, I'm writing application which runs across many computers and sends/receives data from one to another. I feel more comfortable to have separate thread for each connected machine and task, like 1) sending data, 2) receiving data, 3) reestablishing connection when it is dropped. So, given that there are N nodes in cluster, each machine is going to have 3 threads for each of N-1 neighbours. Typically there will be 12 machines, which comes to 33 communication threads. Most of those threads will be sleeping most of the time, so for optimization purposes I could reduce number of threads and give more job to each of them. Like, for example. reestablishing connection is responsibility of receiving thread. Or sending to all connected machines is done by single thread. So is there any significant perfomance impact on having many sleeping threads?
For most cases, the resources consumed by a sleeping thread will be its stack space. Using a 2-threads-per-connection-model, which I think is similar to what you're describing, is known to cause great scalability issues for this very reason when the number of connections grow large. I've been in this situation myself, and when the number of connections grew above 500 connections (about a thousand threads), you tend to get into lots of cases where you get OutOfMemoryError, since the threads stack space usage exceeds the maximum amount of memory for a single process. At least in our case, which was in a Java on 32 bit Windows world. You can tune things and get a bit further, I guess, but in the end it's just not very scalable since you waste lots of memory. If you need a large number of connections, Java NIO (new IO or whatever) is the way to go, making it possible to handle lots of connections in the same thread. Having said that, you shouldn't encounter much of a problem with under a 100 threads on a reasonably modern server, even if it's probably still a waste of resources.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ] }
100,732
I've seen several examples of code like this: if not someobj: #do something But I'm wondering why not doing: if someobj == None: #do something Is there any difference? Does one have an advantage over the other?
In the first test, Python try to convert the object to a bool value if it is not already one. Roughly, we are asking the object : are you meaningful or not ? This is done using the following algorithm : If the object has a __nonzero__ special method (as do numeric built-ins, int and float ), it calls this method. It must either return a bool value which is then directly used, or an int value that is considered False if equal to zero. Otherwise, if the object has a __len__ special method (as do container built-ins, list , dict , set , tuple , ...), it calls this method, considering a container False if it is empty (length is zero). Otherwise, the object is considered True unless it is None in which case, it is considered False . In the second test, the object is compared for equality to None . Here, we are asking the object, "Are you equal to this other value?" This is done using the following algorithm : If the object has a __eq__ method, it is called, and the return value is then converted to a bool value and used to determine the outcome of the if . Otherwise, if the object has a __cmp__ method, it is called. This function must return an int indicating the order of the two object ( -1 if self < other , 0 if self == other , +1 if self > other ). Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the is operator). There is another test possible using the is operator. We would be asking the object, "Are you this particular object?" Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values ( None meaning not initialized for a member field for exemple, or when using the getattr or the __getitem__ methods). To summarize, we have : >>> class A(object):... def __repr__(self):... return 'A()'... def __nonzero__(self):... return False>>> class B(object):... def __repr__(self):... return 'B()'... def __len__(self):... return 0>>> class C(object):... def __repr__(self):... return 'C()'... def __cmp__(self, other):... return 0>>> class D(object):... def __repr__(self):... return 'D()'... def __eq__(self, other):... return True>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \... (repr(obj), bool(obj), obj == None, obj is None) '': bool(obj) -> False, obj == None -> False, obj is None -> False (): bool(obj) -> False, obj == None -> False, obj is None -> False []: bool(obj) -> False, obj == None -> False, obj is None -> False {}: bool(obj) -> False, obj == None -> False, obj is None -> False 0: bool(obj) -> False, obj == None -> False, obj is None -> False 0.0: bool(obj) -> False, obj == None -> False, obj is None -> False A(): bool(obj) -> False, obj == None -> False, obj is None -> False B(): bool(obj) -> False, obj == None -> False, obj is None -> False C(): bool(obj) -> True, obj == None -> True, obj is None -> False D(): bool(obj) -> True, obj == None -> True, obj is None -> FalseNone: bool(obj) -> False, obj == None -> True, obj is None -> True
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/100732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ] }
100,841
I've had a bug in our software that occurs when I receive a connection timeout. These errors are very rare (usually when my connection gets dropped by our internal network). How can I generate this kind of effect artificially so I can test our software? If it matters the app is written in C++/MFC using CAsyncSocket classes. Edit: I've tried using a non-existent host, and I get the socket error: WSAEINVAL (10022) Invalid argument My next attempt was to use Alexander 's suggestion of connecting to a different port, e.g. 81 (on my own server though). That worked great. Exactly the same as a dropped connection (60 second wait, then error). Thank you!
Connect to an existing host but to a port that is blocked by the firewall that simply drops TCP SYN packets. For example, www.google.com:81.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/100841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ] }
100,853
While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it?
<%= is a equivalent to <% Repsonse.Write() You can write any content out here: for example <%=myProperty + " additional Text" %> <%# is a binding expression. You can retrieve any public value in the current context (for example in GridViews). But you cannot mix content here. Take a look at MSDN for more information.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018/" ] }
100,898
What's the best / simplest / most accurate way to detect the browser of a user? Ease of extendability and implementation is a plus. The less technologies used, the better. The solution can be server side, client side, or both. The results should eventually end up at the server, though. The solution can be framework agnostic. The solution will only be used for reporting purposes.
On the server you're pretty much limited to the UserAgent string the browser provides (which is fraught with problems, have a read about the UserAgent string's history ). On the client (ie in Javascript), you have more options. But the best option is to not actually worry about working out which browser it is. Simply check to make sure whatever feature you want to use actually exists. For example, you might want to use setCapture, which only MSIE provides: if (element.setCapture) element.setCapture() Rather than working out what the browser is, and then inferring its capabilities, we're simply seeing if it supports something before using it - who knows what browsers will support what in the future, do you really want to have to go back and update your scripts if Safari decides to support setCapture?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ] }
100,922
Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor? In other words, what is wrong about this code? public class MyClass{ private IMyInterface _myInterface; public MyClass() { _myInterface = new DefaultMyInterface(); } public MyClass(IMyInterface myInterface) { _myInterface = myInterface; }} As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done. In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent). The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently. Am I missing something?
The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface. The main idea is that your component has no knowledge about how it will be used. In your example, your component makes some assumptions about its use. Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO. IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/100922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ] }
100,948
I installed MySQL via MacPorts . What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?
There are different cases depending on whether you installed MySQL with the official binary installer, using MacPorts , or using Homebrew : Homebrew brew services start mysqlbrew services stop mysqlbrew services restart mysql MacPorts sudo port load mysql57-serversudo port unload mysql57-server Note: this is persistent after a reboot. Binary installer sudo /Library/StartupItems/MySQLCOM/MySQLCOM stopsudo /Library/StartupItems/MySQLCOM/MySQLCOM startsudo /Library/StartupItems/MySQLCOM/MySQLCOM restart
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/100948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ] }
100,959
I am aware of CocoaMySQL but I have not seen a Mac GUI for SQLite, is there one? My Google search didn't turn up any Mac related GUI's which is why I'm asking here rather than Google.
SQLite Manager for FireFox
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/100959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
100,993
I'm new to both Web Services and RMI and I wonder which is the better way to do remoting between different web applications, when these applications are all written in Java, that is when different programming languages don't matter (which would be the advantage of WS). While on the one hand I would guess that there's a performance overhead when using web services (does anyone have some numbers to prove that?), on the other hand it seems to me that web services are much more loosely coupled and can be used to implement a more service-oriented architecture (SOA) (which isn't possible with RMI, right?). Although this is quite a general question, what's your opinion? Thanks
The web services do allow a loosely coupled architecture. With RMI, you have to make sure that the class definitions stay in sync in all application instances, which means that you always have to deploy all of them at the same time even if only one of them is changed (not necessarily, but it is required quite often because of serial UUIDs and whatnot) Also it is not very scalable, which might be an issue if you want to have load balancers. In my mind RMI works best for smaller, local applications, that are not internet-related but still need to be decoupled. I've used it to have a java application that handles electronic communications and I was quite satisfied with the results. For other applications that require more complex deployment and work across the internet, I rather use web services.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/100993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ] }
100,995
So I got this question from one of the developers in my team: What is domain driven design? I could of course point to the book from Evans but is that actually an answer? How would you explain DDD in a few sentences to junior software engineers in your team?
I would say this practice promotes concentrating your efforts on the 'problem space' rather than the 'solution space'. Driving an emergent solution (the design) by studying and really getting to know and understand the domain. One of the practices (taken from XP) would be the writing of stories that occur in the problem domain. From these you can identify your use cases and objects for your design. They 'emerge' and tell you what needs to be in the solution, and how they will need to interact with each other.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/100995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18703/" ] }
101,033
I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?
Here is how to build a function that returns a result set that can be queried as if it were a table: SQL> create type emp_obj is object (empno number, ename varchar2(10)); 2 /Type created.SQL> create type emp_tab is table of emp_obj; 2 /Type created.SQL> create or replace function all_emps return emp_tab 2 is 3 l_emp_tab emp_tab := emp_tab(); 4 n integer := 0; 5 begin 6 for r in (select empno, ename from emp) 7 loop 8 l_emp_tab.extend; 9 n := n + 1; 10 l_emp_tab(n) := emp_obj(r.empno, r.ename); 11 end loop; 12 return l_emp_tab; 13 end; 14 /Function created.SQL> select * from table (all_emps); EMPNO ENAME---------- ---------- 7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES 7654 MARTIN 7698 BLAKE 7782 CLARK 7788 SCOTT 7839 KING 7844 TURNER 7902 FORD 7934 MILLER
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
101,055
What makes a language a scripting language? I've heard some people say "when it gets interpreted instead of compiled". That would make PHP (for example) a scripting language. Is that the only criterion? Or are there other criteria? See also: What’s the difference between a “script” and an “application”?
A scripting language is a language that "scripts" other things to do stuff. The primary focus isn't primarily building your own apps so much as getting an existing app to act the way you want, e.g. JavaScript for browsers, VBA for MS Office.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/101055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6400/" ] }
101,061
I have a C extension module and it would be nice to distribute built binaries. Setuptools makes it easy to build extensions modules on OS X and GNU/Linux, since those OSs come with GCC, but I don't know how to do it in Windows. Would I need to buy a copy of Visual Studio, or does Visual Studio Express work? Can I just use Cygwin or MinGW?
You can use both MinGW and VC++ Express (free, no need to buy it). See: http://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/ http://eli.thegreenplace.net/2008/06/27/creating-python-extension-modules-in-c/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4702/" ] }
101,070
If you are writing a simple little loop, what should you name the counter? Provide example loops!
I always use a meaningful name unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use i . When using meaningful names: the code is more understandable to colleagues reading your code, it's easier to find bugs in the loop logic, and text searches for the variable name to return relevant pieces of code operating on the same data are more reliable. Example - spot the bug It can be tricky to find the bug in this nested loop using single letters: int values[MAX_ROWS][MAX_COLS];int sum_of_all_values(){ int i, j, total; total = 0; for (i = 0; i < MAX_COLS; i++) for (j = 0; j < MAX_ROWS; j++) total += values[i][j]; return total;} whereas it is easier when using meaningful names: int values[MAX_ROWS][MAX_COLS];int sum_of_all_values(){ int row_num, col_num, total; total = 0; for (row_num = 0; row_num < MAX_COLS; row_num++) for (col_num = 0; col_num < MAX_ROWS; col_num++) total += values[row_num][col_num]; return total;} Why row_num ? - rejected alternatives In response to some other answers and comments, these are some alternative suggestions to using row_num and col_num and why I choose not to use them: r and c : This is slightly better than i and j . I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code. rr and cc : This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better than r and c . row and col : At first glance this seems more succinct than row_num and col_num , and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. If row could mean either the row structure itself, or a row number, then confusion will result. iRow and iCol : This conveys extra information, since i can mean it's a loop counter while Row and Col tell you what it's counting. However, I prefer to be able to read the code almost in English: row_num < MAX_COLS reads as "the row num ber is less than the max imum (number of) col umn s "; iRow < MAX_COLS at best reads as "the integer loop counter for the row is less than the max imum (number of) col umn s ". It may be a personal thing but I prefer the first reading. An alternative to row_num I would accept is row_idx : the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar. My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs. In summary, my aim with all variable naming (not just loops) is to be completely unambiguous . If anybody reads any portion of my code and can't work out what a variable is for immediately, then I have failed.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12293/" ] }
101,072
Was this an oversight? Or is it to do with the JVM?
Java does indeed have pointers--pointers on which you cannot perform pointer arithmetic. From the venerable JLS : There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3). And later : An object is a class instance or an array . The reference values (often just references ) are pointers to these objects, and a special null reference, which refers to no object. (emphasis theirs) So, to interpret, if you write: Object myObj = new Object(); then myObj is a reference type which contains a reference value that is itself a pointer to the newly-created Object . Thus if you set myObj to null you are setting the reference value (aka pointer ) to null . Hence a NullPointerException is reasonably thrown when the variable is dereferenced. Don't worry: this topic has been heartily debated before.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
101,079
I used to work in a place where a common practice was to use Pair Programming. I remember how many small things we could learn from each other when working together on the code. Picking up new shortcuts, code snippets etc. with time significantly improved our efficiency of writing code. Since I started working with SQL Server I have been left on my own. The best habits I would normally pick from working together with other people which I cannot do now. So here is the question: What are you tips on efficientlywriting TSQL code using SQL ServerManagement Studio? Please keep thetips to 2 – 3 things/shortcuts thatyou think improve you speed ofcoding Please stay within the scopeof TSQL and SQL Server ManagementStudio 2005/2008 If the feature isspecific to the version ofManagement Studio please indicate:e.g. “Works with SQL Server 2008only" EDIT: I am afraid that I could have been misunderstood by some of you.I am not looking for tips for writing efficient TSQL code but rather for advice on how to efficiently use Management Studio to speed up the coding process itself. The type of answers that I am looking for are: use of templates, keyboard-shortcuts, use of IntelliSense plugins etc. Basically those little things that make the coding experience a bit more efficient and pleasant.
community owned wiki Answer - feel free to edit or add comments: Keyboard Shortcuts F5 , CTRL + E or ALT + X - execute currently selected TSQL code CTRL + R – show/hide Results Pane CTRL + N – Open New Query Window CTRL + L – Display query execution plan Editing Shortcuts CTRL + K + C and CTRL + K + U - comment/uncomment selected block of code (suggested by Unsliced) CTRL + SHIFT + U and CTRL + SHIFT + L - changes selected text to UPPER/lower case SHIFT + ALT + Selecting text - select/cut/copy/paste a rectangular block of text Addons Red Gate's SQL Prompt - IntelliSense (suggested by Galwegian) SQLinForm - formatting of TSQL (suggested by Galwegian) Poor Man's T-SQL Formatter - open-source formatting add-in Other Tips Using comma prefix style (suggested by Cade Roux) Using keyboard accelerators (suggested by kcrumley) Useful Links SQL Server Management Studio Keyboard Shortcuts (full list)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ] }
101,100
Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it. A quick google has found http://flatpack.sourceforge.net/ which looks promising. I just wanted to check what others are using before I couple myself to this API.
Apache Commons CSV Check out Apache Common CSV . This library reads and writes several variations of CSV , including the standard one RFC 4180 . Also reads/writes Tab-delimited files. Excel InformixUnload InformixUnloadCsv MySQL Oracle PostgreSQLCsv PostgreSQLText RFC4180 TDF
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171/" ] }
101,125
Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?
I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string: <link href="mystyle.css?SOME_UNIQUE_TEXT" type="text/css" rel="stylesheet" /> I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
101,128
How do I read text from the (windows) clipboard with python?
You can use the module called win32clipboard , which is part of pywin32 . Here is an example that first sets the clipboard data then gets it: import win32clipboard# set clipboard datawin32clipboard.OpenClipboard()win32clipboard.EmptyClipboard()win32clipboard.SetClipboardText('testing 123')win32clipboard.CloseClipboard()# get clipboard datawin32clipboard.OpenClipboard()data = win32clipboard.GetClipboardData()win32clipboard.CloseClipboard()print data An important reminder from the documentation: When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows to access the clipboard. Do not place an object on the clipboard after calling CloseClipboard.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/101128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17493/" ] }
101,145
How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.
if(doc.SelectSingleNode("//mynode")==null).... Should do it (where doc is your XmlDocument object, obviously) Alternatively you could use an XSD and validate against that
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
101,146
Does anybody use anything else to document their PHP code than PHPDoc? Are there any tools that read the same documentation syntax but give richer output?
I´ll go for doxygen too. Here are several reasons : compatible with phpdoc tags and other popular ones : it´s interoperable works with various programming languages : a better time investment there is alternative syntaxes : can choose the commenting style that suit you very efficient with advanced formating / tagging / metadata there is a GUI that is not linked to any IDE and an eclipse plugin as well And still free, multiplatform, and open source :-) It´s easy to learn, but harder that phpdoc because a lot richer.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ] }
101,162
How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
From the controller you can just return a JsonResult: public ActionResult MyAction(){ ... // Populate myObject return new JsonResult{ Data = myObject };} The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like: $.getJSON("/controllerName/MyAction", callbackFunction); where the callbackFunction takes a parameter which is the data from the XHR request.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
101,174
In Python there is a really neat function called zip which can be used to iterate through two lists at the same time: list1 = [1, 2, 3]list2 = ["a", "b", "c"]for v1, v2 in zip(list1, list2): print v1 + " " + v2 The above code should produce the following: 1 a2 b3 c I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.
Update: It is built-in in C# 4 as System.Linq.Enumerable.Zip Method Here is a C# 3 version: IEnumerable<TResult> Zip<TResult,T1,T2> (IEnumerable<T1> a, IEnumerable<T2> b, Func<T1,T2,TResult> combine){ using (var f = a.GetEnumerator()) using (var s = b.GetEnumerator()) { while (f.MoveNext() && s.MoveNext()) yield return combine(f.Current, s.Current); }} Dropped the C# 2 version as it was showing its age.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16047/" ] }
101,184
I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.
Run this SQL: select * from v$version; And you'll get a result like: BANNER----------------------------------------------------------------Oracle Database 10g Release 10.2.0.3.0 - 64bit ProductionPL/SQL Release 10.2.0.3.0 - ProductionCORE 10.2.0.3.0 ProductionTNS for Solaris: Version 10.2.0.3.0 - ProductionNLSRTL Version 10.2.0.3.0 - Production
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/101184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750/" ] }
101,258
I want to search for $maximumTotalAllowedAfterFinish and replace it with $minimumTotalAllowedAfterFinish . Instead of typing the long text: :%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type " p " to paste?
You can insert the contents of a numbered or named register by typing CTRL R {0-9a-z"%#:-=.} . By typing CTRL-R CTRL-W you can paste the current word under the cursor. See: :he cmdline-editing for more information.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/101258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ] }
101,265
Inspired by another question asking about the missing Zip function: Why is there no ForEach extension method on the IEnumerable interface? Or anywhere? The only class that gets a ForEach method is List<> . Is there a reason why it's missing, maybe performance?
There is already a foreach statement included in the language that does the job most of the time. I'd hate to see the following: list.ForEach( item =>{ item.DoSomething();} ); Instead of: foreach(Item item in list){ item.DoSomething();} The latter is clearer and easier to read in most situations , although maybe a bit longer to type. However, I must admit I changed my stance on that issue; a ForEach() extension method would indeed be useful in some situations. Here are the major differences between the statement and the method: Type checking: foreach is done at runtime, ForEach() is at compile time (Big Plus!) The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething); ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion. Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/101265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820/" ] }
101,267
When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code: C++: #ifdef _BuildDateTime_ char* SomeClass::getBuildDateTime() { return _BuildDateTime_; }#else char* SomeClass::getBuildDateTime() { return "Undefined"; }#endif Then on the compile I had a '-D_BuildDateTime_= Date ' in the build script. Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files. One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method. Something like (assuming the file created was called 'DateTime.dat'): // I know Exceptions and proper open/closing // of the file are not done. This is just // to explain the point!String getBuildDateTime() { return new BufferedReader(getClass() .getResourceAsStream("DateTime.dat")).readLine();} To my mind that's a hack and could be circumvented/broken by someone having a similarly named file outside the JAR, but on the classpath. Anyway, my question is whether there is any way to inject a constant into a class at compile time EDIT The reason I consider using an externally generated file in the JAR a hack is because this is ) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules. My personal preference would be to go with using the date from the JAR file as suggested by serg10.
I would favour the standards based approach. Put your version information (along with other useful publisher stuff such as build number, subversion revision number, author, company details, etc) in the jar's Manifest File . This is a well documented and understood Java specification. Strong tool support exists for creating manifest files (a core Ant task for example, or the maven jar plugin ). These can help with setting some of the attributes automatically - I have maven configured to put the jar's maven version number, Subversion revision and timestamp into the manifest for me at build time. You can read the contents of the manifest at runtime with standard java api calls - something like: import java.util.jar.*;...JarFile myJar = new JarFile("nameOfJar.jar"); // various constructors availableManifest manifest = myJar.getManifest();Map<String,Attributes> manifestContents = manifest.getAttributes(); To me, that feels like a more Java standard approach, so will probably prove more easy for subsequent code maintainers to follow.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18744/" ] }
101,268
What are the lesser-known but useful features of the Python programming language? Try to limit answers to Python core. One feature per answer. Give an example and short description of the feature, not just a link to documentation. Label the feature using a title as the first line. Quick links to answers: Argument Unpacking Braces Chaining Comparison Operators Decorators Default Argument Gotchas / Dangers of Mutable Default arguments Descriptors Dictionary default .get value Docstring Tests Ellipsis Slicing Syntax Enumeration For/else Function as iter() argument Generator expressions import this In Place Value Swapping List stepping __missing__ items Multi-line Regex Named string formatting Nested list/generator comprehensions New types at runtime .pth files ROT13 Encoding Regex Debugging Sending to Generators Tab Completion in Interactive Interpreter Ternary Expression try/except/else Unpacking+ print() function with statement
Chaining comparison operators: >>> x = 5>>> 1 < x < 10True>>> 10 < x < 20 False>>> x < 10 < x*10 < 100True>>> 10 > x <= 9True>>> 5 == x > 4True In case you're thinking it's doing 1 < x , which comes out as True , and then comparing True < 10 , which is also True , then no, that's really not what happens (see the last example.) It's really translating into 1 < x and x < 10 , and x < 10 and 10 < x * 10 and x*10 < 100 , but with less typing and each term is only evaluated once.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/101268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679/" ] }
101,270
I want to use Vim's quickfix features with the output from Visual Studio's devenv build process or msbuild. I've created a batch file called build.bat which executes the devenv build like this: devenv MySln.sln /Build Debug In vim I've pointed the :make command to that batch file: :set makeprg=build.bat When I now run :make, the build executes successfully, however the errors don't get parsed out. So if I run :cl or :cn I just end up seeing all the output from devenv /Build. I should see only the errors. I've tried a number of different errorformat settings that I've found on various sites around the net, but none of them have parsed out the errors correctly. Here's a few I've tried: set errorformat=%*\\d>%f(%l)\ :\ %t%[A-z]%#\ %mset errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %mset errorformat=%f(%l,%c):\ error\ %n:\ %f And of course I've tried Vim's default. Here's some example output from the build.bat: C:\TFS\KwB Projects\Thingy>devenv Thingy.sln /Build Debug Microsoft (R) Visual Studio Version 9.0.30729.1.Copyright (C) Microsoft Corp. All rights reserved.------ Build started: Project: Thingy, Configuration: Debug Any CPU ------c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll" /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationProvider.dll" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\Thingy.exe /resource:obj\Debug\Thingy.g.resources /resource:obj\Debug\Thingy.Properties.Resources.resources /target:winexe App.xaml.cs Controller\FieldFactory.cs Controller\UserInfo.cs Data\ThingGatewaySqlDirect.cs Data\ThingListFetcher.cs Data\UserListFetcher.cs Gui\FieldList.xaml.cs Interfaces\IList.cs Interfaces\IListFetcher.cs Model\ComboBoxField.cs Model\ListValue.cs Model\ThingType.cs Interfaces\IThingGateway.cs Model\Field.cs Model\TextBoxField.cs Model\Thing.cs Gui\MainWindow.xaml.cs Gui\ThingWindow.xaml.cs Interfaces\IField.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs RequiredValidation.cs "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\FieldList.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\MainWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\Gui\ThingWindow.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\App.g.cs" "C:\TFS\KwB Projects\Thingy\Thingy\obj\Debug\GeneratedInternalTypeHelper.g.cs"C:\TFS\KwB Projects\Thingy\Thingy\Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?)Compile complete -- 1 errors, 0 warnings========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ========== UPDATE: It looks like using msbuild instead of devenv is probably the right way to go (as per Jay's comment). Using msbuild the makeprg would be: :set makeprg=msbuild\ /nologo\ /v:q Sample output whould be: Controller\FieldFactory.cs(14,19): error CS0246: The type or namespace name 'IFieldNothing' could not be found (are you missing a using directive or an assembly reference?) It looks like the tricky part here may lie in the fact that the path is relative to the .csproj file, not the .sln file which is the current directory in Vim and lies one directory above the .csproj file. ANSWER: I figured it out... set errorformat=\ %#%f(%l\\\,%c):\ %m This will capture the output for both devenv /Build and msbuild.However, msbuild has one catch. By default, it's output doesn't include full paths. To fix this you have to add the following line to your csproj file's main PropertyGroup: <GenerateFullPaths>True</GenerateFullPaths>
I have a blog post which walks through all the details of getting C# projects building in Vim, including the error format. You can find it here: http://kevin-berridge.blogspot.com/2008/09/vim-c-compiling.html In short you need the following: :set errorformat=\ %#%f(%l\\\,%c):\ %m:set makeprg=msbuild\ /nologo\ /v:q\ /property:GenerateFullPaths=true
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/101270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ] }
101,275
In the question What little things do I need to do before deploying a rails application I am getting a lot of answers that are bigger than "little things". So this question is slighly different. What reasonably major steps do I need to take before deploying a rails application. In this case, i mean things which are are going to take more than 5 mins, and so need to be scheduled. For small oneline config changes, please use the little things question.
Set up Capistrano to deploy You'll want to learn capistrano if you don't already know it, and use it to deploy your code in an automated way. This will involve setting up your shared directory and shared resources like database.yml. Install C Based MySQL gem If you don't have all the required libs, this can take a little while, but less than 20 minutes. Make sure you aren't vulnerable to common web application attacks Session fixation, session hijacking, cross-site scripting, SQL injection (probably you don't have to worry much about SQL injection). Be sure you use h() when outputting user-entered data in a view screen. Lots of good material online about this. Choose a server architecture Nginx, Mongrel, FastCGI, CGI, Apache, Passenger: there is a lot to choose from. Think about how your app will be used and decide on the best architecture, then set it up. Set up Exception Notifier or Exception Logger You will want your app to warn you when it breaks. Set one of these tools up to track production exceptions. Note: Exception notifier will warn you when routing errors occur (i.e. when people fat-finger URLs or script kiddies attack you): so think about what you want the framework to do when that happens and adjust accordingly. Make sure all of your passwords are out of source control If you have database.yml, mail.yml (if you use yaml_mail_config) or other sensitive files in source control, get them out of there, replace them with database.yml.example, and put them in the shared/ folder on your server. Ensure that your DB is locked down. A lot of people forget to secure MySQL when setting up their new production Rails box. Don't be like them. Make sure all of the little web-files are in place If you are planning to be listed in Google, generate a sitemap.xml file. If you are planning to use an . htaccess file for something, make sure it's there. If you need a robots.txt file to prevent certain areas of your site from being indexed, make one. If you want a good looking 404 Page , make sure it's set up correctly. If you want a "Be Right Back" page to be present when you deploy, make sure that you have a Capistrano maintenance file specified and Nginx or Apache knows how and when to redirect to it. Get your SSL Certs in place If you are going to use SSL, make sure you get certificates that are valid on your production domain, and set them up.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ] }
101,290
binary question :)
The answer is 4 bits. 2 nibbles make a byte. See here for a cute poem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/101290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18769/" ] }