答:
The MVC pattern was originally formulated before graphical interfaces became commonplace. In that era,it was up to the application to correlate a screen position with a particular button/input field. It was the job of the Controller part of MVC to make that mapping.

Nowadays, translating mouse clicks to a press of the correct button (or a key press to a character in an input field) is taken care of by the OS. For that reason, to say what the role of the Controller is in modern applications, especially desktop applications. It might be valuable to also look at related patterns, such as MVVM and MVP.

In all of these, the View component is responsible for the (graphical) interface that the user sees.

The Model component is responsible for the business logic (the calculations in your case) and should be completely independent from how the user interacts with the program. For the Model, it must not make a difference if the user enters an equation (like 1 + 2 * 3) or presses a sequence of buttons.

The variation between MVC, MVP and MVVM lies in how the Model and View components are connected with each other. This is where, for example, a press on a + button gets translated to tell the Model that a + has been entered.

Title: Building a calculator using MVC

Body:
I've been programming in Java for about 6 months, and I thought a good and challenging test of my skills would be to build a GUI calculator. I have very recently heard about this MVC idea, and I thought (perhaps foolishly) that it would be a good fit for this pet project. But I'm running into trouble during the design, and I'm not sure how to proceed.

So I have a Model, View, and Controller class. The Model is responsible for all the actual calculation; the View draws the calculator and the display; and the Controller:

passes button clicks to View

gets the display value from Model and passes it to View

Ah, but the buttons! I want to have a Button interface, where a Button instance has:

(unique) ID number;

Name;

function.

Then I would have my Controller build up a collection of Buttons, and [not sure how to do this] let both the View and Model use those buttons: View for drawing, Model for calculating.  Thus I have the revised list for Controller:

pass clicks to View

return Button ID to Model

get display value from Model and pass it to View

But the more I work on this, the more I can't figure out how this would all come together. So I have several related questions:

Should View really be responsible for sorting out which Button a click corresponds to? Should that be done in Controller?

Should I have more than one type of Button? Is it necessary to distinguish between numbers, operators, equals, etc.? Which of the three MVC classes needs to know the difference?

Is MVC even the right way to go here? Is there a more fundamental, accepted way of building an OOP calculator?

If MVC is indeed appropriate, what am I doing wrong? I think adding in the Buttons has really thrown me off.


问:
Identifying Domain Services & Application Services when doing DDD
-I'm trying to figure out how to identify Application Services in my application. I think I can identify a Domain service by 2 things:

It acts as a facade to the repository.

It holds business logic that can't be encapsulated in a single entity.

So I thought about this simple use case that I'm currently working on:

An admin should be able to ban a certain user. The operation must be logged and an email must be sent to the banned user.

I have a UserRepository which has a function getUserById(). I have a User entity which has a ban() function.

I'll create a UserService like this:

```<code>class UserService{
    static void banUser(int userId){
          User user= UserRepository.getUserById(userId);
          user.ban();
          UserRepository.update(user);
    }
}
</code>```

The userId is a POST variable that I'll be receiving in my Controller from a web form.

Now where does the logging go? I need to log the ban process twice before and after the operation ex:

```<code>Logger.log("Attempting to ban user with id:"+userId);
//user gets banned
Logger.log("user banned successfully.");
</code>```

Second, I need to send a mail to the user. where should the call go?

I thought about putting the logging and email  is the UserService class itself, but I think there are better solutions.

Third, where do Application Services fit in all of this?

答:
Now where does the logging go?

Second, I need to send a mail to the user. where should the call go?

I would recommend Domain Events.  Create two events: UserBanAttemptedEvent and UserBannedEvent (note the past time).

The logic for logging and email notifying is going inside event handlers, create two handlers UserBanAttemptedEventHandler and UserBannedEventHandler.

The *payload classes just simple DTO with useful information like: UserId etc.
 This approach decouples application logic better imho

```<code>void banUser(int userId){
      DomainEvents.Raise<UserBanAttemptedEvent>(new UserBanAttemptedPayload())

      User user= UserRepository.getUserById(userId);
      user.ban();
      UserRepository.update(user);

      DomainEvents.Raise<UserBannedEvent>(new UserBannedPayload())
}
</code>```

There are many implementations of these pattern, examples:

http://lostechies.com/jimmybogard/2014/05/13/a-better-domain-events-pattern/

DDDSample.Net

ContentLicense: CC BY-SA 3.0

Body:
Now where does the logging go?

Second, I need to send a mail to the user. where should the call go?

I would recommend Domain Events.  Create two events: UserBanAttemptedEvent and UserBannedEvent (note the past time).

The logic for logging and email notifying is going inside event handlers, create two handlers UserBanAttemptedEventHandler and UserBannedEventHandler.

The *payload classes just simple DTO with useful information like: UserId etc.
 This approach decouples application logic better imho

void banUser(int userId){
      DomainEvents.Raise<UserBanAttemptedEvent>(new UserBanAttemptedPayload())

      User user= UserRepository.getUserById(userId);
      user.ban();
      UserRepository.update(user);

      DomainEvents.Raise<UserBannedEvent>(new UserBannedPayload())
}

There are many implementations of these pattern, examples:

http://lostechies.com/jimmybogard/2014/05/13/a-better-domain-events-pattern/

DDDSample.Net


问:
How can I determine which version of Python introduced a particular module to the std lib?
Is there a single timeline-style resource available showing the history of the modules available in different versions of Python?

I'd like to, for instance, easily determine which version of Python introduced the pipes module, without needing to perform a binary search by installing different Python versions until I find a version that doesn't have it followed immediately by one that does.

答:
The pipes module is pretty old. Most standard library modules that have been introduced in the last decade or so state when they were introduced on the module documentation page. For example, the sysconfig module was introduced in version 2.7.

Shameless plug: I have written a script called pyqver (on Github) that attempts to identify the minimum version of Python required to run a particular script. In the source, there is a table of modules and functions along with the version of Python where they were introduced. I see that I hadn't even included the pipes module because it was so old.

To answer your specific question, it appears that the pipes module was first documented in Python 1.5.2p1, released in July 1999. I found this by clicking through the links at on https://www.python.org/doc/versions/.

However, the pipes.py source file is considerably older than that. The first version appeared in October 1992 as can be seen in this commit, found from the file history at https://github.com/python/cpython/commits/master/Lib/pipes.py.


问:
cross-application text formatting
I am not sure whether this question is a good fit for this site, but if it is not, please let me know and I will take it down.

If it is off-topic, some general info on where I can look for these answers would be greatly appreciated.

I am wondering how the data that determines how text is to be formatted is stored. For example, if I format some text in Bold and Italic in Microsoft Word, I can paste it into google docs and the formatting will stay the same, but If I paste it in here, it will loose its formatting. I am wondering if this is because google docs is aware of the formatting used by Word and it converts it, or if they use the same type of formatting and there is some set of standards.

答:
Some applications, among which LibreOffice at Linux, use multiple clipboards if I'm not mistaken.

The clipboard is the place where things are temporarily stored when pressing CTL+C, and of LibreOffice I know it saves it in different clipboards, in different formats. These formats vary from plain-text to rich and might even include images.

There's also a function called Paste special... in LibreOffice, which allows you to choose how you want to paste the information in the clipboard.

(what I'm saying might not be 100% correct - but I believe it is) I know you're using Microsoft Word as an example, so Widows might be a whole other world, but I hope it was of some help.

Title: cross-application text formatting


问:
Does pair programming remove the need of code reviews in an Extreme Programming (XP) project?
In an extreme programming project, programmers do pair programming most of the time.

As these pairs also rotate, that is, you pair program with different people, and there is a sense of collective ownership, source code is being frequently reviewed and updated.

Being so, is there a need for code reviews? I mean, stop programming and actually just do code reviews.

答:
One of the key resources for Extreme Programming is that of Ward's Wiki aka Portland Pattern Repository aka C2.com.  This is where a number of people hashed out various methodologies and documented them as they used them.

Within this wiki, there is a page: Extreme Programming Code Reviews that has a number of contributors to it, including Ron Jeffries and Kent Beck.

To this, they said:

Code reviews are considered important by many large-process gurus. They are intended to ensure conformance to standards, and more importantly, intended to ensure that the code is clear, efficient, works, and has QWAN. They also intended to help disseminate knowledge about the code to the rest of the team.

ExtremeProgramming requires that all development is done by two engineers working together. The code is actually reviewed on the fly, to quite a great degree. This ensures that more than one person has intimate knowledge of the code at all times.

ExtremeProgramming requires that all objects have UnitTests. These ensure that the object works, and continues to work as modified.

Some languages are reflective. In such languages, UnitTests can check directly for important standards conformance. (e.g. objects must implement both #= and #hash, or neither.)

ExtremeProgramming practices CollectiveCodeOwnership, which means that objects needing attention will be browsed by many developers. This tends to bring pressure to bear on those producing code that doesn't conform to standards. Visiting developers are encouraged/expected to bring code into conformance when they find deviations. This also ensures that knowledge of code is disseminated beyond the initial pair of programmers that created it.

Therefore, ExtremeProgramming projects do not require explicit reviews. Drop them from your methodology.

There is also quite a bit more discussion on the topic there from others.

The key points though being that with the combination of tests, collaborative ownership and pair programming these things resolve the goals that a code review is typically supposed to do such as:

Disperse the knowledge of what is being done

A second (or more) set of eyeballs on the code to make sure it is following standards

Verify correct functioning of the code

These are being done continuously through pair programming and automated testing in Extreme Programming and thus an explicit Fagan inspection is unnecessary.

Related reading:

Pair Programming vs. Code Reviews at Coding Horror.

Code Reviews Considered Hurtful at ExtremeProgramming.org


问:
When deploying code to a production server, how are non-source code assets such as images and PDFs managed?
Currently, I am trying to set up deployment procedures and GIT for a group of websites. Code and assets are between 15 and 20GB. The code and related text files are probably closer to 150MB.

When deploying code from the developer machine, to a server, or from a server to another server. What are the common solutions used for managing non-source code assets such as images and PDFs?

There will be a continuous integration server, for sure. However, I don't know how storage and versioning is reliably handled without setting up a separate version control system.

答:
I think this varies from project to project. Generally the advise by
Bart is a valid one. If these assets are directly connected to the source-code and managed by the developer (best example are images statically linked/embedded in a template) it's a good practice to have them inside the repo.

If this isn't the case, we have to ask some other questions. The key questions here are IMHO:

Do you have any benefit from this assets being managed by version control?

Are this assets managed by yourself or by someone or something external (application internal uploader)?

If the assets are managed inside of your application, doesn't that have some kind of version control for assets by itself?

Is there even a need to actively sync assets from one environment to another? Isn't it easier to have them separate on each environment and rsync them from live to staging/local when really needed? (This depends on how the assets are connected to your application.)

Are there any disadvantages from having the assets in version control (for example constantly having conflicts in the different environments local vs. stage vs. live)?

As you are stating a size of 15-20G in your question I would personally assume it doesn't really makes sense to keep these assets in version control at all. Keeping it inside the backup should be enough in almost any case I can imagine, as long as there are no special requirements in your project which we don't know of.

Also keep in mind that you will be forced to download the whole history (read: any file that ever existed) on the initial checkout of that repo. If we assume you could somehow manage to add the 15-20G to that repo now and you have a turnover of 500MB every month the repo will be 27-32G in two years, which will be a major pain for everyone who has to work with it and will in the end force you to get rid of a part of the repo history anyway. ;-)


问:
How much business logic should be allowed to exist in the controller layer?
Sometimes we have some business logic represented in the controller code of our applications. This is usually logic that differentiates what methods to call from the model and/or what arguments to pass them.

Another example of this is a set of utility functions that exist in the controller that may work to format or sanitize data returned from the model, according to a set of business rules.

This works, but I am wondering if its flirting with disaster. If there is business logic shared between controller and model the two layers are no longer separable, and someone inheriting the code may be confused by this unevenness in location of business logic related code.

My question is how much business logic should be allowed in the controller and in what circumstances, if any?

答:
From a pragmatic point of view I have found that you either end up with logic in your controller or controller behavior in your model when you are trying to do something that there is not a good pattern-compliant approach for.  Doubly so if you are writing an app that does not have a big infrastructure behind it.

You can go either way, but I usually try to think if the weird bit is likely to show up in more than one controller action, if so it goes in the model.  If that is unclear, I try to think if it is more "fitting" in one place than the other.  Failing that I usually put it in the model just to keep it out of the controller (personal preference for smaller controllers and stronger data objects, YMMV)

A third option would be to reference the utility items as a separate utility class, but that is somewhat against pattern as well in the opinion of many.

Also, just because you aren't strictly following a pattern you are not necessarily flirting with disaster.  Unless you really expect a significant amount of code re-use off this project I would worry a whole lot more about the project being consistent to itself (ie: don't flip-flop on where you put these bits once you pick a location) than a re-write that for some reason wants to save part of the middle of the project.  Document/comment where & why you deviated from the common pattern and define the expected pattern for this application.

MVC was a deviation from established patterns itself at one point.

ContentLicense: CC BY-SA 2.5


问:
Building a calculator using MVC
I've been programming in Java for about 6 months, and I thought a good and challenging test of my skills would be to build a GUI calculator. I have very recently heard about this MVC idea, and I thought (perhaps foolishly) that it would be a good fit for this pet project. But I'm running into trouble during the design, and I'm not sure how to proceed.

So I have a Model, View, and Controller class. The Model is responsible for all the actual calculation; the View draws the calculator and the display; and the Controller:

passes button clicks to View

gets the display value from Model and passes it to View

Ah, but the buttons! I want to have a Button interface, where a Button instance has:

(unique) ID number;

Name;

function.

Then I would have my Controller build up a collection of Buttons, and [not sure how to do this] let both the View and Model use those buttons: View for drawing, Model for calculating.  Thus I have the revised list for Controller:

pass clicks to View

return Button ID to Model

get display value from Model and pass it to View

But the more I work on this, the more I can't figure out how this would all come together. So I have several related questions:

Should View really be responsible for sorting out which Button a click corresponds to? Should that be done in Controller?

Should I have more than one type of Button? Is it necessary to distinguish between numbers, operators, equals, etc.? Which of the three MVC classes needs to know the difference?

Is MVC even the right way to go here? Is there a more fundamental, accepted way of building an OOP calculator?

If MVC is indeed appropriate, what am I doing wrong? I think adding in the Buttons has really thrown me off.

答:
Instead of having a single class for the model, the view and the controller I would make them 3 different folders/packages full of multiple classes/views/controllers. That will allow you to bind each button or a group of buttons to a different listener/controller which performs different operations on the Model depending on the listener.

One possible solution is you could bind one listener to all of the numbers, then individual controllers for each of the operations (+, -, *, =, etc).

Title: Building a calculator using MVC


问:
Where is it specified that Java is call by value?
I know that Java is by default call-by-value but I am not sure where in the Java Language Specification this is addressed. Google searching only seems to find me unofficial sources but never points to where the actual part of the specification that describes this is.

Where in the JLS does it state that Java is call-by-value and how does that part of the specification actually say that it is call-by-value rather than some other convention?

答:
Pass-by-value/pass-by-reference is a property of the semantics of the language. It's not up to someone to "specify" independently of the language specification; rather, it arises from how the semantics of the language work (which in the case of Java is specified in the JLS). If the language standard actually describes pass-by-value semantics, but the language creator "specifies" the language to be pass-by-reference, that does not make it pass-by-reference.

First, you have to agree on what pass-by-value/pass-by-reference means. The commonly-used definition is that if you do simple assignment (using =) to a parameter inside a function, and it has the same effect as simple assignment to the passed variable in the calling scope, it is pass-by-reference; if it has no effect in the calling scope, it is pass-by-value.

In Java, parameter variables are newly created variables for that method invocation, and initialized with copies of the passed value. Also, assignment in Java only alters that variable, and not possibly any other variable. These things combined fit the definition of pass-by-value.


问:
Forks of MIT licensed projects
Let's take an example:

User A

MIT license

  Copyright (C) 2014, User A

User B

other license (not MIT) in which people who

  fork won't require mention of the current copyright notice

  Copyright (C) 2014, User B & User A

User C

any license

  Copyright (C) 2014 User C

  (No link with User A because User B's license did not require mention)

User A releases a JavaScript library under MIT license. The first line of the license contains :

Copyright (C) 2014, User A.

User B forks the project (with a new name) and his new own license. 1st question: What does he need to write ?

Copyright (C) 2014, User A and User B ?

or

Copyright (C) 2014, User B
(original author: User A)  ?

Moreover, let's say User B's license (not MIT) doesn't contain The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. anymore (this was present in User A's MIT license).

User C forks User B's project. As User B's new license does not contain the previous sentence (The above copyright...), then User C has no link with User A's license. Is that right ?

2nd question : Is it mandatory for User C to mention User A?

It seems that in that story, User A's wish (his copyright notice to be included in forks) is not respected.

答:
To quote from MIT license text:

The MIT License (MIT)

Copyright (c)

Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Anyone who distributes this code must include the license.  So if B forks from A, B must include the license.  B may not remove the license restrictions without A's permission, so if C forks from B, C must also abide by these license restrictions.

In other words, in your question, B is violating the license terms and thus may not legally do this.

(Of course, I am not a lawyer.  Please consult one if you need to do such things.)

Title: Forks of MIT licensed projects


问:
How do you deploy your ASP.Net MVC3 application to the production server?
I just want to find out the best practice to deploy your MVC3 application and what tool you use to get the job done.

I am using Visual Studio 2010.  I publish my web site, then manually backup whats on the production server, then upload the new one there. It's tedious and error prone.

What should I do to make this job easier?

答:
For our production websites we install OctoPack (Octopus Deploy) into the web solution via a nuget package in Visual Studio 2013. We set up a Team City build configuration for that project to trigger a deployment with Octopus Deploy, in which we have set up a project and several machines and environments (e.g. staging, live). We use config transforms to ensure the correct config values are used for these environments.

Initially we used the free limited configurations for both Octopus and Team City but we have now switched to a paid license to enable multiple sites.

The Team City build occurs for us upon a check-in to the Staging branch in our Bitbucket git repository, which is approved via code review from a Tech QA via a pull request. This then triggers an automated deployment to the Staging environment.

We then promote the signed-off Staging release to the live environment through Octopus, which deploys the same package to the required environment. You can set up config values in Octopus for different environments and variable to use in config settings. In future we will using Feature Promotion instead of Environment Promotion for our support sites so that we can deploy Feature Branches from Staging to Live.

Once you've installed the Tentacles, Octopus is very straight-forward to use and I've had no real problems with Team City besides missing DLLs due to badly organised solutions. However, for my local environments, I would just use the built-in Visual Studio publish or even a deployment to a free Azure website for my own dev environment - again an option in VS 2013.


问:
Securing sensitive data from developers
I have an enterprise application running that uses both MySQL and MongoDB datastores. My development team all have SSH access to the machine in order to perform application releases, maintenance, etc.

I recently raised a risk in the business when users started storing highly sensitive data on the application that the developers have indirect access to this data which caused a bit of a storm, so I have now been mandated with securing the data so that it is not accessible.

To me this does not seem possible because if the application has access to the database then a developer with access to the machine and application source will always be able to access the data.

答:
Rule #1 of security: If someone has access to information, they have access to that information

That tautology is annoying, but it is true.  If you give access to an individual, they have access to the data.  For users, this usually means access control, but for developers... well... they're the ones that have to write the access control.

If this is a major issue for you (and it sounds like it is), consider building security into your software.  A common pattern is to design secure software in layers.  At the lowest layer, a trusted development team designs software which manages the most naked of access control.  That software is validated and verified by as many people as possible.  Anyone designing that code has access to everything, so trust is essential.

After that, developers can build more flexible access control on top of that core layer.  This code still has to be V&Vd, but it isn't quite as stringent because you can always rely on the core layer to cover the essentials.

The pattern extends outwards.

The hard part, indeed the art of designing these systems, is how to build each layer so that developers can continue to develop and debug while still providing your company with the security you expect.  In particular, you will need to accept that debugging demands more privileges than you think it should, and attempting to lock that down will result in some very angry developers.

As a side solution, consider making "safe" databases for testing purposes where developers can rip out all of the safety mechanisms and do serious debugging.

In the end, both you and your developers need to understand a key tenet of security: All security is a balance between security and usability.  You must strike your own balance as a company.  The system will not be perfectly secure, and it will not be perfectly usable.  That balance will probably even move as your company grows and/or demands on developers change.  If you are open to this reality, you can address it.

Title: Securing sensitive data from developers


问:
PHP conditional test func call against two values
I was wondering if there's a one liner for PHP that would allow me test multiple  values against a function call. As example, say I want to test if foo() returns either 1 or 2, (in pseudo code)

```<code>if( [1||2]==foo() );
</code>```

Maybe above is a bad example of what I mean. Currently if I want to test two values against a function call I would use:

```<code>$test = foo();
if( 1==$test || 2==$test );
</code>```

Its these two lines that I would like to simplify into one

答:
There is nothing like that in PHP, however you can go for something like this -- even tho I'm not really recommending it:

```<code>if ( in_array(foo(), array(1, 2), true) ) ...
</code>```

Please note that it's not gonna work on && conditions and you're limited only to == and ===.

Body:
There is nothing like that in PHP, however you can go for something like this -- even tho I'm not really recommending it:

if ( in_array(foo(), array(1, 2), true) ) ...

Please note that it's not gonna work on && conditions and you're limited only to == and ===.


问:
offline application development for mobile devices
I am looking to develop an application whereby field staff can complete forms in an offline capacity (when onsite I`m assuming no internet connection) on an Apple or Android device and post the results to a web service when they are online.

I have been lead to understand that this is achievable using sharepoint or infopath.  I would personally prefer to use Cordova / HTML / Javascript forms.

My question is:  Is what I have been told correct?  Is it possible to achieve this goal using sharepoint and/or infopath?

答:
Yes Its possible to achieve this in a Cordova app.

I had similar requirements and did in a project.

localStorage features of HTML5 can be used to store data in offline mode and once a device has detected internet connection then it can automatically send via a service call.

So features you need would be:

localStorage - for offline storage

Cordova Network plugin will be used to detect network status

In case GPS (location lat/lng) is required then geolocation API will be used


问:
"Grep" that highlights instead of filter
I was wondering if there is a program in the common unix toolset such as grep that instead of filtering the lines that contain a string, simply outputs the same input but highlighting or coloring the selected string.

I was thinking in doing it by myself (should be simple enough), but maybe it already exists as a unix command.

I'm planning in using it to monitor logs, so I would do something like this:

```<code>tail -f logfile.log | highlight "error"
</code>```

Usually when I'm monitoring logs I need to find a particular string but I also need to know what is written before and after the string, so filtering sometimes is not enough.

Does something like that exist?

Thanks

答:
I would use a simple sed substitute command with ANSI escape codes put before and after the matching RE.

```<code>tail -f logfile.log | sed 's/\(error\)/^[[42m\1^[[0m/g'
</code>```

where ^[ is an ESC character that you can obtain by pressing ctrl-V ESC

If you do need a highlight command, you can define it as a shell function:

```<code>highlight() { sed 's/'"$1"'\)/^[[42m\1^[[0m/g' ; }
</code>```

Body:
I would use a simple sed substitute command with ANSI escape codes put before and after the matching RE.

tail -f logfile.log | sed 's/\(error\)/^[[42m\1^[[0m/g'

where ^[ is an ESC character that you can obtain by pressing ctrl-V ESC

If you do need a highlight command, you can define it as a shell function:

highlight() { sed 's/'"$1"'\)/^[[42m\1^[[0m/g' ; }


问:
How to programmatically connect to a particular PC of unknown IP from a WiFi network?
I want to connect and transfer data between a PC and an Android device both of which are on the same local WiFi network.

I cannot use the local IP as such in the code to actually get the connection going because it does not remain constant every time. I know I can set the local IP to be constant but I am looking for a more general solution to the problem.

Having a central server is also not what I'm looking for, because I want to transfer data offline.

I am not an expert on networks as you might have already guessed, so if I am missing something out, let me know. Also is there some API in android that could do this?

答:
You should look at broadcasting. This is technique of sending your packets to all devices (IP's) in a subnet. It would look something like that:

Android 192.168.0.101: Send message packet to broadcast address
192.168.0.254

PC 192.168.0.110: Reply to 192.168.0.101's broadcast message

Android now knows PC's IP address and can communicate directly

It's really simple. You can find JAVA sample in this SO question: https://stackoverflow.com/questions/12999425/simple-udp-broadcast-client-and-server-on-different-machines


问:
Languages and frameworks to build REST services
I'm currently in the process of developing a REST service that will be consumed by an iPhone app. Basically, the service wraps existing business logic. This business logic is written in c# and I'm writing the service in c#. From a purely curious point of view (not this project) my questions are:
What other languages and frameworks exist to build REST services?
If the technology choice was open which one would you choose and why?
Can you wrap c# assemblies using non Microsoft languages? Would you ever do it? (If the development team was able to support it)</p>

答: I started to use Django framework with python. It is really good technology. Both development and runtime speed is really fast. I mean, you can develop your server app very fast and also it is process performance is really good. Django Rest Framework is really good for RESTful services. </p>


问:
How do I review my own code?
I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?</p>

答:
This has not actually been placed in an answer yet (but has been added as a comment to an existing answer)

Review your code after a good nights sleep, e.g. start the day by reviewing the code that you wrote the previous day.

This will of course not give you the collective experience of a team, but it will give let you review the code from a new perspective.

For instance, if you left a piece of code with a nasty hack, you might not be too inclined to fix it up, if you review your code immediately after. After all, when you start reviewing your code, you already know, and have accepted, the presence of this hack. But if you have had a good nights sleep you are probably more motivated to find a better solution.

When we sleep, the brain doesn't actually stop working on the problems that we have, so you might actually come up with a solution there, though those solutions may sometimes present themselves in odd ways.

Title: How do I review my own code?


问:
A defense for boilerplate?
To me, boilerplate code is obviously bad.  However I've met a developer who displays resistance in any attempt to reduce boilerplate.  I realized I didn't have a readily formed, well thought out argument past the abhorrence I have developed for it over time.

So that I can form a convincing argument for favoring less boilerplate, what are some counterarguments? In other words what are the arguments (if any) in favor of boilerplate?

(I mean what I think is generally meant by boilerplate, but a good example is getters and setters in Java.)

答:
I'm going to take a different tact. Consistency in development is one of the most important features of software design, it's a critical tool in making applications extensible and maintainable but can be difficult to achieve when managing a team across multiple sites, languages and timezones.

If achieved, consistency makes code much more accessible "once you've seen one, you've seen them all", much cheaper to maintain and refactor, but above all, much easier to extend. When you write a library that does require some boilerplate, along with the power of your library you've also given the developer:

A starting point understand the preamble (boilerplate) into your functionality, most key classes and access points will usually feature as part of the boilerplate. This gives developers a starting point into the documentation

Expectations your placing on developers will become apparent, for example if you setup a tracing object as part of the preamble then developers will know where to log exceptions and information

Implicit understanding as you force the developer to go through your process of instantiating classes, they can infer the techniques they will need to access the rest of your library and have the opportunity to introduce them to any conventions you've used throughout your library

Easy validation when your boilerplate code is needed it can usually very easily validate itself with exceptions and guard clauses, preventing consumers from getting stuck much further down the line when you're already committed to a faulty process

Configuration of a library that requires boilerplate code is easy as there is already an obvious implementation point to customise the functionality for a single path of execution. This is particularly useful if your required boilerplate code is enhanced with the Factory or Command pattern

When the consumers of your library have a grip on the instantiation they can easily create private/extension methods, parent classes or even templates to implement the boilerplate code.

Title: A defense for boilerplate?


问:
Scala infix notation
Is it possible to call a method using infix notation?

For example, in Haskell, I could write the following function:

```<code>x `isAFactorOf` y = x % y == 0
</code>```

and then use it like:

```<code>if 2 `isAFactorOf` 10 ...
</code>```

Which in some cases allows for very readable code. Is anything similar to this possible in Scala? I searched for "Scala infix notation", but that term seems to mean something different in Scala.

答:
Essentially, in Scala you can't call a function in an infix manner, but you can define a method on a type, which the left argument can be converted to implicitly. So for your example, you can define a class which has a method isAFactorOf (taking an Int) and indicate that an Int can be implicitly converted to an instance of this class.

If you look at this answer https://stackoverflow.com/a/3119671 to another question, you will see the syntax in Scala which works equivalently.

ContentLicense: CC BY-SA 4.0

Title: Scala infix notation


问:
cross-application text formatting
I am not sure whether this question is a good fit for this site, but if it is not, please let me know and I will take it down.

If it is off-topic, some general info on where I can look for these answers would be greatly appreciated.

I am wondering how the data that determines how text is to be formatted is stored. For example, if I format some text in Bold and Italic in Microsoft Word, I can paste it into google docs and the formatting will stay the same, but If I paste it in here, it will loose its formatting. I am wondering if this is because google docs is aware of the formatting used by Word and it converts it, or if they use the same type of formatting and there is some set of standards.

答:
When you paste it here (TEXTAREA), the browser looks only at the plain text flavor of the clipboard.

When you paste it in google docs ("content editable"), the browser looks at the rich text flavor of the clipboard.

Title: cross-application text formatting


答:
Starting with version 2.10, Scala introduced implicit Classes to handle precisely this issue.

This will perform an implicit conversion on a given type to a wrapped class, which can contain your own methods and values.

In your specific case, you'd use something like this:

```<code>implicit class RichInt(x: Int) {
  def isAFactorOf(y: Int) = x % y == 0
}

2.isAFactorOf(10)
// or, without dot-syntax
2 isAFactorOf 10
</code>```

Note that when compiled, this will end up boxing our raw value into a RichInt(2). You can get around this by declaring your RichInt as a subclass of AnyVal:

```<code>implicit class RichInt(val x: Int) extends AnyVal { ... }
</code>```

This won't cause boxing, but it's more restrictive than a typical implicit class. It can only contain methods, not values or state.

Title: Scala infix notation

Body:
Is it possible to call a method using infix notation?

For example, in Haskell, I could write the following function:

```<code>x `isAFactorOf` y = x % y == 0
</code>```

and then use it like:

```<code>if 2 `isAFactorOf` 10 ...
</code>```

Which in some cases allows for very readable code. Is anything similar to this possible in Scala? I searched for "Scala infix notation", but that term seems to mean something different in Scala.

Body:
Starting with version 2.10, Scala introduced implicit Classes to handle precisely this issue.

This will perform an implicit conversion on a given type to a wrapped class, which can contain your own methods and values.

In your specific case, you'd use something like this:

implicit class RichInt(x: Int) {
  def isAFactorOf(y: Int) = x % y == 0
}

2.isAFactorOf(10)
// or, without dot-syntax
2 isAFactorOf 10

Note that when compiled, this will end up boxing our raw value into a RichInt(2). You can get around this by declaring your RichInt as a subclass of AnyVal:

implicit class RichInt(val x: Int) extends AnyVal { ... }

This won't cause boxing, but it's more restrictive than a typical implicit class. It can only contain methods, not values or state.


问:
Kth Optimal path in a matrix
I had the following question I was trying to solve:

You are given a n*n matrix. Every cell of the matrix contain some value (positive).

You are currently at (0,0) and you have to go to right most and bottom most cell ((n-1)*(n-1)). You can move either right or down.

I am aware of finding the most optimal solution for this using the dynamic programming approach. But what is the best way to find the kth optimal solution?

答:
This is likely not the best way, but given there are no other answers, here is a way.

The problem of finding the k-th optimal path is AFAIK not very well studied for matrices, but is quite common in graphs. In fact, Wikipedia has some examples of how it can be done in a weighted directed graph. Hence a solution that transforms you matrix to a graph
and employs the algorithm from the Wiki:

Algorithm:

Transform your matrix into a weighted directed graph. Every entry in your matrix will be a vertex, and vertex A has an edge to vertex B iff A was above or to the left of B in the matrix. The weight of the edge is the end vertex value.

Now, use Yen's algorithm to find the k-th optimal path. (it's a fairly known, but long algorithm, so not posting it here).

Complexity

Creating the graph is trivial and takes linear time in the size of your matrix. The resulting graph has N^2 vertexes and 2N(N-1) edges. Yen's algorithm requires K*l calls to Dijkstra, where l is the length of the spur paths (In this case it's 2N, since all paths here are at most 2N length).

Hence the total runtime is expected to be O(K * N^3 * log(N)). This is a very pessimistic bound, but you may find that the cubic behaviour is indeed true - this solution does not use any pros from the graph structure being matrix-like.

After thinking about this a bit more:

There is an obvious naive solution that just takes the standard dynamic programming approach, and instead of storing the shortest path to each node stores the k shortest paths.

This solution will be faster than the above, clocking at O(K * N^2). However, it uses O(K * N^2) space, which is much larger than O(N * (K + N)) of the above solution. I guess here you would need to make a decision on what resource is more scarce.

Title: Kth Optimal path in a matrix


问:
How to get people to actually do code reviews promptly?
First things first, our company has decided to do code reviews. All of the engineers agree with (or accept) this. Code reviews are required as part of our development process for all commits. The problem is that they are done... weeks (or occasionally months) after the stories are code complete.

So as a developer, how to get engineers to actually perform the code reviews promptly?

In my situation, I've got some things that hinder what I can do. I work remotely from the rest of the team. The old standby of standing in their cube until they do what I want isn't available. We use kanban, so everyone is on overlapping schedules. And the usual route of getting my manager or project manager to hold people accountable has proven ineffective.

答:
Getting code reviews completely promptly is a management issue, not a technical issue.

That said, and I'll acknowledge this will generate howls of protest, the best way to ensure timely completion is to make timely completion a part of their performance review process.

You'll need / want to have tooling support in order to make it work.  But with a modest amount of effort, it should be possible to generate reports that show how long it took each person to complete their reviews along with how many reviews are being done by whom.

A good management team will use those metrics as a way to improve the overall work environment.  They ought to be able to draw out underlying reasons why people aren't able to complete their reviews on time.

For example, you could see the following sets of excuses:

Excuse: "I'm too busy" or "I don't care"  Answer: Management has a session with that developer and goes over the benefits of code review and why they are important.

Excuse: "I have too many reviews to complete and they are impacting my other deliverables." Answer: Management can see the number of requested reviews and average response time.  If the developer is overloaded, they can work to shift some of that to other developers.

That said, you mentioned:

the usual route of getting my manager or project manager to hold people accountable has proven ineffective

And that's an issue you need to bring up with your manager.  Point out how your ability to deliver is impacted because the code reviews aren't getting completed on time.  Ask her what her preference would be in order to handle future situations where the code can't be committed because the review isn't done.  In short, you have to make it your manager's problem and not yours since you don't have the leverage in order to get the reviews completed.

It wouldn't hurt to do some research and find out if this is a systemic problem that's affecting everyone or if it's impacting just you, presumably because you're remote to the rest of the team.  If it's a systemic issue, then that needs to be addressed and your development process should be adjusted.  If it's an individual issue or an issue for remote workers, then that's useful information to lobby your manager with while proposing appropriate changes to the process.

But the short version is that the reviews will only occur when they are part of the routine, expected process that everyone is held accountable to.  It doesn't sound like that's the case yet for your environment.


问:
Internal api development and committing procedure
I am now on the job of extending and refactoring a set of APIs and core  data structures that most of the other components depend on. The team is small (5 people ).

A manager told me that before checking in my changes, I should search throughout the code base, find out all the functions that are dependent on the APIs I have changed, and if necessary, modify them to make sure the whole software works. I was a bit astonished by this request.

In terms of procedure, I think all I should do is to test my own stuff, document, and provide instructions for others to update accordingly. What makes this request even worse is that I know unit tests are not thoroughly conducted for some components. How can I possibly be sure that my change wouldn't creat bugs in the component of somebody else? And the development is active, it's almost certain my push of changes for somebody else would create local conflicts everywhere.

Before rejecting this request, can anybody provide some other perspective to this request? What is the common practice for internal API update? Thanks.

答:
My trick is to make sure that the compiler is doing allot of the work for you.

I'll mark a method or class as [Obsolete] to find all the places it's used, or simply use the find all references function. the [Obsolete] method is better as this will inform consumers at compile-time that an alternative technique has been provided.

Diagram the APIs classes and structures so you can identify self-contained functionality, helper functions, common themes and dependencies. If possible document the classes that consumers make use of to see how much of the APIs classes/fields/events can be made private or internal without harming the consumers. The smaller the public interface you need to maintain the more flexible you can be in your rework.

It can also be helpful to literally create public interfaces and add them into the API as a first step, subsequently any changes that you need to make to this interface will be reflected in a compiler error and you can easily find the consumers using find all references or similar.

Look for extension points built into the API and make use of them, don't reinvent the wheel or refactor large portions of code.. try to work with the code that's already there as much as possible.

If your using Visual Studio try this addin from Microsoft which can help you find corner cases in a the codebase that might need to be addressed and implement System.Diagnostics.Contracts which can help you find code that falls into those corner cases.

Try to include as many of the critical consumers of the API in the build for the APIs, this way though compilation will take longer, you will be notified at compile time of any issues that have arisen from your changes to the library.

OwnerDisplayName: Feischi


问:
Separate code coverage reports for unit and integration tests, or one report for both?
Should there be a separate code coverage report for unit and integration tests, or one code coverage report for both?

The thinking behind this is that code coverage allows us to make sure that our code has been covered by tests as far as possible (as much as a machine can now anyway).

Having a separate report is more convenient for us to know what has not been covered by unit tests, and what has not been covered by integration tests. But this way we cannot see the total coverage percentage.

答:
You don't mention your testing tool. Many have "combine" functions that let you aggregate the results of multiple runs or suites. If you want an aggregate coverage metric, explore the combine feature in your coverage tool.

Now, can we talk about the elephant in the room?

There is no spoon. And there is no "total coverage percentage." At least, no simple one.

Coverage percentage is a readily-comprehended metric presented to help understand the scope, depth, and range of testing suites. But like any simple benchmark, it's very easy to become target fixated on this value as some sort of magical talisman of "complete testing."

Let's say you have achieved the glory of "100% test coverage." Yay! But what does that mean? 100% of code lines are tested, right? Then what about this line?

```<code>launch_missile = launch_authorized and launch_cmd_given else previous_launch_status
</code>```

"Covering" that line means something--but not a whole lot, because there are a variety of conditions which are True or False with some probability, but it's unlikely that you have tested all of the combinations of those conditions. Even if that line is covered a dozen times, if one of the conditions is relatively uncommon, you haven't come close to testing all of the real results that might occur in practice. To make that clearer, a more synthetic example:

```<code>engage_laser = (laser_armed and safety_disengaged) or random.random() < 0.0000003
</code>```

How many times would you have to cover that line to really exhaustively test it? How many times would you have to cover it to test it in combination with all of the other variables in the program (with their own, possibly similarly rare) probabilities?

I'm not saying that coverage metrics are useless. They're actually great. They focus on one of the key issues: How extensively is my software system tested? They help move from "we have some tests" to "we have thoroughly tested."

But while you're working on "combined scores," the reality is that your score will typically be for "statement coverage" rather than "condition," "predicate," or "path" coverage. So whatever number your aggregate scores give you, it's unlikely that it's giving you a true picture of how much of your program potential states and state combinations are being tested. While you're working on increasing your coverage percentage, consider also measuring your predicate coverage. It will give you a more realistic--and almost invariably, a more sobering--view of test extensiveness.

Body:
You don't mention your testing tool. Many have "combine" functions that let you aggregate the results of multiple runs or suites. If you want an aggregate coverage metric, explore the combine feature in your coverage tool.

Now, can we talk about the elephant in the room?

There is no spoon. And there is no "total coverage percentage." At least, no simple one.

Coverage percentage is a readily-comprehended metric presented to help understand the scope, depth, and range of testing suites. But like any simple benchmark, it's very easy to become target fixated on this value as some sort of magical talisman of "complete testing."

Let's say you have achieved the glory of "100% test coverage." Yay! But what does that mean? 100% of code lines are tested, right? Then what about this line?

launch_missile = launch_authorized and launch_cmd_given else previous_launch_status

"Covering" that line means something--but not a whole lot, because there are a variety of conditions which are True or False with some probability, but it's unlikely that you have tested all of the combinations of those conditions. Even if that line is covered a dozen times, if one of the conditions is relatively uncommon, you haven't come close to testing all of the real results that might occur in practice. To make that clearer, a more synthetic example:

engage_laser = (laser_armed and safety_disengaged) or random.random() < 0.0000003

How many times would you have to cover that line to really exhaustively test it? How many times would you have to cover it to test it in combination with all of the other variables in the program (with their own, possibly similarly rare) probabilities?

I'm not saying that coverage metrics are useless. They're actually great. They focus on one of the key issues: How extensively is my software system tested? They help move from "we have some tests" to "we have thoroughly tested."

But while you're working on "combined scores," the reality is that your score will typically be for "statement coverage" rather than "condition," "predicate," or "path" coverage. So whatever number your aggregate scores give you, it's unlikely that it's giving you a true picture of how much of your program potential states and state combinations are being tested. While you're working on increasing your coverage percentage, consider also measuring your predicate coverage. It will give you a more realistic--and almost invariably, a more sobering--view of test extensiveness.


答:
In the specific example given this would work:

```<code>if ( abs( foo() - 1.5 ) == 0.5 )
</code>```

This works for two number values, but for the obvious reasons is not very easy to generalise

Title: PHP conditional test func call against two values

Body:
I was wondering if there's a one liner for PHP that would allow me test multiple  values against a function call. As example, say I want to test if foo() returns either 1 or 2, (in pseudo code)

```<code>if( [1||2]==foo() );
</code>```

Maybe above is a bad example of what I mean. Currently if I want to test two values against a function call I would use:

```<code>$test = foo();
if( 1==$test || 2==$test );
</code>```

Its these two lines that I would like to simplify into one

Body:
In the specific example given this would work:

if ( abs( foo() - 1.5 ) == 0.5 )

This works for two number values, but for the obvious reasons is not very easy to generalise


答:
Above all, you need to have and analyse combined (total) coverage. If you think of it, this is the most natural way to properly prioritize your risks and focus your test development effort.

Combined coverage shows you what code is not covered by tests at all, ie is most risky and need to be investigated first. Separate coverage reports won't help here, as these don't let you find out if the code is tested somehow else or not tested at all.

Separate coverage analysis also can be useful, but it would better be done after you're done with combined analysis and preferably would also involve results of analysing combined coverage.

Purpose of separate coverage analysis differs from combined one. Separate coverage analysis helps to improve design of your test suite, as opposed to analysis of combined coverage which is intended to decide on tests to be developed no matter what.

"Oh this gap isn't covered just because we forgot to add that simple unit (integration) test into our unit (integration) suite, let's add it" -- separate coverage and analysis is most useful here, as combined one could hide gaps that you would want to cover in particular suite.

From above perspective, it is still desirable though to also have results of combined coverage analysis in order to analyse trickier cases. Think of it, with these results, your test development decisions could be more efficient due to having information about "partner" test suites.

"There's a gap here, but developing a unit (integration) test to cover it would be really cumbersome, what are our options? Let's check combined coverage... oh it's already covered elsewhere, that is, covering it in our suite isn't critically important."

Title: Separate code coverage reports for unit and integration tests, or one report for both?

Body:
Should there be a separate code coverage report for unit and integration tests, or one code coverage report for both?

The thinking behind this is that code coverage allows us to make sure that our code has been covered by tests as far as possible (as much as a machine can now anyway).

Having a separate report is more convenient for us to know what has not been covered by unit tests, and what has not been covered by integration tests. But this way we cannot see the total coverage percentage.


问:
Copyrights for Open Source projects
Say I'm developing a piece of Open Source software (BSD-Like permissive license) and I write the initial release entirely on my own. After the initial release however I would like numerous other developers to contribute. How do I deal with the Copyright of this project? Obviously I completely own the first version, but how do I handle the Copyrights of these contributors?

I've seen projects where at the top of a source file there will be a Copyright notice acknowledging the one who originally wrote that source file and maybe a partner, with many contributors I don't see this as maintainable though, anyone could patch minor or major parts of that file, how would you handle this?

I've also seen projects that at the top of their source files say something along the lines of:

```<code>Copyright (C) The ExampleProject Developers, see CONTRIBUTORS
</code>```

In the CONTRIBUTORS file in the root directory there is a list of contributors to the project, I see this as more manageable as the first, but I'm not quite sure if this is suitable.

Another similar system I've seen is that at the top of the source files it will say

```<code>See LICENSE for details
</code>```

then in the LICENSE file they have a big long list of contributor Copyrights, then the actual license following it.

I have also seen projects where the original author maintains copyright over the entire project, how does that happen?

What do you suggest the best way to do things now is? I don't want people to have second thoughts about contributing to the project because I'm handling ownership and credit all wrong, how do larger projects (that don't ask for Copyrights to be signed over) handle things like this?

Thanks for any information, I'm having trouble figuring out how I should release my project.

答:
So let's take a look at first clause in the BSD 2-clause license template.

Copyright (c) ,
  All rights reserved.

  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

And the phrase to focus on is this:

Redistribution and use in source and binary forms, with or without modification, are permitted

That part is important because the Copyright Owner is using the BSD license to allow a licensee to do whatever they want with the code that is owned by the Copyright Owner.  In effect, it grants unrestricted use1 to the licensee.

In other words, the BSD license means the Copyright owner is effectively giving away their code for the world to use as it pleases.

1 Unrestricted in the sense that conditions imposed by the license are trivial to comply with and don't impact code usage.

So what does that mean for your project?

how do I handle the Copyrights of these contributors?

You don't necessarily need to.  The BSD license means they're giving away their code too.  If you're really worried about it though, you could have them assign copyright ownership to the project.

In the CONTRIBUTORS file in the root directory there is a list of contributors to the project, I see this as more manageable as the first, but I'm not quite sure if this is suitable.

The older BSD 3-clause license effectively required this.  It was a neat idea at first, and then everyone realized what a pain it was to maintain when you have lots of contributors.  That's why the 2-clause version is preferred to the 3-clause version of the BSD license.

I have also seen projects where the original author maintains copyright over the entire project, how does that happen?

You have all contributors assign copyright ownership to the project prior to accepting their changes into the codebase.

Note that since you're releasing this under a BSD license, there's nothing to stop potential contributors from forking your project in order to bypass assigning copyright ownership.

Your last set of questions is harder to answer because it's a fairly broad question.

What do you suggest the best way to do things now is? I don't want people to have second thoughts about contributing to the project because I'm handling ownership and credit all wrong, how do larger projects (that don't ask for Copyrights to be signed over) handle things like this?

If you release under the BSD license, then I don't think you need to worry about assigning Copyright.  All future recipients of the code can use the code as they see fit, which also includes re-releasing the project under different license terms.  Notably, GPL'd projects can assimilate BSD licensed projects without any legal problems.

You may also be worried about a bitter contributor attempting to take your project down at a later point in time via a DMCA request.  Again, given that you're releasing under the BSD license, which has minimal restrictions within it, you're not likely to have a problem here.  You and your project can likely brush off DMCA claims by pointing out that the contributor freely released their contributions.

Since you're using a BSD license to release under, I think you may be over-analyzing this aspect of your project.  Don't worry about formal copyright ownership assignment unless you have a compelling reason to do so.

Title: Copyrights for Open Source projects


答:
In the classic version(k = 1, solve for best path), the key insight used is as follows.

1) In computing best path for cell (i, j) (best[i][j] is the cost of best path from top-left to (i, j)), we notice that this path could either come from it's left or upper neighbor. Thus we do (leaving aside corner cases for a moment)

```<code>best[i][j] = min(best[i][j-1], best[i-1][j]) + value[i][j]
</code>```

2) Now, if we want to compute k best paths from top-left corner to (i, j), we can again follow a similar, but more general technique. Here, best[i][j] can be thought of as a list of k best paths instead of one best path.

```<code>best[i][j] = merge_and_select_k(best[i-1][j], best[i][j-1], k)
</code>```

merge_and_select_k takes two input lists, an integer k - It concatenates the two lists and keeps only the k best values. Of course, you must also add value[i][j] to all these selected items.

3) Loop over the matrix, just like in the classic version and compute best[i][j] for every i and j. Your final result is best[n][n][k].

4) This works because, we only need to consider best[i-1][j] and best[i][j-1] for computing best[i][j]. Time complexity is O(k * n * n) and space complexity is O(k * n), as we only need keep the values for current and previous rows.

Title: Kth Optimal path in a matrix

Body:
I had the following question I was trying to solve:

You are given a n*n matrix. Every cell of the matrix contain some value (positive).

You are currently at (0,0) and you have to go to right most and bottom most cell ((n-1)*(n-1)). You can move either right or down.

I am aware of finding the most optimal solution for this using the dynamic programming approach. But what is the best way to find the kth optimal solution?

Body:
In the classic version(k = 1, solve for best path), the key insight used is as follows.

1) In computing best path for cell (i, j) (best[i][j] is the cost of best path from top-left to (i, j)), we notice that this path could either come from it's left or upper neighbor. Thus we do (leaving aside corner cases for a moment)

best[i][j] = min(best[i][j-1], best[i-1][j]) + value[i][j]

2) Now, if we want to compute k best paths from top-left corner to (i, j), we can again follow a similar, but more general technique. Here, best[i][j] can be thought of as a list of k best paths instead of one best path.

best[i][j] = merge_and_select_k(best[i-1][j], best[i][j-1], k)

merge_and_select_k takes two input lists, an integer k - It concatenates the two lists and keeps only the k best values. Of course, you must also add value[i][j] to all these selected items.

3) Loop over the matrix, just like in the classic version and compute best[i][j] for every i and j. Your final result is best[n][n][k].

4) This works because, we only need to consider best[i-1][j] and best[i][j-1] for computing best[i][j]. Time complexity is O(k * n * n) and space complexity is O(k * n), as we only need keep the values for current and previous rows.


问:
Choosing a random integer in a range such that it doesn't equal a particular number
Given an integer range and a number within that range, what's a reasonably robust and efficient way to randomly select a new number within the range such that it's not equal to the given number?

Whenever I need to do this, I usually use something like:

```<code>// Randomly choose an integer within an inclusive range with the condition
// that the result not equal the previous number chosen
// INPUT: lastNum is an int in the range [minVal, maxVal]
int ChooseNewNumber(lastNum){

    minVal = 0;
    maxVal = N; // This would usually be a value like someContainer.size - 1
    intervalLength = maxVal - minVal + 1;

    // Assume RandomInt...() is an existing function that lives up to its name
    int newNum = RandomIntWithinInclusiveRange(minVal, maxVal);

    if (newNum == lastNum){
        // Add a random offset to newNum and wrap around if necessary
        newNum = (newNum+RandomIntWithinInclusiveRange(1, intervalLength - 1)) % (maxVal+1);
    }

    return newNum;
}
</code>```

This works and it seems to avoid the introduction of any bias in the newNum == lastNum case, but it's a bit clunky. Is there a cleaner way to accomplish the same thing?

EDIT: as coredump pointed out, the method above fails if minVal != 0. Just for reference, the line:

```<code>newNum = (newNum+RandomIntWithinInclusiveRange(1, intervalLength - 1)) % (maxVal+1);
</code>```

should be:

```<code>new = ((new + RandomIntWithinInclusiveRange(1, intervalLength - 1) - minVal) % intervalLength) + minVal;
</code>```

I realize this mistake gave the impression that minVal might always be 0; sorry about that.

答:
Just take a number in the range [minVal, maxVal-1] and add 1 if it is greater or equal to lastNum

```<code>int ChooseNewNumber(lastNum){
    minVal = 0;
    maxVal = N;
    if(minVal > lastNum || lastNum > maxVal){
        //if lastNum is outside range then just take full range
        return RandomIntWithinInclusiveRange(minVal, maxVal);
    }
    random = RandomIntWithinInclusiveRange(minVal, maxVal-1);
    if(lastNum <= random) random++;
    return random;
}
</code>```

Body:
Just take a number in the range [minVal, maxVal-1] and add 1 if it is greater or equal to lastNum

int ChooseNewNumber(lastNum){
    minVal = 0;
    maxVal = N;
    if(minVal > lastNum || lastNum > maxVal){
        //if lastNum is outside range then just take full range
        return RandomIntWithinInclusiveRange(minVal, maxVal);
    }
    random = RandomIntWithinInclusiveRange(minVal, maxVal-1);
    if(lastNum <= random) random++;
    return random;
}


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
An extra level of indirection.

You don't want to care whether the object you're using is a Cat or a Dog, so you go through a virtual function table to find the right makeNoise() function.

I'm sure this could be applied to 'lower' and 'higher' levels as well - think of a compiler looking up the right instruction to use for a given processor or Haskell's Monads abstracting over computational effects by calling everything return and >>=.

Title: What is abstraction?


答:
It sounds like the big concern of your manager is to make sure the software is always in a working state in the repository. This is not an unreasonable request, as they could pull and compile it for release at any point, and they would want to be confident they are not releasing a bad build.

Your manager proposed one option, but this option has the problems you cited. You have to search the entire code base for calls into the API (which may not be 100% reliable). You have to edit code under active development by other teams, which can lead both to merge conflicts and interpersonal conflicts. You will be trying to refactor code that you may not totally understand (and don't have the backing of tests for). This approach can lead to... challenges.

There are other options. For example, it might make sense to refactor the old API into an adapter for the new API. This way, the new code is being called internally, while externally no one should need to change their code immediately. Over time, you can convert over by working with the other developers, not around them, all while keeping the code fully functional.

A benefit to this is that you could add in logging to the old API calls to find out where those calls are being made from, and how often they are being called. This way, you can prioritize certain areas for conversion while not having to change over everything at once.

This strategy wouldn't be without its challenges. For example, you might have naming conflicts between the two APIs. Developing a versioning scheme for your API will help, and will alleviate this problem in the future. You will need to support both APIs for a time. Since the old API will simply wrap the new API, changes should mostly fall on the new API. You may have to hack around incompatibilities (deprecated data structures, etc). This is par for the course, but it would limit this problem to a single place within your direct control.

Title: Internal api development and committing procedure

Body:
I am now on the job of extending and refactoring a set of APIs and core  data structures that most of the other components depend on. The team is small (5 people ).

A manager told me that before checking in my changes, I should search throughout the code base, find out all the functions that are dependent on the APIs I have changed, and if necessary, modify them to make sure the whole software works. I was a bit astonished by this request.

In terms of procedure, I think all I should do is to test my own stuff, document, and provide instructions for others to update accordingly. What makes this request even worse is that I know unit tests are not thoroughly conducted for some components. How can I possibly be sure that my change wouldn't creat bugs in the component of somebody else? And the development is active, it's almost certain my push of changes for somebody else would create local conflicts everywhere.

Before rejecting this request, can anybody provide some other perspective to this request? What is the common practice for internal API update? Thanks.


问:
Early destruction of objects in c++
I am not sure if this is the right forum of this question, but I will try here since this question about the c++ language. The problem:

I use one global variable in my code which is a graphics object. The thing is that when I shut down the program I tried to delete all the created objects (in a function called close, since I wanted to finish some processes from an C API as well). However, when I deleted that global graphics object I got a memory access violation error at the end of main. The reason for this was that the destructor was called again when main ended. This was something that I was not aware of. This led me to the for this program completely irrelevant (since I still wanted to keep the variable until the GUI closed), but for c++ programming really relevant question; Is it impossible to destroy a global c++ object before the end of main?

However, I read this

Static: Objects declared in global or namespace scope (§6.3.4) and statics declared in func- tions (§12.1.8) or classes (§16.2.12) are created and initialized once (only) and ‘‘live’’ until the program terminates (§15.4.3). Such objects are called static objects. A static object has the same address throughout the life of a program execution. Static objects can cause serious problems in a multi-threaded program because they are shared among all threads and typically require locking to avoid data races (§5.3.1, §42.3)

However, though versions of this text appear all over on the internet my question is not completely answered by this explanation. Though it may be implied, since global variables always seem to be static it would be nice to have a straight out answer.

答:
However, though versions of this text appear all over on the internet my question is not completely answered by this explanation. Though it may be implied, since global variables always seem to be static it would be nice to have a straight out answer.

If you didn't explicitly create it, you don't need to explicitly destroy it.
Let's just remove some of the words from your standard quote:

Static: Objects declared in global or namespace scope (§6.3.4) ... are created and initialized once (only) and ‘‘live’’ until the program terminates (§15.4.3). Such objects are called static objects.

So, if you declare an object with global or namespace scope, it is static, and its lifetime is roughly the program lifetime.

By analogy, consider normally-scoped local variables:

```<code>void foo() {
    std::string s;
    // code
}
</code>```

now there is no way to destroy s without exiting its enclosing scope. If you explicitly destroy it in-place, the destructor will still be called again when the scope exits.

Now, consider global and namespace scope to be the top-level scope of your program. You enter this scope before main (which is nested inside the global scope) and exit it after leaving main. This top-level scope lives exactly as long as the program, and you're no more able to destroy the its objects early than you are objects in any other scope.

There is some subtlety about exactly when the constructor gets called (generally before main starts, with a fudge to allow dynamically-loaded libraries without having to talk about platform specifics), when the destructor gets called (relative to exit handlers, say), and the relative ordering of these for different statics (not well-defined, so don't make global initialization or destruction depend on other globals).

Of course, if you want the object to be global for convenience, you can still choose to have explicit setup/cleanup calls instead of using the ctor/dtor for this.

Title: Early destruction of objects in c++

Body:
However, though versions of this text appear all over on the internet my question is not completely answered by this explanation. Though it may be implied, since global variables always seem to be static it would be nice to have a straight out answer.

If you didn't explicitly create it, you don't need to explicitly destroy it.
Let's just remove some of the words from your standard quote:

Static: Objects declared in global or namespace scope (§6.3.4) ... are created and initialized once (only) and ‘‘live’’ until the program terminates (§15.4.3). Such objects are called static objects.

So, if you declare an object with global or namespace scope, it is static, and its lifetime is roughly the program lifetime.

By analogy, consider normally-scoped local variables:

void foo() {
    std::string s;
    // code
}

now there is no way to destroy s without exiting its enclosing scope. If you explicitly destroy it in-place, the destructor will still be called again when the scope exits.

Now, consider global and namespace scope to be the top-level scope of your program. You enter this scope before main (which is nested inside the global scope) and exit it after leaving main. This top-level scope lives exactly as long as the program, and you're no more able to destroy the its objects early than you are objects in any other scope.

There is some subtlety about exactly when the constructor gets called (generally before main starts, with a fudge to allow dynamically-loaded libraries without having to talk about platform specifics), when the destructor gets called (relative to exit handlers, say), and the relative ordering of these for different statics (not well-defined, so don't make global initialization or destruction depend on other globals).

Of course, if you want the object to be global for convenience, you can still choose to have explicit setup/cleanup calls instead of using the ctor/dtor for this.


问:
How much business logic should be allowed to exist in the controller layer?
Sometimes we have some business logic represented in the controller code of our applications. This is usually logic that differentiates what methods to call from the model and/or what arguments to pass them.

Another example of this is a set of utility functions that exist in the controller that may work to format or sanitize data returned from the model, according to a set of business rules.

This works, but I am wondering if its flirting with disaster. If there is business logic shared between controller and model the two layers are no longer separable, and someone inheriting the code may be confused by this unevenness in location of business logic related code.

My question is how much business logic should be allowed in the controller and in what circumstances, if any?

答:
Like many other interesting concepts in programming, MVC is a powerful paradigm to bring structure and focus to a family of close or similar strategies to implement certain scenarios.

Like many other programming concepts, MVC simplifies reality, discards small details and provides a crude wireframe model to follow. Like many other simplifications of reality it does it job ny bringing stucture into chaos as seen by a human mind.

Still, like many other programming concepts, MVS is just a simplification of reality. It's not perfect and it's not thorough. Which is why it is not possible to fit a real world scenario into a oversimplified model. Hence arise many questions similar to this one.

How much logic should go into a controller?

Whether a view should contain any conditional logic?

Whether a model should contain any additional data not found directly in business entities?

These are all questions born in an attempt to adjust the code to fit the conceptual idea of MVC precisely and completely.

My answer to you is don't try to. MVC provides structure. Build your application around this foundation but don't expect it to fit perfectly. There will be deviations, it's normal. Just watch to keep them under control.


问:
Use cases and usage patterns of futures vs callbacks
I've become interested in futures lately, mostly due to their inclusion in standard C++ - but I see there is an active debate over futures vs. callbacks in many programming areas, such as Node.js.

I'd like to ask is if there are any well-known patterns/use-cases where futures provide a clear advantage (in terms of readability and ease of implementation) to callbacks?

We all know the main downsides associated with callbacks: indirection in terms of reading the code, and the potentially deeply nested and confusing lambdas in languages like Javascript.

The advantage of using futures is they eliminate the code indirection and let you write code in a "synchronous" style, but provide you with a handler that lets you check on the status of some background operation.  In that sense, I don't think it would be too subjective/controversial to claim that futures are a better syntactic fit with how the human mind tends to think (do this, do that, do this while waiting for that, etc).

However, when I actually use futures in practice, I often run into the following issue:

A typical use case for futures is where you manage many async operations via an array of future objects, like a vector<future> futures (using C++ syntax).  I think a key insight is that futures require that you actively check each async operation to see if it's done, whereas with callbacks you passively wait for each event to complete.  But since, in the general case, you have no way of knowing which event will complete first, you may lose out on some parallelism if you're iterating over an array of futures and future[10] finishes 5 seconds before future[0], but you're sitting there waiting for future[0] to complete.

We can mitigate this with a "wait_for" type of operation - instead of waiting on each future, we can wait for a certain short interval, and then proceed to continue iterating.  But this is basically like busy waiting, consuming extra CPU resources.  With callbacks, you wouldn't need to do any of this because callback code is invoked passively by some background event reactor.  Basically, by iterating over an array of futures in application code, you're sort of "re-implementing" a poll event reactor at a higher level.

One straightforward use case for futures I've found is any situation where you have one or more async calls, and you can interleave some CPU cycles between calls.  Suppose you have to call an HTTP web service twice, but the result of the first call gives you the opportunity to start processing immediately without the need to wait for the second call to complete.  Futures make this easy, because you can just say:

```<code>future result1 = some_remote_call();
object data = result1.get(); // wait for result1 to complete

future result2 = another_remote_call();

// ... do some processing here while we're still waiting on result2 ... //
</code>```

So that's definitely a nice use case, but the more common case of waiting for N events to occur seems better suited for callbacks, despite the code-indirection we suffer using callbacks.

So, what are some well-known usage patterns/use-cases where futures provide a clear advantage (in terms of code readability and ease of implementation) over callbacks?

答:
What you need to understand is that the C++ standard library quite possibly has the worst implementation of futures conceivable by man.  What C++ does is little more than a weak wrapper around a semaphore.  Most future implementations encourage use of callback lambdas extensively, to chain several futures together asynchronously using then, and allow you to easily create a single future that is based on a collection of other futures.  They have none of the issues you are raising here.

Look at Q for one of the best implementations, to see how futures were really designed to be used.  If you search around, there are people bringing those ideas into C++.  It's not terribly difficult to implement yourself.


问:
Paid software includes MIT licensed library, does that put my app under MIT too?
If I include MIT licensed source code in my program, am I obliged to provide my whole software under MIT?

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

How is "substantial" determined?  The wording is not very specific.

答:
You're not obliged to provide your whole software under MIT. The MIT license is a non-infectious license. If you include MIT licensed software in your software, it will not extend onto your software (unlike GPL). Only those parts of the software which were MIT before, and modifications made to those parts, are to stay under MIT license, nothing else.

Substantial is not very well defined, that's right, but a valid assumption is "substantial" == "subject to copyright". Means, if you copy a for-loop iterating over an array instead of typing it yourself, that's not substantial. Anything more than that can pretty soon become substantial.

As soon as you use substantial portions, you have to include the MIT license as part of your license, i.e. mention "This software includes parts of XYZ under MIT license ...", reproduce the license, obey to the license conditions as well as request your customers to obey to the license conditions.

Disclaimer: I'm not a lawyer, consult a lawyer.


答:
Just choose between 1 and N and return 0 if the value is lastNum.

```<code>int ChooseNewNumber(lastNum){
    random = RandomIntWithinInclusiveRange(1, N);
    if (random == lastNum) {
        return 0;
    }
    return random;
}
</code>```

Or the shorter version, if you prefer:

```<code>int ChooseNewNumber(lastNum){
    random = RandomIntWithinInclusiveRange(1, N);
    return (random == lastNum ? 0 : random);
}
</code>```

The generic answer (EDIT)

There was a little confusion about why I did actually wrote 0 and 1 instead of minVal and maxVal. For my defense, I found the original question equally confusing ;-) (cf. comment).
Here is a modified version, with those variables given as parameters and with all assumptions explicitly checked:

```<code>int ChooseNewNumber(minVal, maxVal, lastNum){

    assert(minVal =< lastNum);
    assert(lastNum =< maxVal);
    assert(minVal < maxVal); /* there is at least one value */

    random = RandomIntWithinInclusiveRange(minVal, maxVal);
    return (random == lastNum ? (minVal + 1) : random);
}
</code>```

Note however that since lastNum is supposed to be the last number picked, we could safely assume that it belongs to the intended interval.

Below, I still assume that minVal is 0 and maxVal is N, which makes sense in my example and keeps the explanation simpler.

Explanation

Image a deck of 4 cards:

```<code>ABXD
</code>```

X is at position lastNum.

Then, you want to pick only A,B or D.

This is equivalent to picking a random card in this set,

```<code>XBAD
</code>```

... where you would swap lastNum and 0 and choose an element between 1 and N.

But in fact, you can do this without actually swapping elements.

Title: Choosing a random integer in a range such that it doesn't equal a particular number

Body:
Given an integer range and a number within that range, what's a reasonably robust and efficient way to randomly select a new number within the range such that it's not equal to the given number?

Whenever I need to do this, I usually use something like:

```<code>// Randomly choose an integer within an inclusive range with the condition
// that the result not equal the previous number chosen
// INPUT: lastNum is an int in the range [minVal, maxVal]
int ChooseNewNumber(lastNum){

    minVal = 0;
    maxVal = N; // This would usually be a value like someContainer.size - 1
    intervalLength = maxVal - minVal + 1;

    // Assume RandomInt...() is an existing function that lives up to its name
    int newNum = RandomIntWithinInclusiveRange(minVal, maxVal);

    if (newNum == lastNum){
        // Add a random offset to newNum and wrap around if necessary
        newNum = (newNum+RandomIntWithinInclusiveRange(1, intervalLength - 1)) % (maxVal+1);
    }

    return newNum;
}
</code>```

This works and it seems to avoid the introduction of any bias in the newNum == lastNum case, but it's a bit clunky. Is there a cleaner way to accomplish the same thing?

EDIT: as coredump pointed out, the method above fails if minVal != 0. Just for reference, the line:

```<code>newNum = (newNum+RandomIntWithinInclusiveRange(1, intervalLength - 1)) % (maxVal+1);
</code>```

should be:

```<code>new = ((new + RandomIntWithinInclusiveRange(1, intervalLength - 1) - minVal) % intervalLength) + minVal;
</code>```

I realize this mistake gave the impression that minVal might always be 0; sorry about that.

Body:
Just choose between 1 and N and return 0 if the value is lastNum.

int ChooseNewNumber(lastNum){
    random = RandomIntWithinInclusiveRange(1, N);
    if (random == lastNum) {
        return 0;
    }
    return random;
}

Or the shorter version, if you prefer:

int ChooseNewNumber(lastNum){
    random = RandomIntWithinInclusiveRange(1, N);
    return (random == lastNum ? 0 : random);
}

The generic answer (EDIT)

There was a little confusion about why I did actually wrote 0 and 1 instead of minVal and maxVal. For my defense, I found the original question equally confusing ;-) (cf. comment).
Here is a modified version, with those variables given as parameters and with all assumptions explicitly checked:

int ChooseNewNumber(minVal, maxVal, lastNum){

    assert(minVal =< lastNum);
    assert(lastNum =< maxVal);
    assert(minVal < maxVal); /* there is at least one value */

    random = RandomIntWithinInclusiveRange(minVal, maxVal);
    return (random == lastNum ? (minVal + 1) : random);
}

Note however that since lastNum is supposed to be the last number picked, we could safely assume that it belongs to the intended interval.

Below, I still assume that minVal is 0 and maxVal is N, which makes sense in my example and keeps the explanation simpler.

Explanation

Image a deck of 4 cards:

ABXD

X is at position lastNum.

Then, you want to pick only A,B or D.

This is equivalent to picking a random card in this set,

XBAD

... where you would swap lastNum and 0 and choose an element between 1 and N.

But in fact, you can do this without actually swapping elements.


问:
Software License change after version change
I used a open source software to build an application about few months back. The license on the software states,

"XXXYYY is Free Software, licensed under the MIT license - so it's free to use for all purposes."

MIT license says that - http://opensource.org/licenses/MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software."

All this happened few months back.

I visited the software's site now and it says that the software has been updated & is under Creative Commons license and that I need to pay a price to use it in my application.

https://creativecommons.org/licenses/

My application still uses the older version of the software with the MIT license. What should I do? Should I license the software?

I agree that I must pay the developer who created the software, but the only reason I chose this software over other alternatives was that it is totally open source & customizable + free.

答:
So long as you keep using the version of the software which was released under the MIT licence, you don't need to do anything: nobody, not even the copyright holder can revoke the licence you received.

Of course, if you want to update to the newer CC-licenced version of the software, you would have to comply with whatever terms that version of the software was released under - or in your case, pay the licencing fee.


问:
Creating a calendar/planner program. Confused about OO logic?
I'd like to create a piece of software that has the functionality of a common written planner. To do this, it will have a Calendar. When planning the program, I became confused as to how I would implement the functionality of a Calendar.

I thought have a Calendar class that stores and array of Date objects, and each Date object contains event or task objects, and so on. But a Calendar has infinite dates, and of course I can't make an object for every date and store it in an array.

How would I go forward with the object oriented software design of a Calendar program. I am talking about software design and how to handle the data, not UI design. I am using Java, but these concepts are universal.

答:
The basic class in such an app will be an "Appointment" or "Event" class. It will contain the date/time and place of the meeting, who will be there, whether a reminder alarm should sound, whether the event repeats... All that sort of stuff.

There should also be some sort of AppointmentCollection class that holds all the appointments, allows appointments to be added and deleted, as well as having the ability of doling out appointments based on certain parameters.

That way, the month view can display all the appointments for its month by asking the AppointmentCollection to give it an array of all the appointments that will transpire during that month, the day view can ask for all the appointments that will happen that day, etc...

OwnerDisplayName: Connorelsea


答:
Short answer: No, MIT licenses do not obligate you to release your code as MIT.

Long answer:

Let's take a look at the MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

And let's look at the heart of it:

to deal in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software

In layman's terms, software that is licensed with the MIT license is saying "use this any way you wish."  And the only exception is that you need to abide by and include their disclaimer of warranty if you keep their portion of code under the MIT license.

So let's say you want to take an MIT library and re-release it as only a GPL library.  You can most certainly do that, and the FSF has provided notes: 1 and 2 on that exact subject.

Note that you didn't make any change at all whatsoever to the project except to claim ownership of your fork of the project that you then released as GPL.  But also note that you cannot restrict others from continuing to distribute the original project as MIT.  You can also restrict them from distributing your project as something other than GPL.

But what about that disclaimer of warranty and copyright notice?

You cannot take away someone's copyright to a creation they own.  And even though you legally claimed ownership of the code (as explicitly permitted by the MIT license), you should include a notice to the effect of "portions of this code were originally created by such and such" and state the date of their claim to copyright.  But you don't necessarily have to do so since you've re-licensed their project and assumed liability.

And what about the warranty statement?  Since you re-licensed their project, you assumed liability for the distribution of that code.  If you re-license, you better choose the new license terms carefully or be prepared to service warranty claims that may get raised.

So this example isn't the free lunch you thought it might be.  By re-licensing, you're taking on liability and responsibility for the project that you may not want.  It's something you have to think through and decide upon.

Another thing you need to consider in this example is that you can't use the reputation of the MIT licensed code as a supporting mechanism for your re-licensed version of the code unless you abide by the conditions of the MIT license - which are to include their copyright and include their disclaimer of warranty.  If you incorporate it and re-license it, then it's your's and not their's.  So you can't use their reputation for your benefit.  At least not without noting the sub-module licensed under the MIT license.

Bringing all of that back around: using MIT licensed code in your project doesn't force you to use the MIT license for your project.  And you can even completely incorporate the MIT licensed code within your project without any viral effect.

Title: Paid software includes MIT licensed library, does that put my app under MIT too?

Body:
If I include MIT licensed source code in my program, am I obliged to provide my whole software under MIT?

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

How is "substantial" determined?  The wording is not very specific.