问:
Picking m number in the best possible time
Imagine we want to pick m numbers from n numbers so that the difference of the maximum and minimum of the m numbers be minimum, for example if

m = 4

  n =6

  numbers: 10 12 10 7 5 22

The minimum difference is 5, picking 5, 7, 10, 10 from the numbers.

the first thing that pops into mind is to sort the numbers and pick the n number which has the minimum difference through looping on an m sized window on the n numbers.

I was wondering if there would be a way to do this in a time order less than O(nlogn), maybe through dynamic programming?

EDIT : The m numbers doesn't matter, the only thing the problem wants is the minimum difference (e.g. 5 for the provided example)

答:
As said in another answer, worst case better than O (n log n) is not possible. You can obviously try to be better in some or many cases.

Calculate the minimum and maximum. Then calculate a bucket size so that any optimal group must belong completely to two consecutive buckets, and distribute the values into that number of buckets.

That should work quite well with random data.


问:
Intersection of geometric entities
I was trying to design a small C++ geometric API for learning purposes, but came across a problem when dealing with intersections of geometric entities. For example, the intersection of a line and a sphere can have three different types: a couple of points, a point or nothing at all. I found several ways to deal with this problem, but I don't know which of them seems to be the best:

CGAL Object return type

I first tried to see what was done in other geometric libraries. The most complete I can found was CGAL. In CGAL, intersection functions return an Object which is a generic type that can hold anything (like boost::any). Then, you try to assign the Object to a value of another type, here is an example:

```<code>void foo(CGAL::Segment_2<Kernel> seg, CGAL::Line_2<Kernel> line)
{
    CGAL::Object result;
    CGAL::Point_2<Kernel> ipoint;
    CGAL::Segment_2<Kernel> iseg;

    result = CGAL::intersection(seg, line);
    if (CGAL::assign(ipoint, result)) {

        // handle the point intersection case.

    } else if (CGAL::assign(iseg, result)) {

        // handle the segment intersection case.

    } else {

       // handle the no intersection case.
    }
}
</code>```

By the way, the assign function uses dynamic_cast to check whether the two variables are assignable (everybody loves RTTI).

Union return type

A union can also be used as a return type, but it means using an id for every geometric type and having some kind of variant type to cover all the problems.

```<code>struct Variant
{
    int id;
    union
    {
        Point point;
        std::pair<Point, Point> pair;
    };
};

int main()
{
    Point point;
    std::pair<Point, Point> pair;

    Variant v = intersection(Line{}, Sphere{});
    if (v.id == ID_POINT)
    {
        point = v.point;
        // Do something with point
    }
    else if (v.id == ID_VARIANT)
    {
        pair = v.pair;
        // Do something with pair
    }
    else
    {
        // No intersection
    }
}
</code>```

Avoiding the "no intersection" problem

In order to split the "no intersection" case from the main problem, some libraries used to require the user to check whether there was an intersection before trying to find what was the intersection return type. It looked like this:

```<code>Line line;
Sphere sphere;

if (intersects(line, sphere))
{
    auto ret = intersection(line, sphere);
    // Do something with ret
}
</code>```

Another way to split the "no intersection" case from the rest of the problem would be to use an optional type:

```<code>std::optional<...> ret = intersection(Line{}, Sphere{});
if (ret)
{
    // Do something with ret
}
</code>```

Using exceptions to control the "return" type

I can already see some of you crying.

Yet another way to handle that problem of having different return types would be to throw the results instead of returning them. The "no intersection" return could still use one of the techniques from the previous paragraph:

```<code>try
{
    intersection(Line{}, Sphere{});
}
catch (const Point& point)
{
    // Do something with point
}
catch (const std::pair<Point, Point>& pair)
{
    // Do something with pair
}
// Can still catch errors (or "no intersection" special type?)
</code>```

Having a "main" return type, throwing the other ones

Another way would be to have a "main" return type for the intersection, let's say std::pair<Point, Point> and considering the other return types as "exceptional"; it gives more meaning to the use of exceptions while this is still not quite an error gestion. On the other hand, it could seem strange to handle a "main" type differently than the others...

```<code>try
{
    auto pair = intersection(Line{}, Sphere{});
    // Do something with pair
}
catch (const Point& point)
{
    // The chances for a sphere and a line to meet at
    // a single point are so small that the case can
    // already be considered exceptional.
    // ...
}
</code>```

I purposedly left the errors gestion and the "no intersection" case out of this last example since many techniques already described could be used to handle it and I don't want the number of examples to be exponential. Here is one though:

```<code>try
{
    // res is optional<pair<Point, Point>>
    if (auto res = intersection(Line{}, Sphere{}))
    {
        std::cout << "intersection: two points" << '\n'
                  << std::get<0>(*res).x() << " "
                  << std::get<0>(*res).y() << '\n'
                  << std::get<1>(*res).x() << " "
                  << std::get<1>(*res).y() << '\n';
    }
    else
    {
        std::cout << "no intersection" << '\n';
    }
}
catch (const Point& point)
{
    // Exceptional case
    std::cout << "intersection: one point" << '\n'
              << point.x() << " "
              << point.y() << '\n';
}
</code>```

Since the cases where the result is thrown are exceptional, it should not add any runtime overhead to the program if the underlying system uses zero cost exceptions instead of the old SJLJ exceptions system.

The actual question

Well, that was a pretty long introduction, so here is the question: is there an idiomatic solution to the problem in these examples? And if not, are there at least some of the examples which could be banned without a second thought (well, you could give a second thought to the exception examples though...)?

Note: something seemed evident to me but apparently is not: the entity returned by intersection between two geometric entities is not limited to a nothing, a point or a set of point. An intersection can pretty much return any geometric entity. Therefore, using a container to hold the values does not sound like a good idea.

Note 2: time machine note, it happens. After having given it some thought, I would ban exceptions (as most people would do), not because exceptions are inherently bad or not designed for this, but because it makes the expression intersection(...) == SomeShape throw an exception even when the both operands should be equal, which isn't elegant. I guess that I would use a bastard child of a variant instead.

答:
You have listed many valid alternatives, however the straightforward one is missing:

Just return the count of intersections, and return the points via an array argument. The array argument, of course, has a size to fit the maximum count of intersections. Something like this:

```<code>size_t getIntersections(const Sphere& sphere, const Ray& ray, std::array<Point, 2>* intersections);
</code>```

This is just as safe or unsafe as the union approach or the one that returns illegal points. However, it has one clear advantage: You do not force user code to differentiate between the three cases. I. e., instead of having an if-else ladder along the lines

```<code>auto result = intersections(...);
if(/*no intersection*/) {
    ...
} else if(/*one intersection*/) {
    ...
} else /*two intersections*/ {
    ...
}
</code>```

the calling site may choose to say

```<code>arrays<Point, 2> points;
for(size_t i = getIntersections(..., &points); i--; ) {
    /*code to handle points[i]*/
}
</code>```

That is not possible if the count of intersections is somehow encoded in the return type of the function.

And, yes, I would also discard anything with exceptions without a second thought. They are brutally slow unless they are optimized away. And for optimization you would need to disclose the intersection calculating code to the calling site.

ContentLicense: CC BY-SA 3.0

Title: Intersection of geometric entities

Body:
You have listed many valid alternatives, however the straightforward one is missing:

Just return the count of intersections, and return the points via an array argument. The array argument, of course, has a size to fit the maximum count of intersections. Something like this:

size_t getIntersections(const Sphere& sphere, const Ray& ray, std::array<Point, 2>* intersections);

This is just as safe or unsafe as the union approach or the one that returns illegal points. However, it has one clear advantage: You do not force user code to differentiate between the three cases. I. e., instead of having an if-else ladder along the lines

auto result = intersections(...);
if(/*no intersection*/) {
    ...
} else if(/*one intersection*/) {
    ...
} else /*two intersections*/ {
    ...
}

the calling site may choose to say

arrays<Point, 2> points;
for(size_t i = getIntersections(..., &points); i--; ) {
    /*code to handle points[i]*/
}

That is not possible if the count of intersections is somehow encoded in the return type of the function.

And, yes, I would also discard anything with exceptions without a second thought. They are brutally slow unless they are optimized away. And for optimization you would need to disclose the intersection calculating code to the calling site.


问:
Strategy pattern can use this pointer?
I want to use strategy pattern, but I wander if it is correct to use "this pointer" with the strategy pattern interface.

This is required in order to get internal information which is required for the algorithm, but in all examples I've seen for Strategy pattern, there is no use of this pointer, so I'm not sure if this a correct thing to do.

EDIT: Why do I need this pointer parameter ?
For example I have filemanager class which contain several parameters of files and folder state, and the strategy algorithm is used for decision making of files to be deleted and opened and to return current file handler. using this and getters and setters make it easy to handle the algorithm input and output.

答:
There is no "correct" in programming. There are good things, there are bad things, but more often than not there's a series of tradeoffs that are some good and some bad. Even if you made code that did the job and mislabeled it the strategy pattern, that doesn't make the code incorrect; it just makes your communication confusing.

Rant aside, using this in the strategy pattern is perfectly fine. These are called functors in C++, and are comparable to function objects and closures in other languages.

Title: Strategy pattern can use this pointer?


问:
Application model management questions
Consider the following type of Java / Spring web application, with an SQL database:

there are multiple data entity types (about 100) with relations between them

the entities are viewed, edited or exposed to APIs, and frequently this happens with several entity types (joined)

The current approach uses three layers:

a data layer, that queries the tables, and uses entities that are 1:1 match to the database

a service layer to perform the business logic, and call the data layer as needed

a controller layer - exposing operations to the client side code and to the API

My questions related to handling the models are:

Should every layer have its own models / entity classes? If yes, how is it best to handle copying / merging the models across the layers?

Sometimes, at the service layer, an entity might require to have certain fields filled in one case, but not in other cases. Should there be two model classes for these two situations? (To make sure you can count on what fields are provided by the service)

Given the large number of entities, is it worth to be consistent in addressing the issues above in the same manner, regardless of any extra complexities involved?

答:
I don't think each layer should have their own entity classes. Doing this would multiply number of classes and raise complexity without any real benefit. Sometimes one concept from service layer doesn't map well to relational DB (or other persistence technology) so it's sensible to create different entity classes, but mostly it's not necessary and you can have the same entity class for all layers. But keep in mind that things will change and requirements for one layer will diverge from the others (e.g. you must keep the old contract at the controller layer) - that's when you need to be prepared to create different entity classes for different use cases. If you use one entity for all layers, changes will affect all layers - e.g. renaming attribute can possibly break contract of your controllers.

This is usually done for performance reasons. Best thing to do is to avoid it as much as possible - beware the dangers of premature optimizations. But sometimes this is necessary and then it's difficult to give one answer - if this is one special case where this incomplete entity is used, you might get just fine with just documenting it. If it's used more often, you should create special entity class for this, otherwise you'll get lost in following complexity.

Personally I think that it's better to handle this on one-by-one basis. Entities will evolve differently and trying to handle them all in a unified way will bring a lot of overhead and useless complexity.

So, my advice is to create entity per layer only when it's necessary/meaningful. But you need to keep in mind the consequences and be ready to divide the entity class once the need arises.

Also, be careful about transactions. It's too easy to forget whether you are in a transactional context or not, especially if you're using same entity classes everywhere. From my experience, it's usually good to have clear transactional demarcation - i.e. whole service layer is transactional (by default), everything outside (controllers, tasks etc.) is not.

Title: Application model management questions


问:
Does F# require .NET runtime and libraries to run?
Does F# like C# requires .NET framework to run? According to Wikipedia as stated below, F# is mostly used as a CLI language which means that it is used mostly with .NET. But it also states that the F# foundation provides a compiler for F# separately.

F# is most often used as a cross-platform CLI language, but can also be used to generate JavaScript and GPU code.

F# is developed by the F# Software Foundation,[6] Microsoft and open contributors. An open source, cross-platform compiler for F# is available from the F# Software Foundation. F# is also a fully supported language in Visual Studio and Xamarin Studio. Other tools supporting F# development include Mono, MonoDevelop, SharpDevelop and WebSharper.

Does it mean that F# can be used like unmanaged code similar to C++ and C. I am a total newbie to the .NET platform.

答:
Does it mean that F# can be used like unmanaged code similar to C++ and C?

Theoretically, yes. Practically, no.

Languages often don't specify how they're compiled. There's nothing precluding you from taking the syntax and semantics of Java or C# and have them compile down directly to x86 assembly and avoid the need for the JVM or .NET runtime.

That said, such a compiler doesn't exist (as far as I know) - so if you want that functionality you'll need to spend a few years to decades building it yourself. And I would question any reason for thinking you'd want that in the first place.


问:
Why sending a file is so difficult using angular?
I have to send a file (very large file) to a server. I'm studying what options I have and how to do it. I'm using angular + express + nodejs.

If I use a simple form, I could catch the file on the server using multer with no problem. Is very simple. The html is just a form, in which I specify the target etc. and everything works. The nodejs code is also very simple and straight forward.

As soon as I try to use angular, everything becomes incredible complicated. Meaning, I have to use a directive, and still have trouble with the server. As I said I'm using multer, which requires the data to be "multipart/form-data", and I get from the server "Error: Multipart: Boundary not found"

There are many modules to load files in angular. Which shows that is a recurrent problem with more than one solution. Now, I don't want to post code because for that I asked at Stack Overflow. My question is more subtle:

Why what can be done with a simple form, get's so complicated in angular? I don't mean it in a bad way. I mean it in a 'I want to understand' way.

答:
Angular is for Single Page Applications, forms are sent using AJAX to avoid the page to be reloaded. For sending multipart forms with AJAX, your browser need to support FormData(IE10+): http://caniuse.com/#search=FormData

https://developer.mozilla.org/en-US/docs/Web/API/FormData

ngModel doesn't work with input[type="file"], so you have to create your own directive. Your own directive should be simple: on change, update a File object on your scope.

When sending your form, create a FormData object and add your file(s) to it using FormData.set or FormData.append. You can send your FormData with $http or $resource, and you are relying on the browser for setting the content-type and boundary.

```<code>var formData = new FormData();
formData.append('file', $scope.file);
$http.post('yourUrl', formData, {
   transformRequest: angular.identity,
   headers: {'Content-Type': undefined}
}).then(function () {
   // ...
});
</code>```

angular.identity prevents Angular to do anything on our data (like serializing it).

I recommend this article: https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

Body:
Angular is for Single Page Applications, forms are sent using AJAX to avoid the page to be reloaded. For sending multipart forms with AJAX, your browser need to support FormData(IE10+): http://caniuse.com/#search=FormData

https://developer.mozilla.org/en-US/docs/Web/API/FormData

ngModel doesn't work with input[type="file"], so you have to create your own directive. Your own directive should be simple: on change, update a File object on your scope.

When sending your form, create a FormData object and add your file(s) to it using FormData.set or FormData.append. You can send your FormData with $http or $resource, and you are relying on the browser for setting the content-type and boundary.

var formData = new FormData();
formData.append('file', $scope.file);
$http.post('yourUrl', formData, {
   transformRequest: angular.identity,
   headers: {'Content-Type': undefined}
}).then(function () {
   // ...
});

angular.identity prevents Angular to do anything on our data (like serializing it).

I recommend this article: https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs


问:
is OOP the dominant programming model in real world?
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?

答:
I don't pretend to know the exact numbers, or even to make a rough guess, but there are many programming projects that do not involve OOP. I work with industrial robots. The programs tend to be fairly simple and straight forward procedural code. The actual robot operating system is even more so. </p>

<p>Many of our "tools" we use are OOP based, but they run on PCs and not the robot controller. These include editors, simulations, and utilities. </p>

Body:
I don't pretend to know the exact numbers, or even to make a rough guess, but there are many programming projects that do not involve OOP. I work with industrial robots. The programs tend to be fairly simple and straight forward procedural code. The actual robot operating system is even more so.

Many of our "tools" we use are OOP based, but they run on PCs and not the robot controller. These include editors, simulations, and utilities.

ContentLicense: CC BY-SA 2.5


问:
Should I use the State Design pattern for only two states? Also, what if one object's state is affected by another state?
If you only have two states for an object, is it worth it to still use the State Design pattern?

The context is a multi-player, turn-based game environment where there are Game "Tables" that a player can join, by either entering or leaving a seat.

So, I was focusing on the Seat object to start, as a way of trying to implement recent learning on design patterns.

Generally speaking, the Seat has two states: Vacant or Occupied.
When a seat is Vacant, a player may join it.
When a seat is Occupied, no other players may join and only the Player who has already joined, may leave.

This leads me to my other question...what if one of the states of the Seat is affected by a state in another object, the Game.

The Game object will also have various states. An example of this is, when all 4 players join the table and press Start, the game is considered to be IN PROGRESS.

Consequently, if a Player leaves a seat at this time, for example, by being disconnected, then the seat goes into a "third" state which is a Hiatus State where the spot is reserved for that player to return...but if the game is NOT in progress, then the player may leave the seat freely and it is not reserved.

How would the relationship between the two states be modelled? Would you add a third state to the States a seat can have?

Or is there some parent context that has both a GameState reference and SeatState reference and the "extra state" is handled there?

Any help or insight into the right direction would be much appreciated.

答:
The Wikipedia article for State Pattern has a Java example that illustrates two states, involving two different methods.  Those methods can be arbitrarily complex, so I consider a two-state solution (no pun intended) perfectly valid.

interface Statelike {
    void writeName(StateContext context, String name);
}

class StateLowerCase implements Statelike {
    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toLowerCase());
        context.setState(new StateMultipleUpperCase());
    }
}

class StateMultipleUpperCase implements Statelike {
    /** Counter local to this state */
    private int count = 0;

    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toUpperCase());
        /* Change state after StateMultipleUpperCase's writeName() gets invoked twice */
        if(++count > 1) {
            context.setState(new StateLowerCase());
        }
    }
}
```

<p>Note that <code>writeName</code> swaps out its own implementation by handing a new <code>StateLike</code> object to the <code>StateContext</code> when the <code>i</code> count exceeds one.</p>

<pre class="lang-java prettyprint-override"><code>class StateContext {
    private Statelike myState;
    StateContext() {
        setState(new StateLowerCase());
    }

    /**
     * Setter method for the state.
     * Normally only called by classes implementing the State interface.
     * @param newState the new state of this context
     */
    void setState(final Statelike newState) {
        myState = newState;
    }

    public void writeName(final String name) {
        myState.writeName(this, name);
    }
}
</code>```

A State Pattern would be indicated if your "machinery" substantially changes between states.  The complexity of the condition needed to choose the correct processing object doesn't matter; it's the complexity of the state objects themselves that are the deciding factor.  Otherwise, you could just write all of the logic into a single class.

Think about what happens when you build a car.  The chassis moves along an assembly line and stops at a station where the welding takes place.  Once that state has completed, the chassis moves to the next station on the assembly line, where a different set of robots with completely different programming installs the engine.

Body:
The Wikipedia article for State Pattern has a Java example that illustrates two states, involving two different methods.  Those methods can be arbitrarily complex, so I consider a two-state solution (no pun intended) perfectly valid.

interface Statelike {
    void writeName(StateContext context, String name);
}

class StateLowerCase implements Statelike {
    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toLowerCase());
        context.setState(new StateMultipleUpperCase());
    }
}

class StateMultipleUpperCase implements Statelike {
    /** Counter local to this state */
    private int count = 0;

    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toUpperCase());
        /* Change state after StateMultipleUpperCase's writeName() gets invoked twice */
        if(++count > 1) {
            context.setState(new StateLowerCase());
        }
    }
}

Note that writeName swaps out its own implementation by handing a new StateLike object to the StateContext when the i count exceeds one.

class StateContext {
    private Statelike myState;
    StateContext() {
        setState(new StateLowerCase());
    }

    /**
     * Setter method for the state.
     * Normally only called by classes implementing the State interface.
     * @param newState the new state of this context
     */
    void setState(final Statelike newState) {
        myState = newState;
    }

    public void writeName(final String name) {
        myState.writeName(this, name);
    }
}

A State Pattern would be indicated if your "machinery" substantially changes between states.  The complexity of the condition needed to choose the correct processing object doesn't matter; it's the complexity of the state objects themselves that are the deciding factor.  Otherwise, you could just write all of the logic into a single class.

Think about what happens when you build a car.  The chassis moves along an assembly line and stops at a station where the welding takes place.  Once that state has completed, the chassis moves to the next station on the assembly line, where a different set of robots with completely different programming installs the engine.


问:
Why would I use Angular?
From the basic Angular tutorial, it seems like all it does is fetch some JSON from an API and display it. Also, there's its double binding magic.

But why would I use it instead of a backend solution (like Rails) that builds the view in the backend and serves it to the user, with everything in place already? What are the use cases?

答:
Angular is for developing Single Page Applications, it helps with providing a solid skeleton for your app. It is also good with forms, not so good with complex crowded UIs with lots of data. Two-way data binding is "magic" at first but you have to be aware that most recent frameworks (including Angular 2 itself) move away from two-way data binding for a more simple Data flow down / event flow up approach (telling that story would be too long here).

I also have to warn you that Angular doesn't have a definite way of doing things and sometimes offers too many ways to skin a cat, which can make the learning curve steeper. Also if you want to scale an Angular app, you'll have to understand its internal mechanics and possible impact on performance. Once you do that, and once you establish consistent solid design patterns, the sky is the limit. But you need to dedicate time to it.

That said, your question seems to be more about what are the use cases of SPAs rather than Angular itself.

The use cases of Single Page Applications are for having web apps with robust UI/UX and overall better application feel. By not having to reload your page you save on rendering time and bandwidth. You also separate data and presentation which is awesome. Your application becomes:

Static files, including your index.html

A REST API serving data

A data-driven front-end application

Title: Why would I use Angular?


问:
Redex and reduction strategies
I'm studying Types and Programming Languages, and have some trouble getting my head around the concepts of the 5th chapter, The Untyped Lambda Calculus.

Specifically, redex, reduction and the various evaluation strategies are doing my head in. The following is what I understand put into my own words, in an attempt to explain things to myself and get more knowledgeable people to correct my mistakes / imprecisions. I am honestly unsure as to whether this is an acceptable format for stackexchange, and am open to suggestions to make this a better fit.

Note that others have tried to answer a very similar question, but have still left me confused:

Call by value in the lambda calculus

Untyped lambda calculus: Why is call-by-value strict?

Redex

If my understanding is correct, a redex is a reducible expression, that is, the application of a lambda term to a lambda abstraction.

Or, more concretely, a redex is always of the form (λx.s)t.

Redex reduction

Reducing (λx.s)t is done by replacing all free occurrences of x in s by t.
For example:

```<code>(λx.x + 2) 1
→ 1 + 2
→ 3
</code>```

The process of reducing a lambda expression to its normal form is driven by an evaluation strategy: an algorithm for picking which redex to reduce first. In order to describe these however, we need some more vocabulary.

Redex qualifications

Leftmost and rightmost

the leftmost redex is the one whose abstraction is textually to the left of all other redexes.

the rightmost redex is the one whose abstraction is textually to the right of all other redexes.

So, for example, in (λx.x + 2) (λy.y + 1), we have:

leftmost redex: λx.x + 2

rightmost redex: λy.y + 1

There can only be one leftmost and one rightmost redex in a given expression. I'm assuming that in an expression composed of a single redex, that redex is both the leftmost and the rightmost.

Innermost and outermost

an innermost redex is one that contains no other redex.

an outermost redex is one that is contained within no other redex.

So, for example, in (λx.(λy.y + 1) x) 2, we have:

innermost: λy.y + 1, as it contains no other redex.

outermost: λx.[...], as it isn't contained in any other redex.

I'm assuming that in an expression composed of a single redex, that redex is both outermost and innermost.

Evaluation strategies

Having defined this, we can talk about the two evaluation strategies that I'm struggling with: call by name and call by value.

Call by name

In call by name, the leftmost outermost redex is always picked for reduction. Additionally, no reduction can occur within a lambda abstraction.
The example given by Types and Programming Languages is:

```<code>id (id (λz. id z)) # the leftmost, outermost redex is the very first id
→ id (λz. id z)    # the leftmost, outermost redex is still the first id
→ λz. id z         # there is no outermost redex remaining, we're done.
</code>```

I do not understand the need for the definition of the strategy to include no reduction can occur within a lambda abstraction: is that not implied by the fact that only outermost redexes are eligible for reduction?

Call by value

In call by value the rightmost outermost redex is always picked for reduction.
The example given by Types and Programming Languages is:

```<code>id (id (λz. id z)) # the rightmost, outermost redex is the second id
→ id (λz. id z)    # the rightmost, outermost redex is the first id
                   # (it's textualy on the left, but there is no redex to its right)
→ λz. id z         # the only remaining redex is not outermost (it's contained within
                   # an abstraction) and cannot be reduced.
</code>```

答:
In Call by name:

I do not understand the need for the definition of the strategy to
  include no reduction can occur within a lambda abstraction: is that
  not implied by the fact that only outermost redexes are eligible for
  reduction?

No.
According to your definition of outermost, a redex is outermost if it is not contained within any other redex.
In the following code, id z is the outermost redex, not λz. id z (which is an abstraction, not a redex).

```<code>id (id (λz. id z)) # the leftmost, outermost redex is the very first id
→ id (λz. id z)    # the leftmost, outermost redex is still the first id
→ λz. id z         # there is no outermost redex remaining, we're done.
</code>```

Note that in the description of call by value in TAPL, there is a missing word in the definition of value:

p 57, definition of call-by-value

"a term that is finished computing..." should be "a CLOSED term that is
  finished computing..."

This is probably the reason for your confusion.

Edited to add:
It turns out that the author's description of call-by-value is inconsistent with the operational semantics given in the book for the untyped lambda-calculus under call-by-value evaluation.
According to the description of call-by-value on page 57, λx. id id would evaluate to λx. id since id is a value. (a closed term that cannot be reduced) and id id is the outermost redex. However the operational semantics (on page 72) do not have a rule that can reduce this term in this way. In addition, on the same page the author writes "Since (call-by-value) evaluation stops when it reaches a lambda, values can be arbitrary lambda-terms" suggesting that reductions are not allowed inside abstractions.

In the description of call-by-name, the author mentions that no reductions are allowed inside abstractions but neglects to do so in the description of call-by-value.

Second edit:
I believe the correction that adds the word "CLOSED" to the definition of call-by-value that I mentioned above causes an inconsistency with the operational semantics.
For instance, id (λx. x y) reduces to λx. x y according to the operational semantics given. (Since values are arbitrary lambda-abstractions and the rule 'E-AppAbs' applies here) However, λx. x y is not a closed term since the occurrence of y in it is not bound.

Errata for the book are available at:
http://www.cis.upenn.edu/~bcpierce/tapl/errata.txt

Title: Redex and reduction strategies

Body:
In Call by name:

I do not understand the need for the definition of the strategy to
  include no reduction can occur within a lambda abstraction: is that
  not implied by the fact that only outermost redexes are eligible for
  reduction?

No.
According to your definition of outermost, a redex is outermost if it is not contained within any other redex.
In the following code, id z is the outermost redex, not λz. id z (which is an abstraction, not a redex).

id (id (λz. id z)) # the leftmost, outermost redex is the very first id
→ id (λz. id z)    # the leftmost, outermost redex is still the first id
→ λz. id z         # there is no outermost redex remaining, we're done.

Note that in the description of call by value in TAPL, there is a missing word in the definition of value:

p 57, definition of call-by-value

"a term that is finished computing..." should be "a CLOSED term that is
  finished computing..."

This is probably the reason for your confusion.

Edited to add:
It turns out that the author's description of call-by-value is inconsistent with the operational semantics given in the book for the untyped lambda-calculus under call-by-value evaluation.
According to the description of call-by-value on page 57, λx. id id would evaluate to λx. id since id is a value. (a closed term that cannot be reduced) and id id is the outermost redex. However the operational semantics (on page 72) do not have a rule that can reduce this term in this way. In addition, on the same page the author writes "Since (call-by-value) evaluation stops when it reaches a lambda, values can be arbitrary lambda-terms" suggesting that reductions are not allowed inside abstractions.

In the description of call-by-name, the author mentions that no reductions are allowed inside abstractions but neglects to do so in the description of call-by-value.

Second edit:
I believe the correction that adds the word "CLOSED" to the definition of call-by-value that I mentioned above causes an inconsistency with the operational semantics.
For instance, id (λx. x y) reduces to λx. x y according to the operational semantics given. (Since values are arbitrary lambda-abstractions and the rule 'E-AppAbs' applies here) However, λx. x y is not a closed term since the occurrence of y in it is not bound.

Errata for the book are available at:
http://www.cis.upenn.edu/~bcpierce/tapl/errata.txt


问:
In SemVer should I increase the version on every commit/accepted pull request
Running a community project. Have a few pull requests that have been made and the version of our product is currently 2.5.0

All 3 of the changes are feature adds but are backwardly compatible. Should I be creating 2.6.0, 2.7.0 and then 2.8.0 as I have 3 new features being added or is it common to bind together a collection of features and rev the version once.

For example, 2.6.0 will contain all 3 pull requests

I would expect it would transition as

```<code>2.6.0-RC1 ->
2.6.0-RC2 ->
2.6.0-RC3
</code>```

ending with

2.6.0 (version)

I've had a look at Puppet who say they use semantic versioning but they have just merged 38 pull requests this month and I'm doubting I'll see the version going crazy. Version 2.2.0 for example seems to have a number of fixes
https://github.com/puppetlabs/puppetdb/commit/d31c22ed00aa5d25b9e09403abee3a46bdecb7ef

What should I be doing as per SemVer?

答:
While not being explicit about it, SemVer applies to released packages.

Therefore, if you, as release manager, build a package containing all 3 commits then you only have to increment the version once. If you choose to release them in separate packages then you have to increase the version each time you release.


问:
Is renaming an 'alias' for moving?
Is it true to say (on Windows and Unix\Linux\OS X) that renaming a file or directory is just an alias for moving?

e.g.

Are there any side effects to either which are not present on the other?

Does 'rename' actually 'move' move under the hood?

Is there a way I can prove\disprove this?

答:
The extra options supported by Win32 MoveFileEx function provide a good overview and explanation of the similarities and differences between renaming and moving.

When moving files across volumes, a copy (followed by delete) is performed.

From the perspective of an ordinary computer user, when one wants to perform a rename, one would expect the computer to prevent this from overwriting an existing file of the same name.

Whereas copying and moving would offer a choice of cancelling, auto-renaming, or replacing (overwriting).

Note that this is from a user's perspective, not from a programmer's perspective. However, the API must support additional flags so that the programmer can implement the user's expectations.

In summary, due to conventions inherited from the days of MS-DOS, a "rename" is perceived to be less destructive (other than being renamed) than a "move", even though the distinction no longer has any relevance to the underlying mechanism (the file system) unless the operation spans different file systems.

Unix and Linux had been designed by programmers, for programmers. Therefore the opinions of ordinary computer users had never factored into the design of file system commands, so the distinction does not exist there.

Title: Is renaming an 'alias' for moving?


问:
Is there any reason not to allow negative numbers to be entered into a JSP field labeled for positive numbers?
Our application, a fairly complicated money ledger, has a JSP field for entering a certain type of money due, balanced by payments made towards that amount due.  In the application, this field is labeled "Other Payment"

After much discussion about our users' confusion over why their ledger printouts were 'inaccurate', it was decided that we should do away with entering negative numbers into this data field.  This field was not designed to take negative numbers, nor are any of our JSP fields supposed to take negative numbers.  To allow users to enter 'negative' numbers, we're adding a new field called "Other Unpaid".

I may be called upon in the future to justify this change.  Is there any reason, for a java application built on an SQL database foundation, why entering numbers as negative could be bad for our application?

答:
Because payments aren't negative.  Ask any accountant.  In most accounting ledgers, this would not only be intuitively incorrect, but physically impossible.

If you want to make a negative payment, you issue a positive credit.

Note that Quickbooks considers this data corruption.


问:
Difference between class scope and object scope design patterns
Apparently design patterns have a ton of classifications. One I am struggling with is whether or not the pattern is a class scoped pattern or an object scoped pattern. Of course no documentation exists on the differences between the two, so I'm asking your opinion.

The GoF book defines it as:

"Class patterns deal with relationships between classes and their subclasses. These relationships are established through inheritance, so they are static-fixed at compile-time. Object patterns deal with object relationships, which can be changed at run-time and are more dynamic. Almost all patterns use inheritance to some extent. So the only patterns labelled "class patterns" are those that focus on class relationships. Note that most patterns are in the object scope."

Problem is, there are only class relationships as an object is nothing without its class. I've never heard of "object relationships" outside of this book.

答:
This boils down to composition vs. inheritance.

Let's take a look at one pattern that you can do in both ways.

The adapter pattern is, as the name implies, an adapter between two classes that are otherwise incompatible.

Say you write a 3D engine and you need a Point class. You have your Point all ready and it kind of works, but then you find another class OtherPoint in some library that does everything your class should be doing in a nicer way, but its methods have different names. Your 3D engine expects your Point class.

What can you do to make both classes compatible in order to use OtherPoint class?

Point extends OtherPoint inheritance for the win. Point receives all the functionality it needs. The methods specific to your engine that Point declares simply call the corresponding ones from OtherPoint. This is the class pattern style of the adapter.

On the other hand, you could do Point(OtherPoint constructorParameter) to receive an OtherPoint object. The idea is similar: the Point methods now don't delegate to the methods it received via inheritance but to the object it received as a parameter in the constructor. This is the object pattern style of the adapter. This is a comparable to the wrapper pattern.

How does that explain the GoF statement(s)?

"Class patterns [...] are static-fixed at compile-time.

By saying Point extends OtherPoint you say that a Point is a OtherPoint. It's a plain old simple inheritance chain. You cannot change them at run time.

Object patterns [...] which can be changed at run-time and are more dynamic

By saying Point(OtherPoint constructorParameter) you say that a Point has a OtherPoint. Maybe you find out that this library has an even fancier class, i.e. FancierOtherPoint extends OtherPoint. You can pass that to Point as well. In fact you can pass any sublcass of OtherPoint to Point, because of polymorphism.

Maybe FancierOtherPoint only works on certain hardware and you have to check for that hardware at run time. With the object pattern style of the adapter, you can do exactly that: decide dynamically what class to use.

I've never heard of "object relationships" outside of this book.

"object relationships" is not  special phrase. It means exactly what is says: relationships between objects. Design patterns are just names for common ways to define relationships between objects.

If I were to say  "3.14159265359..." you'd probably stop me to ask if I mean "pi". Now if you were to tell me you "inherit from that one class to make things compatible and delegate methods and..." I would stop you to ask if you mean the adapter pattern.

It simplifies communication and everybody has a rough understanding of what the conversation is about without explaining everything in full detail.

OwnerDisplayName: Matt


问:
Pre-Processors vs Pure Web
It seems like within the last few years or so HTML/CSS/JavaScript Preprocessors have exploded in quantity and general use. They're still not as common as pure HTML, CSS, and JS/jQuery, but their overall popularity seems to be growing if sites like CodePen are any indication. After reading up on tutorials for Haml, Jade, SASS, Coffeescript, etc. I'm honestly slightly confused. They all have benefits, understandably, but really they seem like very short-sighted languages. With the exception of SASS/SCSS it seems like simple things like creating div tags in an HTML preprocessor or adding events in a JS preprocessor are made very, very simple, but then when you get into more complex functions or template creation, they become even more complex than the languages they're processing for.

All in all without the innate browser support that I doubt any of these preprocs will get none of the languages, to me, feel like they are in the running to fully succeed anywhere outside of their established user base. My issue is that I don't even see a benefit to really digging into any of the preproc languages. Using them I could make a website from the early millenium pretty easily, but really if I need to create a modern site it seems to be a waste of time to get in the know with any of them whereas I could just code it out with HTML/CSS/JS(JQuery).

My question is - Am I missing something in the larger scope of it all? What are the benefits to using these preproc'd languages, especially given the fact that they're not browser supported? As a web developer is it worth it to spend time to learn any of them?

答:
I see plenty of reason why you should embrace pre-processed languages, and I'll try to demonstrate the benefits of those tools.

1. Paradigm shift

In my opinion, the greatest feature of any pre-processed language is the ability you to develop and solve problems in a different mindset compared to the standard HTML/CSS/JS way. In short, pre-processing can lead to (but not always) a paradigm shift.

Why is it powerful ? Some problems are easily solved in one paradigm, some in another paradigm. What's powerful is that you can create any paradigm and convention that maps to HTML/CSS/JS to efficiently solve a particular problem.

The most known paradigm shift is made by C compilers, transforming easy to write C/C++ to efficient but hard to write ASM.

In theory, you could create a mapping between sufficiently complex CSS and JS, any CSS-aware designer could then use JS through well known tools.

2. Offline optimisation

You don't need to be pre-processed to shift paradigm, jQuery is paradigm-shifting at runtime. What's awesome with pre-processed tools is that the cost is (mostly) invisible at runtime.

Using compiled language compared to a library or a run-time toolkit is, in my experience, always better in term of final performance. This is very intuitive, if a piece of code is compiled once into optimised low level code without any dependency, it should perform better compared to the same piece of code executed at runtime by a library.

This is not new at all, compilers were the first (as far as I know) to introduce this kind of transformations and the first to introduce optimisations. This technique was proven efficient many time in the past in non-web environment.

3. Polyfill at the language level

The web world is browser based (boom! mind blown!), these browsers are updated and deployed at different pace, most web developers may have to deal with outdated browsers one day or another.

Up until now, many great libraries managed to fill those gaps for us. Yes, i'm thinking about the great mighty jQuery, many thanks to those who contributed to this awesome library. The problem is that library can only be written inside the scope of the language they're written in, and unlike in ruby, you can't meta-program everything in JS. Sadly, browsers still can't understand ruby.

This is applicable primarily to JS but also valid with CSS and HTML. To implement a new keyword or a new language structure (to solve problems faster, paradigm shift and stuff), you have to use pre-processing. Pre-processing sets you free from many kind of limitation inside the language, unlike libraries.

Want to use the new ES6 right now because your code will be more maintainable than ever? You can! Want to stick with your programming language and target a browser anyway? You can! (use emscripten).

4. Because we can (in a reasonable amount of time)

As the time of writing, compiling (SASS or Coffeescript in my case) is no longer a pain, it's instantaneous and can be triggered on file save with the right toolchain.
The build toolchain has evolved too, we see more and more great developer tools like bower, yeoman, gulp, ...

The frontend developer is now armed with a mature toolchain and is ready to tackle every common problem in a matter of seconds. Easy to install and maintain, your build tools and processes should be part of your project and should now be ready to accept a pre-processing step. (even if you only uglify)

Conclusion

Using compiled languages/tools is no longer a pain, and you should use any tool that fits your needs. The fact that it needs to be compiled shouldn't be a blocker.

Title: Pre-Processors vs Pure Web


问:
Angular Architecture
I have been developing a few prototype apps in Angular, with various backends, including firebase and php/mysql.  I'm pretty sure I'm not using a good organization pattern for development because of a couple of kluges I have to use in the code to avoid the "max digest iterations reached" exception.

I have a template with an ng-repeat, like this:

```<code><ion-item data-ng-repeat="outcome in Outcomes.getAll()">...</ion-item>
</code>```

It is supported by a service like this:

'use strict';

angular.module('app.outcomes', ['app.utility']).service('Outcomes',
function ($http, Utility) {
    var svc = this;
    svc.outcomes = false;

```<code>/**
 * Initializes the outcomes array if it has not yet been initialized.
 *
 * @returns {Array}
 */
svc.initialize = function () {
    if (svc.outcomes === false) {
        // If this is not set to something immediately, repeated calls to
        // digest occur during http call and digest overloads.
        svc.outcomes = true;
        $http.get('/api/outcome/all').
            success(function (data, status, headers, config) {
                        svc.outcomes = data.result; // set data to real array value
                    }).
            error(function (data, status, headers, config) {
                  });
    }
};

/**
 * Called in ng-repeat so that it makes sure the data is initialized.
 * An ng-init call does not work.
 * @returns {Array}
 */
svc.getAll = function () {
    svc.initialize();  // called constantly from ng-repeat, while array actually set
    return svc.outcomes;
};});
</code>```

The controller is a one-liner that sets the $scope.Outcomes variable to the service.

This strategy works, because the digest loop tests the condition.  What seems klugy to me is that I need to set the outcomes array to some unused value while I wait for the ajax call to return. Otherwise the digest loop is called and it tries to keep doing it for however long the call takes to return from the server.

Another related problem I have is that if I set the svc.outcomes array later, I will sometimes get the same error about too many digest iterations.

The questions I have are:

1) Is there a better way to organize the code?  I need to be able to access that server data across multiple scopes.

2) Is there a way to ensure that the data array gets initialized without having to call the getAll() method in the ng-repeat loop?  An ng-init call doesn't populate the data, so I can't just reference Outcomes.outcomes in the template.

What is strange to me is that I think the "max iterations" thing just started happening with using a minor update (1.3.3 to 1.3.6) to angular.  That could be my imagination though.  Any architectural suggestions would be appreciated.

答:
tldr;

1) Yes, there's a better way.

2) Yes, you shouldn't be firing an HTTP request in an ng-repeat

Full Answer

You need to understand how ng-repeat works. Every single time the digest cycle runs, angular checks to see if the array in the ng-repeat has changed. And when you work with angular, I'd recommend that you think of the digest cycle as something that runs ALL THE TIME. Everything you do in angular fires a digest cycle. Clicked somewhere? The digest cycle just ran. Changed a value in an input somewhere? Digest cycle just ran. Hovered over something with an angular-bootstrap tooltip (because you thought those things are much prettier than titles)? Digest cycle just ran. Breathed too hard? Digest cycle just ran.

That's why you'll often hear people say you shouldn't ng-repeat over functions. Not because that's a hard and fast rule, but because in general, you don't want to force angular to have to execute that function every single time anything happens on the page just to see if the return value changed. Do your self a favor and ng-repeat over an array, not a function that returns an array.

Which brings me to my next point. If you do ng-repeat over a function, make sure the function returns the same array every time. I don't mean an array with the same elements, or an array that looks the same, but the same javascript object. If you don't, you'll end up with a max digests reached error. That's because even though the contents of the array are the same, the actual objects are different.

So how should you be doing this?

In your controller, call the initialize method on the service. This will populate the outcomes array. In your ng-repeat, iterate over the outcomes array directly. To do this, you'll need to expose two things from your service: the initialize function (you already are doing this) and the outcomes array that's populated in the success method of your $http.get call. You can get rid of the getAll function.

Final Note

I'm assuming that you really only have to run the HTTP request once. If you have to run the HTTP request all the time to reflect changes on the server, you need to start thinking of other solutions to this problem (websockets, etc). You can't run an HTTP request inside the digest cycle and expect your app to respond normally.

Title: Angular Architecture


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
Is the ternary operator evil?

No it's a blessing.

When is ?: appropriate?

When it's something so simple you don't want to waste many lines for.

and when is it not?

When the readability and clearness of code suffers and a potential for a mistake through insufficient attention increases, for example, with many chained operators, just like in your example.

The litmus test is when you begin to doubt your code is easily readable and maintainable in the long run. Then don't do it.

Title: Ternary operator considered harmful?


问:
Is obtrusive JavaScript required to support a feature of AngularJS?
I'll start by saying I'm just learning about AngularJS, and I was reading this article, which seems to advocate for obtrusive JavaScript as the right thing:

http://www.ng-newsletter.com/posts/angular-for-the-jquery-developer.html

My understanding is that unobtrusive JavaScript is generally considered "the right thing" (which is perhaps debatable, but outside the scope of my question). But I was wondering if there is a particular feature of AngularJS that requires event bindings be specified via attributes like ng-click? Is there a way to use AngularJS and NOT use inline event bindings?

For reference:
Obtrusive JavaScript generally refers to having your JavaScript ties in the HTML itself. Unobtrusive JavaScript refers to using JavaScript or other means to programmatically apply code behaviors to the DOM rather than the plain-text markup having references to JavaScript.

答:
Yes.

That's how angular works.

In olden times (just after the dinosaurs all died out and a bit before smartwatches became The Next Big Thing), Unobtrusive JavaScript was considered The Right Thing. Unobtrusive JavaScript would hang out with her cousin, Progressive Enhancement, and the two of them were heralded as the light unto the world and the beacon of goodness.

There was a reason for that. Lots of users were using browsers with poor JavaScript engines or perhaps no JavaScript engines. Or they had JavaScript disabled. The web was primarily for hypertext transfer, we were told, and we shouldn't make our websites unusable to some by forcing JavaScript upon them.

By the same token, it made sense to keep JavaScript out of the HTML. HTML should be kept pure, it was thought, because JavaScript was something you added on afterwards - if the user allowed it. If not, at least the HTML markup reflected the semantics of what you were trying to convey.

That's not the philosophy of AngularJS or most modern web development guidelines because things have changed. When we use AngularJS or similar frameworks, we're using the web to deliver applications, not just text and images. Web applications are useless without JavaScript, and there's no point in pretending otherwise. So we've thrown off the shackles of Progressive Enhancement because (a) we can safely rely on all of our users having JavaScript enabled and (b) it just slows us down.

Once we're not doing Progressive Enhancement, why do Unobtrusive JavaScript? Separation of concerns is a wonderful concept. But it's six of one or half-dozen of the other: you either have HTML riddled with references to JavaScript or you have JavaScript riddled with references to HTML (the jQuery way).

If you use AngularJS, you'll pretty soon see a cleaner separation of concerns in your code than you've seen in other styles of web development. Sure, there are references to JS functions in your HTML. But you can easily move around HTML without worrying about breaking code, and your JS is clean, testable, and does not rely on a very specific DOM. This allows you to reuse business logic better AND reuse HTML better.

Bottom line: don't stress about it. You'll get used to it quickly enough. And don't resist things just because you were always told that the other way is The Right Way.

Addendum
If you feel it's important for your HTML to be compatible with the standard, you can use the data- prefix on your angular directives: ie, data-ng-click= and data-ng-repeat= and your HTML will be W3C compliant. Personally I never worry about it, but doing it is harmless.


问:
Why is Haskell unable to avoid repeated evaluation without the monomorphism restriction?
I just finished learnyouahaskell the other day, and I was trying to make sense of the Monomorphism Restriction, as described by the Haskell Wiki. I think I understand how the MR can prevent repeated evaluations, but I'm failing to see why those repeated evaluations can't be avoided by far more straightforward means.

The specific example I have in mind is the one used by the wiki:

```<code>f xs = (len,len)
  where
    len = genericLength xs
</code>```

where genericLength is of type Num a => [b] -> a.

Obviously, genericLength xs only needs to be computed once to evaluate (len,len), since it's the same function with the same arguments. And we don't need to see any invocations of f to know that. So why can't Haskell do this optimization without introducing a rule like the MR?

The discussion on that wiki page tells me it has something to do with the fact that Num is a typeclass rather than a concrete type, but even so, shouldn't it be obvious at compile-time that a pure function would return the same value--and thus the same concrete type of Num--when given the same arguments twice?

答:
It's the same function name, with the same arguments, but potentially different return types and implementations, because it's polymorphic.  That means if it's called in a context expecting an (Int, MyWeirdCustomNumType) return type, it has to evaluate it twice, because the implementation of (+) in Int is completely different from the implementation of (+) in MyWeirdCustomNumType.  You need to run physically different code at some point.

That's why it matters that Num is a type class.  It means you have different implementations for different types.  It also means if f is in a library, it doesn't know at compile time about all the combinations of types it might need to return.

So, yes, you do need to see the invocations of f to know what return types to use.  Most of the time, you would expect them to be the same, which is why they put the monomorphism restriction in by default.  It can be turned off for those rare occasions when you don't.  In practice, programmers don't tend to leave these sorts of situations up to type inference anyway.


问:
Best strategy to find the root cause when exception is swallowed by 3rd party
I am sure we have all run into a scenario where a 3rd part API complains with an incomplete stack trace. In essence the error handling in the 3rd party API does something like this,

```<code>catch (WhateverException e) {
   throw new ConfusingException("Something terrible happened, BUT I won't tell you what!");
}
</code>```

Now here when the ConfusingException is thrown it doesn't pass WhateverException as the cause in the second param, and hence when the someone using this API gets the exception they wouldn't get the whole trace. Sadly, it is still common to see people write such code and it gets worse when you have no control over the code.

What is the strategy you would follow when faced with the situation - how do you find the exception message and line on which WhateverException was raised?

答:
Your best chance would be to run the application with a debugger and set a breakpoint on that line (or the constructor of ConfusingException).

It is possible to set a break point even in 3rd part applications when source may be unavailable. As in this case in the method or ConfusingException as suggested here.


问:
Setting up folders and importing modules in Python
I'm building an app to automate some processes that are annoying to do by hand (looking in a file, taking certain information out of a file, building another file with that information).

My project has three main pieces: app.py, which talks to the user and uses webpy to build a simple interface; maker.py, which contains a set of functions that do the heavy lifting; and a folder of html templates. There is also a static folder, which is where the app puts the results of its hard work.

The only way I can get this mess to work is if app.py and maker.py are in the same folder. That doesn't jive with the way various tutorials have told me to set up my folders, though. If they aren't in the same folder, I get errors like "no module named maker". Another problem is that I can't see any good reason for the FragmentMaker class to exist at all. Why can't I have a file full of functions and just import the whole thing as it stands?

What is the best way to set up the folders for this kind of project? Are maker.py and app.py supposed to be in different folders? If so, how do I import maker.py so I can use the code I've put in it?

The web side, app.py :

```<code>import web
from maker import FragmentMaker #can't make this work

urls = ('/upload', 'Upload',
        '/make_link', 'Make_Link'
)

app = web.application(urls, globals())
render = web.template.render('templates/')

maker = FragmentMaker() #this doesn't work either

class Upload:
    def GET(self):
        return render.upload_form()

    def POST(self):
        x = web.input(myfile={})
        filename = x['myfile'].filename
        input_file = x['myfile'].file # returns a file-like object
        if '.docx' in filename: #Runs the docx side of fragment maker
            E_supinfo = maker.makeList(input_file)
            maker.WriteFrag(E_supinfo)
        elif '.csv' in filename: #Runs for everything else
            Other_supinfo = maker.ProcessCSV(input_file)
            maker.WriteFrag(Other_supinfo)
        else: #For unsupported file types
            return render.error_page(filename)
        return render.upload_confirm(filename)

class Make_Link:
    def GET(self):
        return render.make_link('NONE')
    def POST(self):
        instring = web.input(accession = 'NONE')
        E_Link = maker.makeLink(instring.accession)
        return render.make_link(E_Link)

if __name__ == "__main__":
app.run()
</code>```

And this is maker.py, more or less:

```<code>import a bunch of useful things other people have built

class FragmentMaker: #does '(object)' need to be in here?
    def __init__(self):
        self.joy = "service is my only joy" #do I need a variable here? Nothing uses this.

    def Thing1(self, stuff_for_thing1):
        useful code here.

    def ProcessCSV(self, other):
        more code that works

    def makeLink(self, acnum):
        code here

    def makeList(docname): # does 'self' have to be in these?

        E_List = Thing1(docname) #calling a function from inside another function is ok, right?

        code: then a miracle happens.
</code>```

... and so on.

my file structure:

```<code>makefrag
|-bin
    app.py
|-docs
    empty for now
|-Fragment_Maker
    __init__.py
    maker.py
|-static
    results go here
|-templates
    html files here
|-tests
    all sorts of random test files and code in here
__init__.py
</code>```

答:
I cannot comment so instead I'll answer or lead you there with rhetorical questions:

First, how are you intending on launching as well as using this program? You are building a python package by using __init__.py's but you are executing a module (bin/app.py) within the package as __main__. This is not a typical setup.

Do you plan on importing this package of yours into some other python script? Maybe you don't need a package at all and can use a few scripts. Generally all python files related to some function would be in one cohesive package (perhaps you don't need that top-level __init__.py).

Did you mean for bin/app.py to be executable since it appears that's your only use of it? Add a #!/usr/bin/env python run command to the top of the file, and IMO make the file called app and executable $ chmod +x bin/app.

It would be good to google how python finds modules, how to construct a package, and how env's PYTHONPATH and sys.path work. If your module name doesn't make it to sys.path or is relative to your current directory python won't find it. I added some links below.

If you don't intend on using a python package mechanics you could simply (answer) perform a sys.path.append(os.path.join(os.getcwd(), 'Fragment_Maker')) or sys.path.append(os.path.join(os.dirname(__file__), '..', 'Fragment_Maker')) before your import maker, depending on how you intend on launching your application. Otherwise your question cannot be answered without assumptions from above (e.g. maybe you'll want to put your python script app at top level, keep Fragment_Maker a package, perform a from Fragment_Maker import maker), but assuredly you can now figure it out with these resources:

https://docs.python.org/2/tutorial/modules.html#packages

https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH

https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python

https://stackoverflow.com/questions/50499/in-python-how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executin

https://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py


答:
Is there a way I can prove\disprove this?

No, because

Different operating systems do things differently.

Different kinds of renames/moves can be conceptually different acts:

Renaming/moving a file within the same directory,

Renaming/moving a file from one folder/directory to another on the same logical device,

Renaming/moving a file from one logical device to another, and

Renaming/moving a file from one physical device to another.

On most common modern systems, renaming/moving a file within the same logical device is a simple matter of deleting the reference to the file object from the original location and adding a reference to the file object in the target location. The contents of the file are not touched.

This is impossible when "moving" across physical devices. The contents of the file to be moved don't exist on the target device. The contents have to be copied. How moving across logical devices depends on the operating system's concept of a logical device.

Title: Is renaming an 'alias' for moving?

Body:
Is it true to say (on Windows and Unix\Linux\OS X) that renaming a file or directory is just an alias for moving?

e.g.

Are there any side effects to either which are not present on the other?

Does 'rename' actually 'move' move under the hood?

Is there a way I can prove\disprove this?


问:
Which approach for coding a 'texture atlas'?
For a game project, I have a couple of textures coming from multiple sources and I need to pack all these within a single texture atlas.

Example for a racing game circuit, there are textures for :

the sky

the track

the various objects in environment

Each of the aforementioned item is a catalog containing many textures.

My problem is the following:

How should I design the ins and outs of this object, knowing that I must be able to add textures to it, then retrieve the region it has been placed in ?

I first came up with the idea using a simple string but did not like that approach regarding the usage of it throughout a code base.

Is this a case of over-engineering from me or would a simple string be sufficient for such job ?

答:
I would first start from the interface. I think a good interface for your texture atlas would be something like:

```<code>class TextureAtlas
{
    public Texture Sky { get; }
    public Texture Track { get; }
    public Texture SomeObjectInEnvironment { get; }
}
</code>```

Since you're probably going to use some tool to generate the texture atlas and that tool will provide you with the information about the position of each texture in the atlas, you could use that to generate the code of the TextureAtlas type (and to do that, you could use T4).

The generated code could look something like:

```<code>class TextureAtlas
{
    private Texture m_atlas;

    public Texture Sky { get { return m_atlas.Subtexture(1000, 0, 256, 512); } }
    …
}
</code>```

Body:
I would first start from the interface. I think a good interface for your texture atlas would be something like:

class TextureAtlas
{
    public Texture Sky { get; }
    public Texture Track { get; }
    public Texture SomeObjectInEnvironment { get; }
}

Since you're probably going to use some tool to generate the texture atlas and that tool will provide you with the information about the position of each texture in the atlas, you could use that to generate the code of the TextureAtlas type (and to do that, you could use T4).

The generated code could look something like:

class TextureAtlas
{
    private Texture m_atlas;

    public Texture Sky { get { return m_atlas.Subtexture(1000, 0, 256, 512); } }
    …
}


问:
What data structure would you use to represent an organic compound?
Are there any good data structures out there that can be used to represent a molecule?

I was thinking maybe I represent it as a Graph by making every atom a vertex, however, it's common for organic compounds to have lots of Carbons and Hydrogens. How would you number it? Is there a good way to represent molecules, but at the same time, have an efficient .contains() method?

One of the most basic uses for this would be to check if a compound contains carbonyl group, or a benzylic hydrogen, or even a benzene ring.

答:
The first temptation with modelling this is to use a quad-tree style data structure.  Each carbon atom has four connections, each oxygen two and each hydrogen one.  I don't think that this is the proper solution though.

I think that the proper solution has already been invented.  The data structure to use is a string.

Think about this.  Chemists have been modelling organic compounds for quite a long time now.  If you show a chemist CH4, they will immediately recognise that as methane.  Show them CH3CH2OH and they will recognise that as ethanol.  They recognise this because they identify the CH3CH2 combination as an "eth" compound (meaning two carbon atoms) and the OH as an "anol" or alcohol group.

We also have a pre-existing methodology for searching and identifying substrings - regular expressions.

So to represent programatically an organic compound, I would define a compound as containing a string which represents its chemical formula and a string defining its chemical name.  It could have methods which identified which "special" properties the compound had.

An example class in C#:

```<code>public class OrganicCompound
{
    private Regex benzineRingRegex;

    public OrganicCompound(string formula, NameCalculator nameCalculator, Regex benzineRingRegex)
    {
        this.Formula = formula;
        this.Name = nameCalculator.CalculateName(formula);
        this.benzineRingRegex = benzineRingRegex
    }

    public string Formula { get; private set; }

    public string Name { get; private set; }

    public bool HasBenzeneRing()
    {
        return Regex.IsMatch(this.Formula, benzineRingRegex);
    }
}
</code>```

Obviously you would need to write the nameCalculator class, which calculates the name based off of the formula.  You would need to create the regex which defines a benzine ring.  Define extra regexes for each of the groups you wish to search for.

The advantage of modelling the compounds this way is it's in the language that is exactly in the business domain of the end user.  All you as the developer needs to know is the strings to search for, which can easily be provided by either a text book or a chemist.

If structural representations of these chemicals are required, I suggest looking into maintaining SMILES representations of the formula.

SMILES chemical formula representation

Body:
The first temptation with modelling this is to use a quad-tree style data structure.  Each carbon atom has four connections, each oxygen two and each hydrogen one.  I don't think that this is the proper solution though.

I think that the proper solution has already been invented.  The data structure to use is a string.

Think about this.  Chemists have been modelling organic compounds for quite a long time now.  If you show a chemist CH4, they will immediately recognise that as methane.  Show them CH3CH2OH and they will recognise that as ethanol.  They recognise this because they identify the CH3CH2 combination as an "eth" compound (meaning two carbon atoms) and the OH as an "anol" or alcohol group.

We also have a pre-existing methodology for searching and identifying substrings - regular expressions.

So to represent programatically an organic compound, I would define a compound as containing a string which represents its chemical formula and a string defining its chemical name.  It could have methods which identified which "special" properties the compound had.

An example class in C#:

public class OrganicCompound
{
    private Regex benzineRingRegex;

    public OrganicCompound(string formula, NameCalculator nameCalculator, Regex benzineRingRegex)
    {
        this.Formula = formula;
        this.Name = nameCalculator.CalculateName(formula);
        this.benzineRingRegex = benzineRingRegex
    }

    public string Formula { get; private set; }

    public string Name { get; private set; }

    public bool HasBenzeneRing()
    {
        return Regex.IsMatch(this.Formula, benzineRingRegex);
    }
}

Obviously you would need to write the nameCalculator class, which calculates the name based off of the formula.  You would need to create the regex which defines a benzine ring.  Define extra regexes for each of the groups you wish to search for.

The advantage of modelling the compounds this way is it's in the language that is exactly in the business domain of the end user.  All you as the developer needs to know is the strings to search for, which can easily be provided by either a text book or a chemist.

If structural representations of these chemicals are required, I suggest looking into maintaining SMILES representations of the formula.

SMILES chemical formula representation


问:
Legitimate cases of having .equals() behaving inconsistently with .compareTo()?
Java documentation says it's "strongly recommended" to have them behaving consistently.

But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo()?

答:
This confusion would occur in situations where there are conflicting understandings of equals.

compareTo is 'easy' in that it asks a simple question 'which one is bigger?' If you were given a bunch of Things, how do you sort them?

equals on the other hand wants to ask 'are these the same thing?'

BigDecimal in Java is one such place where there are conflicting understandings of what it means to have two things being equal.

```<code>BigDecimal foo = new BigDecimal("1.00");
BigDecimal bar = new BigDecimal("1.000");
</code>```

These two entires will have the same meaning for sorting.  They, however, are not the same when it comes to equality. They have a different underlying state (the precision of the number) and that means they are not equal but foo.compareTo(bar) will return 0.

Consider this, if you had a Map qux = HashMap<BigDecimal, Object>() for some reason, do you want qux.put(foo,foo) to take the same spot as qux.put(bar,bar) and thus evict the earlier insertion?

So, while they are math equals (which is how compareTo sorts them), they are not inner state equals, and thus the necessity of the inconsistency here.

Yes, this inconsistency comes at the price of a higher cognitive load for dealing with BigDecimal.  It means maps may not behave like you want them to... and the question is "which map do you want to behave 'right'?"

```<code>import java.math.BigDecimal;
import java.util.HashMap;
import java.util.TreeMap;

class Main {
    public static void main (String[] args) {
        BigDecimal foo = new BigDecimal("1.00");
        BigDecimal bar = new BigDecimal("1.000");

        HashMap<BigDecimal, String> hash = new HashMap();
        TreeMap<BigDecimal, String> tree = new TreeMap();

        hash.put(foo, "foo");
        hash.put(bar, "bar");

        tree.put(foo, "foo");
        tree.put(bar, "bar");

        System.out.println("hash foo: " + hash.get(foo));
        System.out.println("hash bar: " + hash.get(bar));

        System.out.println("tree foo: " + tree.get(foo));
        System.out.println("tree bar: " + tree.get(bar));
    }
}
</code>```

ideone

Output:

```<code>hash foo: foo
hash bar: bar
tree foo: bar
tree bar: bar
</code>```

Because compareTo returned 0, in the TreeMap, bar evicted foo when bar was inserted.  However, because these are different objects with different internal state and thus different hash codes, they were both able to exist within a HashMap.

From the docs:

Note: care should be exercised if BigDecimal objects are used as keys in a SortedMap or elements in a SortedSet since BigDecimal's natural ordering is inconsistent with equals. See Comparable, SortedMap or SortedSet for more information.

And so, thats the problem, the inconsistency and the "there's no good answer to this" dilemma.

One could also imagine this with a Rational class where one wants to keep 2/4 having the internal state of 2/4 so that:

```<code>Rational twoFourths = new Rational(2,4);
Rational oneHalf = new Rational(1,2);

System.out.println(twoFourths); // prints 2/4
System.out.println(oneHalf);    // prints 1/2
System.out.println(twoFourths.compareTo(oneHalf)); // prints 0
System.out.println(twoFourths.equals(oneHalf));    // ???
</code>```

And you are once again up against that same question.  Are these equal with the mathematical sense of equality (which means the hashCode needs to also return the same value?) or are they not equal using the object oriented state of the object sense of equality despite being the 'same'.

Body:
This confusion would occur in situations where there are conflicting understandings of equals.

compareTo is 'easy' in that it asks a simple question 'which one is bigger?' If you were given a bunch of Things, how do you sort them?

equals on the other hand wants to ask 'are these the same thing?'

BigDecimal in Java is one such place where there are conflicting understandings of what it means to have two things being equal.

BigDecimal foo = new BigDecimal("1.00");
BigDecimal bar = new BigDecimal("1.000");

These two entires will have the same meaning for sorting.  They, however, are not the same when it comes to equality. They have a different underlying state (the precision of the number) and that means they are not equal but foo.compareTo(bar) will return 0.

Consider this, if you had a Map qux = HashMap<BigDecimal, Object>() for some reason, do you want qux.put(foo,foo) to take the same spot as qux.put(bar,bar) and thus evict the earlier insertion?

So, while they are math equals (which is how compareTo sorts them), they are not inner state equals, and thus the necessity of the inconsistency here.

Yes, this inconsistency comes at the price of a higher cognitive load for dealing with BigDecimal.  It means maps may not behave like you want them to... and the question is "which map do you want to behave 'right'?"

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.TreeMap;

class Main {
    public static void main (String[] args) {
        BigDecimal foo = new BigDecimal("1.00");
        BigDecimal bar = new BigDecimal("1.000");

        HashMap<BigDecimal, String> hash = new HashMap();
        TreeMap<BigDecimal, String> tree = new TreeMap();

        hash.put(foo, "foo");
        hash.put(bar, "bar");

        tree.put(foo, "foo");
        tree.put(bar, "bar");

        System.out.println("hash foo: " + hash.get(foo));
        System.out.println("hash bar: " + hash.get(bar));

        System.out.println("tree foo: " + tree.get(foo));
        System.out.println("tree bar: " + tree.get(bar));
    }
}

ideone

Output:

hash foo: foo
hash bar: bar
tree foo: bar
tree bar: bar

Because compareTo returned 0, in the TreeMap, bar evicted foo when bar was inserted.  However, because these are different objects with different internal state and thus different hash codes, they were both able to exist within a HashMap.

From the docs:

Note: care should be exercised if BigDecimal objects are used as keys in a SortedMap or elements in a SortedSet since BigDecimal's natural ordering is inconsistent with equals. See Comparable, SortedMap or SortedSet for more information.

And so, thats the problem, the inconsistency and the "there's no good answer to this" dilemma.

One could also imagine this with a Rational class where one wants to keep 2/4 having the internal state of 2/4 so that:

Rational twoFourths = new Rational(2,4);
Rational oneHalf = new Rational(1,2);

System.out.println(twoFourths); // prints 2/4
System.out.println(oneHalf);    // prints 1/2
System.out.println(twoFourths.compareTo(oneHalf)); // prints 0
System.out.println(twoFourths.equals(oneHalf));    // ???

And you are once again up against that same question.  Are these equal with the mathematical sense of equality (which means the hashCode needs to also return the same value?) or are they not equal using the object oriented state of the object sense of equality despite being the 'same'.


问:
Why is .compareTo() in an interface while .equals() is in a class in Java?
I want to know why the .compareTo() is in the Comparable interface while a method like .equals is in the Object class. To me, it seems arbitrary why a method like .compareTo() is not in the Object class already.

To use .compareTo(), you implement the Comparable interface and implement the .compareTo() method for your purposes. For the .equals() method, you simply override the method in your class, since all classes inherit from the Object class.

My question is why is a method like .compareTo() in an interface that you implement rather than in a class like Object? Likewise, why is the .equals() method in the class Object and not in some interface to be implemented?

答:
The JLS §4.3.2 defines the class object in the following way:

4.3.2. The Class Object

The class Object is a superclass (§8.1.4) of all other classes.

All class and array types inherit (§8.4.8) the methods of class Object, which are summarized as follows:

The method clone is used to make a duplicate of an object.

The method equals defines a notion of object equality, which is based on value, not reference, comparison.

The method finalize is run just before an object is destroyed (§12.6).

The method getClass returns the Class object that represents the class of the object.

A Class object exists for each reference type. It can be used, for example, to discover the fully qualified name of a class, its members, its immediate superclass, and any interfaces that it implements.

The type of a method invocation expression of getClass is Class<? extends |T|> where T is the class or interface searched (§15.12.1) for getClass.

A class method that is declared synchronized (§8.4.3.6) synchronizes on the monitor associated with the Class object of the class.

The method hashCode is very useful, together with the method equals, in hashtables such as java.util.Hashmap.

The methods wait, notify, and notifyAll are used in concurrent programming using threads (§17.2).

The method toString returns a String representation of the object.

So, that's why equals is in Object but compareTo is in a separate interface. I would speculate that they wanted to keep Object as minimal as possible. They probably figured that nearly all Objects would need equals and hashCode (which is really just a form of equality testing) but not all objects would need to have a concept of ordering, which is what compareTo is used for.


问:
How to work on a program from any computer that is connected to the internet?
I apologize if this question is a duplicate but I am having trouble phrasing my question. I am a beginner and for the last months I have been working on a Java program. Sometimes I work on the go from my laptop and sometimes I work at home from my desktop. This means that if I am done writing some code in the desktop then I have to upload all the files to Google Drive and then download them again when I work on my laptop and vice versa. I am switching computers more often and it's becoming tedious to have to do this uploading and downloading to Google Drive all the time (open browser, delete old files from computer, download new files from Drive, move files from Download folder to the program folder).

Is there something more convenient? Something that I can run from the terminal that will immediately save my files to some server and then allow me to pull them from the server to any computer?

答:
Make a cloud machine your workstation.

The good: Access it from anywhere.

The bad: never as good as a local desktop.

Or: make a cloud file system your source file system.

The good: No uploading and downloading

The bad: accessing the files is going to be slow.

The bad: you have to maintain duplicate development environments everwhere.

Or: pick your primary desktop. Use VNC or Windows Remote to access it when
it's not your local desktop.


答:
Not all objects can be compared, but all objects can be checked for equality. If nothing else, one can see if two objects exist at the same location in memory (reference equality).

What does it mean to compareTo() on two Thread objects? How is one thread "greater than" another? How do you compare two ArrayList<T>s?

The Object contract applies to all Java classes. If even one class cannot be compared to other instances of its own class, then Object cannot require it to be part of the interface.

Joshua Bloch uses the key words "natural ordering" when explaining why a class might want to implement Comparable. Not every class has a natural ordering as I mentioned in my examples above, so not every class should implement Comparable nor should Object have the compareTo method.

...the compareTo method is not declared in Object. ... It is
  similar in character to Object's equals method, except that it
  permits order comparisons in addition to simple equality comparisons,
  and it is generic. By implementing Comparable, a class indicates
  that its instances have a natural ordering.

Effective Java, Second Edition: Joshua Bloch. Item 12, Page 62. Ellipses remove references to other chapters and code examples.

For cases where you do want to impose an ordering on a non-Comparable class that does not have a natural ordering, you can always supply a Comparator instance to help sort it.

Title: Why is .compareTo() in an interface while .equals() is in a class in Java?

Body:
I want to know why the .compareTo() is in the Comparable interface while a method like .equals is in the Object class. To me, it seems arbitrary why a method like .compareTo() is not in the Object class already.

To use .compareTo(), you implement the Comparable interface and implement the .compareTo() method for your purposes. For the .equals() method, you simply override the method in your class, since all classes inherit from the Object class.

My question is why is a method like .compareTo() in an interface that you implement rather than in a class like Object? Likewise, why is the .equals() method in the class Object and not in some interface to be implemented?


答:
(Biochemistry graduate with 30 years software development experience)

Non-organic molecules are "relatively" simple.  The interesting ones are the ones that can bond with themselves e.g. C, N, O, Si because you can get some really funky combinations.  The Benzene ring is a very simple example.  Some variations substitute a Nitrogen for one of the Carbons and it gets weird fast.

I'd start with an "atom" object with the various types of atom inheriting from it.

Each "atom" object  would contain a list of atom objects to represent the various bonds so Nitrogen would have a list of fixed size 3.  It could then store links to three other atoms.  A double bond could be represented as a duplicate entry.

Each atom would have rules embedded about what it can legally bond to and how.

So you can make up reasonably complicated molecules unambiguously - because bond 3 on the Carbon #1 is linked to bond 1 on Hydrogen 2 etc.

Hope that makes sense...

Title: What data structure would you use to represent an organic compound?

Body:
Are there any good data structures out there that can be used to represent a molecule?

I was thinking maybe I represent it as a Graph by making every atom a vertex, however, it's common for organic compounds to have lots of Carbons and Hydrogens. How would you number it? Is there a good way to represent molecules, but at the same time, have an efficient .contains() method?

One of the most basic uses for this would be to check if a compound contains carbonyl group, or a benzylic hydrogen, or even a benzene ring.


答:
Problem with working on different pc's on the same code/project?

This issue was also my problem before, luckily I found out about revision control systems..

I used git as my tool so whenever I modify my code to my pc at home, as I continue to code at my office, I could just update it flawlessly using git pull and when I finish updating my code I will just update the repo by git push origin master and so..

You can also modify your code in your workplace and in home pc with different codes and just merge the codes later..

there are other tools like this: svn, cvs, etc.. but I would suggest GIT...

for more info on git, visit this link.

Title: How to work on a program from any computer that is connected to the internet?

Body:
I apologize if this question is a duplicate but I am having trouble phrasing my question. I am a beginner and for the last months I have been working on a Java program. Sometimes I work on the go from my laptop and sometimes I work at home from my desktop. This means that if I am done writing some code in the desktop then I have to upload all the files to Google Drive and then download them again when I work on my laptop and vice versa. I am switching computers more often and it's becoming tedious to have to do this uploading and downloading to Google Drive all the time (open browser, delete old files from computer, download new files from Drive, move files from Download folder to the program folder).

Is there something more convenient? Something that I can run from the terminal that will immediately save my files to some server and then allow me to pull them from the server to any computer?


问:
How to get real time notifications, when a database change (insert, update, delete) occurs?
I'm creating a dashboard which should monitor a database table. I have only database access (no application layer). The table is rather large (10 million rows), however not changing rapidly (100 inserts/updates per minute)

How can I find out whether the table changed? I would try to hit the database every second, but this seems like a brute-force approach...

Databases: MySQL/Postgres

答:
You can use triggers.</p>

```<code>CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
   EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'DB AutoMailer',
        @recipients = 'user@example.com',
        @body = 'The DB has changed',
        @subject = 'DB Change';
GO
</code>```

Body:
You can use triggers.

CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
   EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'DB AutoMailer',
        @recipients = 'user@example.com',
        @body = 'The DB has changed',
        @subject = 'DB Change';
GO