问:
Using a GPLv2 library in a web project
I'm trying to understand the way that GPLv2 works, and have a couple of questions.
I'm going to describe a couple of scenarios, and want to know how GPL applies there.

I make a web application that uses a GPLv2 library. I put this project in a public repository (github). The project calls functions from the library, but does not actually include its source - it just pulls it from the developers repository via a package manager during deployment. Do I still need to license the project as GPLv2?

The same scenario, but I do NOT put the project in a public repository. As far as I understand this would not count as "distribution", so I don't have to bother with GPLv2 at all?

I make a project that is built on top of a BSD-3 licensed framework and also use a GPLv2 library. Parts of the framework are included in the project, but the GPLv2 library is only downloaded during deployment. Which license has higher precedence then? Do I license my project under BSD-3 or GPLv2?

答:
When you use a GNU GPL library then the whole software needs to be licensed under the GNU GPL. There is a variant of the GPL, the LGPL (Lesser GPL or Library GPL), which allows to call the library from a non-GPL software. But the authors of the library seem to have intentionally picked the GPL insted of the LGPL, so their intention seems to be to not allow it to be used for non-GPL software. Your build process is irrelevant. What matters is if the software is usable without the GPL component. When it is not, you need to license it under GPL.

The BSD-License, on the other hand, is a so-called "permissive" license. You can use BSD-code in a project and still license it under a different license as long as you follow the requirements of the BSD regarding attributing the original authors and the license conditions of their code (which only applies to their code, not what you built around it).

tl;dr: your whole project needs to be licensed under GPLv2

Rearding not putting the sourcecode on a public repository: When it is a web application, does it include Javascript code which is executed in the client browser? When that is the case, that Javascript code is distributed to your visitors and needs to be licensed to them under GNU GPL. But any code you only use server-sided is not distributed to the users, which means that you don't have to publish the sourcecode (there is another variant of the GPL, the AGPL, which also requires to license the software to anyone who uses it via a network, but the normal GPL does not have this clause).

Title: Using a GPLv2 library in a web project


问:
Should I use multivalued attributes in conceptual modelling?
My team and I have designed a simple, affordable conceptual modelling language as part or a larger research project. This language is aimed to end users with little or no training in information technologies. It allows them to create class models using basic constructs such as classes, attributes, associations, and the like.

The language is working nicely, but we are considering whether we should add multivalued attributes to it. In the OO paradigm, attributes are usually considered to be single-valued, i.e. they can take a value on each instance of a class, or they can be null, but they can never take multiple simultaneous values. However, some situations in certain application domains call for multivalued attributes. For example, imagine a Garment class with a Colour attribute. That attribute may as well be multivalued, since garments can be multi-coloured: the shirt I'm wearing as type this is white and purple.

However, very few approaches to OO conceptual modelling use multivalued attributes, and none of them are mainstream as far as I know. I seem to recall reading that multivalued attributes are not a good way to model things, but I can't recall a sound reason, and I can't think of one, and I refuse to accept this at face value. In addition, most of the work I know of about multivalued attributes is at the database level rather than at the conceptual modelling level.

So, my question is: Do you think that multivalued attributes make sense in a conceptual modelling language? Can you point me to any books, papers or other sources that discuss this? Thank you.

答:
Sure, I use MV attributes every day. I work with a Multi-valued database called Unidata. These types of databases violate First Normal Form.

MV is easier to understand for the average hunter and you can still normalize it out to join tables under the hood if needed.

ContentLicense: CC BY-SA 2.5


问:
C++: Should class own or observe its dependencies?
Say I have a class Foobar that uses (depends on) class Widget. In good ol' days, Widget wolud be declared as a field in Foobar, or maybe as a smart pointer if polymorphic behavior was needed, and it would be initialized in constructor:

```<code>class Foobar {
    Widget widget;
    public:
    Foobar() : widget(blah blah blah) {}
    // or
    std::unique_ptr<Widget> widget;
    public:
    Foobar() : widget(std::make_unique<Widget>(blah blah blah)) {}
    (…)
};
</code>```

And we'd be all set and done. Unfortunately, today, Java kids will laugh at us once they see it, and rightfully, as it couples Foobar and Widget together. The solution is seemingly simple: apply Dependency Injection to take construction of dependencies out of Foobar class. But then, C++ forces us to think about ownership of dependencies. Three solutions come to mind:

Unique pointer

```<code>class Foobar {
    std::unique_ptr<Widget> widget;
    public:
    Foobar(std::unique_ptr<Widget> &&w) : widget(w) {}
    (…)
}
</code>```

Foobar claims sole ownership of Widget that is passed to it. This has following advantages:

Impact on performance is negligible.

It's safe, as Foobar controls lifetime od its Widget, so it makes sure that Widget doesn't suddenly disappear.

It's safe that Widget won't leak and will be properly destructed when no longer needed.

However, this comes at a cost:

It places restrictions on how Widget instances can be used, e.g. no stack-allocated Widgets can be used, no Widget can be shared.

Shared pointer

```<code>class Foobar {
    std::shared_ptr<Widget> widget;
    public:
    Foobar(const std::shared_ptr<Widget> &w) : widget(w) {}
    (…)
}
</code>```

This is probably closest equivalent ot Java and other garbage collected languages. Advantages:

More universal, as it allows sharing dependencies.

Maintains safety (points 2 and 3) of unique_ptr solution.

Disadvantages:

Wastes resources when no sharing is involved.

Still requires heap allocation and disallows stack-allocated objects.

Plain ol' observing pointer

```<code>class Foobar {
    Widget *widget;
    public:
    Foobar(Widget *w) : widget(w) {}
    (…)
}
</code>```

Place raw pointer inside class and shift the burden of ownership to someone else. Pros:

As simple as it can get.

Universal, accepts just any Widget.

Cons:

Not safe anymore.

Introduces another entity that is responsible for ownership of both Foobar and Widget.

Some crazy template metaprogramming

The only advantage I can think of is that I'd be able to read all those books I didn't find time for while my software is builing;)

I lean towards the third solution, as it is most universal, something has to manage Foobars anyway, so managing Widgets is simple change. However, using raw pointers bothers me, on the other hand smart pointer solution feel wrong to me, as they make consumer of dependency restrict how that dependency is created.

Am I missing something? Or is just Dependency Injection in C++ not trivial? Should class own its dependencies or just observe them?

答:
You ignored a fourth possible answer, which combines the first code you posted (the "good ol' days" of storing a member by value) with dependency injection:

```<code>class Foobar {
    Widget widget;
public:
    Foobar(Widget w) // pass w by value
     : widget{ std::move(w) } {}
};
</code>```

Client code can then write:

```<code>Widget w;
Foobar f1{ w }; // default: copy w into f1
Foobar f2{ std::move(w) }; // move w into f2
</code>```

Representing the coupling between objects should not be done (purely) on the criteria you listed (that is, not based purely on "which is better for safe lifetime management").

You can also use conceptual criteria ("a car has four wheels" vs. "a car uses four wheels which the driver has to bring along").

You can have criteria imposed by other APIs (if what you get from an API is a custom wrapper or a std::unique_ptr for example, the options in your client code are limited as well).

ContentLicense: CC BY-SA 3.0

Body:
You ignored a fourth possible answer, which combines the first code you posted (the "good ol' days" of storing a member by value) with dependency injection:

class Foobar {
    Widget widget;
public:
    Foobar(Widget w) // pass w by value
     : widget{ std::move(w) } {}
};

Client code can then write:

Widget w;
Foobar f1{ w }; // default: copy w into f1
Foobar f2{ std::move(w) }; // move w into f2

Representing the coupling between objects should not be done (purely) on the criteria you listed (that is, not based purely on "which is better for safe lifetime management").

You can also use conceptual criteria ("a car has four wheels" vs. "a car uses four wheels which the driver has to bring along").

You can have criteria imposed by other APIs (if what you get from an API is a custom wrapper or a std::unique_ptr for example, the options in your client code are limited as well).


问:
Maintaing drop down lists for the application
What would be the best approach to maintain the dropdown lists for the whole application (like city, state etc) taking into account the SOLID principles and performance?

Right now am loading the list values into a static property and using the same like

```<code>public int DestCountry { get; set; }

private string _CountryText;
public string CountryText
{
    get
    {
        if (this.DestCountry > 0)
        {
            _CountryText = Lists.CountryList.Find(x => x.Value == Convert.ToString(this.DestCountry)).Text;
        }
        return _CountryText;
    }
}
</code>```

But I am not sure whether this is the best approach possible. Could you please suggest.

答:
This depends on some different factors:

first, who is responsible for maintaining them (the developer of the application, the user, some power users, an admin)?

is the list fixed for one version of the application, or is there a requirement to change those values without delivering a new version?

are those really fixed texts in one language, or do you expect them to be localized?

is the list of values only needed in one form/dialog/class, or will the list be needed in different places in the application?

if it is needed in different places, is it needed always in exactly the same way, or will it be sometimes needed in modified ways? For example, does it have to be extended, depending on the context?

if the chosen dropdown value has to be stored somewhere (for example, in a database), how will it be stored? As a fixed text? As an index? Where will the mapping index-to-text take place?

If you know the answer to those questions, I am sure you can work out by yourself where the best place is for your specific case. It may be either a hardcoded list in the form, a list in a reusable or extentable class, it maybe stored in a resource file, in a configuration file or in a database. Just avoid to store the same information in two different places.


问:
Throwing an exception if some property is not present in a properties file
it's not a big programming problem, but I'm curious if it should be done better. So I have a config file which I'm reading via java.util.Properties class. When property is not present in a file getProperty() method returns null. I would like to throw an exception if any property is not present in config file. So how should I do it?

Two ideas comes to mind, but I think there should be other way to do it. The first is that after every call of getProperty() I would do if (prop == null) throw new SomeException, but it wouldn't look nice if there would be identical ifs after every two lines. Second approach is to make one big if after all properties are read and just check them all at once.

答:
Third option is that you create a derived class of Properties that does this for you:

```<code>public class Configuration extends Properties {
    public String getProperty(final String key) {
        final String property = super.getProperty(key);
        if(property == null) {
            throw new InvalidParameterException(MessageFormat.format("Missing value for key {0}!", key)));
        }
        return property;
    }

    public String getProperty(final String key, final String defaultValue) {
        // Throw exception here as above if you want to throw exception even with defaultValue
        return super.getProperty(key, defaultValue);
    }
}
</code>```

I call it Configuration because it is a scenario in which missing properties might be cause to throw an exception, though you're welcome to call it as you wish.  As it is now, calling getProperty given parameter defaultValue will not throw an exception (since presumably you're okay with a value not being there).

On a side note, you should ask yourself if this is how you truly want to handle this.  It may happen that there aren't values that you expect to find in a property file.  In that case there is nothing exceptional about it.  However if you expect to find very specific values that will cause the application to fail if they aren't present, then this solution is satisfactory.

I hope that helps.

Body:
Third option is that you create a derived class of Properties that does this for you:

public class Configuration extends Properties {
    public String getProperty(final String key) {
        final String property = super.getProperty(key);
        if(property == null) {
            throw new InvalidParameterException(MessageFormat.format("Missing value for key {0}!", key)));
        }
        return property;
    }

    public String getProperty(final String key, final String defaultValue) {
        // Throw exception here as above if you want to throw exception even with defaultValue
        return super.getProperty(key, defaultValue);
    }
}

I call it Configuration because it is a scenario in which missing properties might be cause to throw an exception, though you're welcome to call it as you wish.  As it is now, calling getProperty given parameter defaultValue will not throw an exception (since presumably you're okay with a value not being there).

On a side note, you should ask yourself if this is how you truly want to handle this.  It may happen that there aren't values that you expect to find in a property file.  In that case there is nothing exceptional about it.  However if you expect to find very specific values that will cause the application to fail if they aren't present, then this solution is satisfactory.

I hope that helps.


问:
Why do we have to wait for I/O?
It's always been known that Disk operations are slow and we know the reasons why they are slow.
So the question here is why do we have to wait for I/O or why is there such a thing as IOWait, etc.?

I mean I've noticed that when you're doing some I/O tasks in the background, your computer basically gets a lot slower, I've especially noticed that when using Linux, if you're doing some longer I/O tasks, the OS becomes almost unusable until they are completed.

Indeed, I also found this topic in an article, there's a snippet:

I/O wait is 12.1%. This server has 8 cores (via cat /proc/cpuinfo). This is very close to (1/8 cores = 0.125)

So basically it means it's slowing down the computer a LOT, why is that? I mean OK, now the normal computer are at least 2 cores, sometimes 4 or sometimes they have more because of hyperthreading or something like that. But now the question is why the CPU actually has to stay there, practically not doing anything else than just waiting for IO? I mean the basic idea or architecture of the process managament, now I don't know whether it's the OS who's responsible for that, or does it come down to the hardware part, but it should be made possible for the cpu to wait or to check regularly, while actually performing lots of other tasks and only going back to the IO process when it's ready. Indeed, if that's such a difficult task and the cpu would have to wait, why isn't that managed by hardware more efficiently then? Like for instance there could be some kind of mini cpu which would just wait for it and deliver the small part of data to the real cpu as soon as it gets back to the process and so the process would be repeated and we wouldn't have to practically dedicate a whole cpu core for the data copy process... Or would I be the one who should invent this kind of stuff and get a nobel prize for that? :S

Now okay, I'm really putting it now from an observers perspective and I really haven't gone that deep into the topic, but I really don't understand why the cpu has to work with the speed of HDD, while it could just do something else and come back to HDD once it's ready. The idea is not to speed up the application who needs that IO operation or the copy process or whatever, but the idea is to just minimally affect the CPU consumption while performing that operation, so that the OS could utilise it for other processes and the user wouldn't have to feel general computer lag when doing some copying operations...

答:
It does depend upon your application code. I am supposing your code is running on Linux.

You could use multi-threading (e.g. POSIX pthreads) to have compute-bound threads doing some computation while other IO-bound threads are doing the IO (and waiting for it). You could even have your application running several processes communicating with inter-process communication (IPC), see pipe(7), fifo(7), socket(7), unix(7), shm_overview(7), sem_overview(7), mmap(2), eventfd(2) and read Advanced Linux Programming etc....

You could use non-blocking IO, e.g. pass O_NOBLOCK to open(2) etc etc etc...; then you'll need to poll(2) and/or use SIGIO signal(7)... and handle the EWOULDBLOCK error from read(2) etc...

You could use POSIX asynchronous IO, see aio(7)

For file access, you could give hints to the page cache, e.g. with madvise(2) after mmap(2) and with posix_fadvise(2); see also the Linux specific readahead(2)

But you would eventually reach some hardware bottleneck (the bus, the RAM, etc...). See also ionice(1)

Title: Why do we have to wait for I/O?


答:
It's possible to write asynchronous IO where you tell the OS to dispatch a disk read/write and then go do something else and then later check if it's done. It's far from new. An older method is using another thread for the IO.

However that requires that you have something to do while that read is being executed and you will not be allowed to touch the buffer you passed in for the result.

It's also much easier to program when you assume everything is blocking IO.

When you call a blocking read function you know it won't return until something has been read and immediately after you can start processing on it.

The typical read loop is a good example

//variables that the loop uses
char[1024] buffer;
while((read = fread(buffer, 1024, 1, file))>0){
    //use buffer
}
```

<p>Otherwise you need to save the current function state (usually in the form of a callback + userData pointer) and pass it + identifier of the read operation back up to a <code>select()</code> type loop. There if an operation is finished it will map the identifier of the read operation to the callback+data pointer and invoke the callback with information of the completed operation.</p>

<pre class="lang-c prettyprint-override"><code>void callback(void* buffer, int result, int fd, void* userData){
    if(result<=0){
    //done, free buffer and continue to normal processing
    }
    //use buffer

    int readID = async_read(fd, buffer, userData->buff_size);
    registerCallback(readId, callback, userData);
}
</code>```

This also means that every function that could end up using that async read would need to be able to handle a async continuation. That is a non-trivial change throughout most programs, you ask people trying to get into async C# about that.

However synchronous IO vs. asynchronous IO isn't the cause of the general slowdown. Swapping pages in is also an operation that needs to wait on IO. The scheduler will just switch to another program that isn't waiting on IO if one is (IO wait is when the processor is idle and there is a IO operation pending).

The real problem is that both the harddrive and the CPU use the same channel to communicate with the RAM; the memory bus. And unless you are using RAID then there is only a single disk to get the data from. This is made worse if you are also using a graphics intensive application, then the communication with the GPU will also interfere.

In other words the real bottleneck is probably in the hardware rather then the software.

Title: Why do we have to wait for I/O?

Body:
It's always been known that Disk operations are slow and we know the reasons why they are slow.
So the question here is why do we have to wait for I/O or why is there such a thing as IOWait, etc.?

I mean I've noticed that when you're doing some I/O tasks in the background, your computer basically gets a lot slower, I've especially noticed that when using Linux, if you're doing some longer I/O tasks, the OS becomes almost unusable until they are completed.

Indeed, I also found this topic in an article, there's a snippet:

I/O wait is 12.1%. This server has 8 cores (via cat /proc/cpuinfo). This is very close to (1/8 cores = 0.125)

So basically it means it's slowing down the computer a LOT, why is that? I mean OK, now the normal computer are at least 2 cores, sometimes 4 or sometimes they have more because of hyperthreading or something like that. But now the question is why the CPU actually has to stay there, practically not doing anything else than just waiting for IO? I mean the basic idea or architecture of the process managament, now I don't know whether it's the OS who's responsible for that, or does it come down to the hardware part, but it should be made possible for the cpu to wait or to check regularly, while actually performing lots of other tasks and only going back to the IO process when it's ready. Indeed, if that's such a difficult task and the cpu would have to wait, why isn't that managed by hardware more efficiently then? Like for instance there could be some kind of mini cpu which would just wait for it and deliver the small part of data to the real cpu as soon as it gets back to the process and so the process would be repeated and we wouldn't have to practically dedicate a whole cpu core for the data copy process... Or would I be the one who should invent this kind of stuff and get a nobel prize for that? :S

Now okay, I'm really putting it now from an observers perspective and I really haven't gone that deep into the topic, but I really don't understand why the cpu has to work with the speed of HDD, while it could just do something else and come back to HDD once it's ready. The idea is not to speed up the application who needs that IO operation or the copy process or whatever, but the idea is to just minimally affect the CPU consumption while performing that operation, so that the OS could utilise it for other processes and the user wouldn't have to feel general computer lag when doing some copying operations...

Body:
It's possible to write asynchronous IO where you tell the OS to dispatch a disk read/write and then go do something else and then later check if it's done. It's far from new. An older method is using another thread for the IO.

However that requires that you have something to do while that read is being executed and you will not be allowed to touch the buffer you passed in for the result.

It's also much easier to program when you assume everything is blocking IO.

When you call a blocking read function you know it won't return until something has been read and immediately after you can start processing on it.

The typical read loop is a good example

//variables that the loop uses
char[1024] buffer;
while((read = fread(buffer, 1024, 1, file))>0){
    //use buffer
}

Otherwise you need to save the current function state (usually in the form of a callback + userData pointer) and pass it + identifier of the read operation back up to a select() type loop. There if an operation is finished it will map the identifier of the read operation to the callback+data pointer and invoke the callback with information of the completed operation.

void callback(void* buffer, int result, int fd, void* userData){
    if(result<=0){
    //done, free buffer and continue to normal processing
    }
    //use buffer

    int readID = async_read(fd, buffer, userData->buff_size);
    registerCallback(readId, callback, userData);
}

This also means that every function that could end up using that async read would need to be able to handle a async continuation. That is a non-trivial change throughout most programs, you ask people trying to get into async C# about that.

However synchronous IO vs. asynchronous IO isn't the cause of the general slowdown. Swapping pages in is also an operation that needs to wait on IO. The scheduler will just switch to another program that isn't waiting on IO if one is (IO wait is when the processor is idle and there is a IO operation pending).

The real problem is that both the harddrive and the CPU use the same channel to communicate with the RAM; the memory bus. And unless you are using RAID then there is only a single disk to get the data from. This is made worse if you are also using a graphics intensive application, then the communication with the GPU will also interfere.

In other words the real bottleneck is probably in the hardware rather then the software.


答:
Have faith that the processing of other stuff while waiting for I/O is quite streamlined, close to as streamlined as possible.  When you see that your computer is waiting for I/O only 12.1% of the time, it means that it is in fact doing a lot of other things in parallel.  If it really had to wait for I/O without doing anything else, it would be waiting for 99.9% of the time, that's how slow I/O is.

The only way to do more things in parallel is by predicting what the user might want to do next, and we are not very good at that kind of prediction yet.  So, if the user performs an operation which requires a particular sector to be read from the hard drive, and that sector does not already happen to be in the cache, then the OS will start the very long process of reading that sector, and it will try to see if there is anything else to do in the mean time.  If there is another user who wants a different sector, it will queue that request too. At some point, all requests have been queued, and there is nothing we can do but wait for the first one of them to be satisfied before we can proceed.  It is just a fact of life.

EDIT:

Finding a solution to the problem of how to do other stuff while doing I/O would be an admirable feat, because it would at the same time be a solution to the problem of how to do other stuff while idle.  An amazing feat that would be, because it would mean that you would find work for your computer to do, while it does not have any.

You see, this is what happening: your computer is just sitting 99.99% of the time, doing nothing.  When you give it something to do, it goes and does it.  If in doing so it has to wait for I/O, it sits there and waits.  If it has something else to do while doing I/O, it does that, too.  But if it does not have anything else to do besides I/O, then it has to sit there and wait for the I/O to be completed. There is no way to work around that, other than by enrolling in SETI@Home.

Title: Why do we have to wait for I/O?


答:
The I/O schemes you are describing are in current use in computers.

why the CPU actually has to stay there, practically not doing anything else than just waiting for IO?

This is the simplest possible I/O method: programmed I/O. Many embedded systems and low/end microprocessors have only a single input instruction and a single output instruction. The processor must execute an explicit sequence of instructions for every character read or written.

but it should be made possible for the cpu to wait or to check regularly, while actually performing lots of other tasks and only going back to the IO process when it's ready

Many personal computers have other I/O schemes. Instead of waiting in a tight loop for the device to become ready (busy waiting), the CPU starts the I/O device asking it to generate an interrupt when it's done (interrupt driven I/O).

Although interrupt-driven I/O is a step forward (compared to programmed I/O), it requires an interrupt for every character transmitted and it's expensive...

Like for instance there could be some kind of mini cpu which would just wait for it and deliver the small part of data to the real cpu as soon as it gets back to the process and so the process would be repeated and we wouldn't have to practically dedicate a whole cpu core for the data copy process...

The solution to many problems lies in having someone else do the work! :-)

The DMA controller/chip (Direct Memory Access) allows programmed I/O but having somebody else do it!

With DMA the CPU only has to initialize a few registers and it's free to do something else until transfer is finished (and an interrupt is raised).

Even DMA isn't totally free: high speed devices can use many bus cycles for memory references and device references (cycle stealing) and the CPU has to wait (DMA chip always has a higher bus priority).

I/O wait is 12.1%. This server has 8 cores (via cat /proc/cpuinfo). This is very close to (1/8 cores = 0.125)

I think this is from:
Understanding Disk I/O - when should you be worried?

Well it isn't strange: the system (mySQL) must fetch all the rows before manipulating data and there aren't other activities.

Here there isn't a computer architecture / OS issue. It's just how the example is set.

At most it could be a RDBMS tuning problem or a SQL query problem (missing index, bad query plan, bad query...)

Title: Why do we have to wait for I/O?


问:
Is it good to define a variable inside a loop?
My instructor once told me that I should not define a variable inside a loop, but I honestly still do not understand why.

What are the disadvantages of that?

Could any body explain that to me?

答:
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope.

What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs. Depending on how complex the right-hand side of the assignment is, this could become rather expensive and might even dominate the run time of the loop. If you write a loop that uses the same computed value in all iterations, you should definitely compute it above the loop - that is more important than minimizing its scope.

To clarify: as long as compute() always returns the same value, this

```<code>int value = compute();
while (something) {
    doSomething(value);
}
</code>```

is smarter than this:

```<code>while (something) {
    int value = compute();
    doSomething(value);
}
</code>```

Body:
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope.

What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs. Depending on how complex the right-hand side of the assignment is, this could become rather expensive and might even dominate the run time of the loop. If you write a loop that uses the same computed value in all iterations, you should definitely compute it above the loop - that is more important than minimizing its scope.

To clarify: as long as compute() always returns the same value, this

int value = compute();
while (something) {
    doSomething(value);
}

is smarter than this:

while (something) {
    int value = compute();
    doSomething(value);
}


答:
Complex types have non-trivial constructors and destructors.

Those will get called at the start and end of the loop body (as it's initialized and goes out of scope). If the initialization is expensive like it needs to allocate some memory then that should be avoided.

However for trivial types that is no problem. The allocation and deallocation itself is just adding and subtracting a value from the stack pointer. (which will get optimized out)

Title: Is it good to define a variable inside a loop?

Body:
My instructor once told me that I should not define a variable inside a loop, but I honestly still do not understand why.

What are the disadvantages of that?

Could any body explain that to me?

ContentLicense: CC BY-SA 4.0


问:
Code licensing injection and version control history
Are there licensing ramifications to having GPLed code in a public git history, but not a released version of the distributed software?

Could a repo owner be obliged to changing their licensing based on historical missteps?

This seems like it could be an avenue to inject GPL into code for projects that may not have rigorous pull criteria.

答:
The GPL doesn't necessarily care about the release state of the code.  Rather, it cares about whether the code has been intentionally distributed or not.  Hosting the code in a public repository on GitHub would certainly qualify as distributing the code.

As such, an errant pull request could have some onerous consequences to the copyright owners of the project.  In theory, an application could be effectively forced to be re-licensed by pulling in GPL'd code.1

At the same time, the FSF has indicated a need for "intent" behind distributing code under the GPL.  Since the inception of the GPL, various nefarious and hypothetical schemes have been concocted in order to force the release of source.  However, the FSF has held that owners of the code needed to have knowingly added2 GPL'd code in order for the requirements of the license to take hold.

Said another way3 - nobody can force anyone to release their own source code through the GPL. The GPL is a license, not a contract.

So an errant git pull request wouldn't necessarily force an application to become released as GPL code.  The original application owner(s) didn't intend to distribute and license the code that way.  However, once the original application owner(s) is / are notified that their application contains GPL'd code, they are obligated to either remove the GPL'd code or re-license their application under the GPL.

1 It's also worth noting that there are ways to incorporate GPL'd code into an application without impacting the existing license for the application.

2 That's "knowingly added" or "reasonably ought to have known."  The excuse of "Oh, I didn't know that GNU library was GPL'd!" is an excuse almost as old as the GPL itself.  Repository owners ought to be checking the code that's being added to their application.

3 Hat tip to Robert Harvey for that prhasing


问:
Storing an all day event in database
I have an event table that should store events (dt_start, dt_end, all_day,etc).

I saw that .ical files stores dt_start and dt_end as the same day (without time) for an "all_day" event.

Question: if I have an event on 2015.09.08 all day, how it should appear for a user that has a different  timezone? Along two days? or a single day?

答:
If someone gave that problem to me, I would probably do the following:

All the data in the system should be stored in one time zone (normally UTC), then only when the value needs to be printed to the output should time zone offset be applied.

The user sets an all day event, which would appear to the user as 00:00:00.000 - 23:59:59.999 in the user's local time. This means that finding scheduling conflicts is trivial, as opposed to having to check somehow if an event is marked as all day.

Now, as for storing it, if you have users in different time zones the best thing to do is to convert everything to UTC before storing in the database. Then when rendering a particular user's calendar, convert it to their local time for the purposes of display only.

When the user does anything date related, the backend should always be working on UTC, only ever taking into account the offset when it's time to print something to the user.

Doing it this way means you will very rarely have to worry about time zones, and checking conflicts is really simple. If a user on +6 hours looks at a user's schedule on -5 hours, the interface should ideally show the event over the time adjusted to the viewing user's time. This means an all day event in London would run from 5:00am - 4:59:59.999pm when viewed in a +5 time zone. It's no good to the person in a different time zone if his calendar shows the event over two whole days, or over one (incorrect) day as if he needs to call or be involved somehow, he may easily miss it.

EDIT

Thanks to @Blrfl for linking to it, but many DBMS's have excellent support for time zone operations built in so you might not want to do what I suggested. As for displaying it, I would still recommend displaying it as overlapping days, especially if other user's events from various timezones will be displayed on the same calendar.

Title: Storing an all day event in database


问:
Computing and returning a sub-object where the sub-object is stored in the object
I have a complex object which routinely needs to compute a sub-object representing various aspects of the parent's state as a bundle. For example, imagine the object represents information about an aircraft and the sub-object is a summary of various key parameters of the aircraft at some particular time such as its heading, speed, etc. The object needs to store the last computed version of the sub-oject.

Currently the way I do this is that I have a void method in the object that does the computation and then sets a module-level variable to be equal to the newly computed sub-oject. The outside user of this sub-object then retrieves the current sub-oject via a getter. So, for the client methods the operation looks like this:

```<code>main_object.computeState();
State new_state = main_object.getState();
</code>```

To handle possible errors, however, in the computation, which is currently not done, I am thinking of changing to a compute method that returns the state:

```<code>State new_state = main_object.computeState( error_msg );
if( new_state == null ){
   print( error_msg );
   goto failure continuation
}
.... [everything ok, continue normally ]
</code>```

Is there a better strategy for constructing this pattern?

答:
What you are suggesting is IMHO pretty straightforward, I just would consider to use exceptions for error handling if your programming language allows this. For example:</p>

```<code> try
 {
     State new_state = main_object.computeState();
     .... [everything ok, continue normally ]
 }
 catch(MyException ex)
 {
    print( ex.error_msg );
    ... do further error processing
 }
</code>```

Body:
What you are suggesting is IMHO pretty straightforward, I just would consider to use exceptions for error handling if your programming language allows this. For example:

 try
 {
     State new_state = main_object.computeState();
     .... [everything ok, continue normally ]
 }
 catch(MyException ex)
 {
    print( ex.error_msg );
    ... do further error processing
 }


问:
Is this the correct way to think about the client/server socket relationship?
I'm designing a distributed application, very basic for now. The idea is that once the application is active on all machines (about 5 vms), you can initiate a grep on all log files from all machines from any one machine.

Generally, the steps would be:

Launch the application on all machines

All applications pause in a wait condition of Press [Enter] to continue...

Once [Enter] is pressed, that particular machine is the issuer of commands, so to speak

You type your desired pattern, and it issues the commands to all machines, pulling down the results

At first, my plan was to do connection setup after the user pressed [Enter], setting up a client connection for the host issuing the commands, and server connections on the rest; but this seems not very scalable. My idea now is to just initiate all connections from the start, both a client and server, and just always be polling the server socket for incoming queries.

Is this standard practice, or should I be looking at a different way to monitor / setup connections? Are there any basic design principles or best practices for building distributed connections?

答:
Having a number of client connections to numerous remote nodes is not that intensive so that should not be a problem in that respect. For the data rate that you can expect from a terminal, you might consider non-blocking I/O with callbacks and a single server with a thread per client or a thread pool to process the response messages. This should scale until you are processing bound with your connections.

You could then set up your connections either in advance or as needed. Working on an as needed basis will avoid a startup hit if there are no tight time requirements for getting the list of files at about the same time. If you want more details, provide a diagram and we can discuss.


答:
So, for the client methods the operation looks like this:

```<code>main_object.computeState();
State new_state = main_object.getState();
</code>```

This is a bad pattern. You are exposing all the client code to an implementation detail of main_object.  This complicates the client code, complicates future optimizations of main_object, and will lead to bugs when some programmer calls getState() without calling computeState().

You should provide a single method of main_object that clients can call to get the current state.  That method can call computeState if necessary. Sometime in the future you may find that it is not necessary to call computeState for every call to getState.

The getState() method should take care of calling computeState whenever necessary.

Title: Computing and returning a sub-object where the sub-object is stored in the object

Body:
I have a complex object which routinely needs to compute a sub-object representing various aspects of the parent's state as a bundle. For example, imagine the object represents information about an aircraft and the sub-object is a summary of various key parameters of the aircraft at some particular time such as its heading, speed, etc. The object needs to store the last computed version of the sub-oject.

Currently the way I do this is that I have a void method in the object that does the computation and then sets a module-level variable to be equal to the newly computed sub-oject. The outside user of this sub-object then retrieves the current sub-oject via a getter. So, for the client methods the operation looks like this:

```<code>main_object.computeState();
State new_state = main_object.getState();
</code>```

To handle possible errors, however, in the computation, which is currently not done, I am thinking of changing to a compute method that returns the state:

```<code>State new_state = main_object.computeState( error_msg );
if( new_state == null ){
   print( error_msg );
   goto failure continuation
}
.... [everything ok, continue normally ]
</code>```

Is there a better strategy for constructing this pattern?

Body:
So, for the client methods the operation looks like this:

main_object.computeState();
State new_state = main_object.getState();

This is a bad pattern. You are exposing all the client code to an implementation detail of main_object.  This complicates the client code, complicates future optimizations of main_object, and will lead to bugs when some programmer calls getState() without calling computeState().

You should provide a single method of main_object that clients can call to get the current state.  That method can call computeState if necessary. Sometime in the future you may find that it is not necessary to call computeState for every call to getState.

The getState() method should take care of calling computeState whenever necessary.


答:
The OS (unless it's a very low level embedded system or something similarly exotic) already takes care of this: if your application has to wait for I/O, it will usually block on that I/O and some other thread or application will become active. The scheduler decides which one.

It's only if there is no other thread or application which could be running that you're actually accumulating wait time. In the article you quoted (thanks to @manlio for the link), that is the case: you have 12.1% waiting vs. 87.4% idle, which means one core is waiting for I/O to complete while the rest is not doing anything at all. Give that system something to do, preferrably multiple somethings, and the wait percentage should drop.

One of the high goals of todays application design is ensuring that even if there is only a single application running, and even if that single application is at some point waiting for I/O, the application can still continue on some other chunk of work. Threads are one approach to this, non-blocking I/O another, but it very much depends on the kind of work you're doing, whether you actually can get something done without the data you're waiting for.

when using Linux, if you're doing some longer I/O tasks, the OS becomes almost unusable until they are completed.

That's typically an indication of some I/O-bound situation. I dare say that the system isn't getting slow because it can't do enough CPU processing. More likely it's slow because a number of things depend on data from the HDD, which is busy at that time. This might be applications you want to run but which have to load their executable files, library files, icons, fonts and other resources. It might be applications you already have running, but which have swapped out part of their memory and now need that swapped in again to proceed. It might be some daemon which for one reason or other thinks that it not only has to write a line to a log file but actually flush that log file before answering some request.

You can use tools like iotop to see how I/O capacity is allocated to processes, and ionice to set I/O priorities for processes. For example on a desktop machine, you could classify all bulk data processing to the idle scheduling class, so that the moment some interactive application needs I/O bandwidth, the bulk processing gets suspended until the interactive application is done.

Title: Why do we have to wait for I/O?


问:
Difference between O(N^2) and Θ(N^2)
What is the difference between O(N^2) and Θ(N^2)? I know that O is the upper bound and Θ is tight bound. Could someone explain me this concept with an example.</p>

答:
Compare Selection Sort and QuickSort.

Selection sort has a n^2 behavious in both the best and worst case. It will always perform bad.

Quicksort on the other hand, might perform with n^2 complexity if the odds are against you, but it might (and in most cases will) perform with n*log(n) complexity.

Note how both algorithms are O(n^2) in the worst case, however only Selection Sort is Θ(n^2). This is essentially saying the above - we can bound Selection Sort running time from below by the same function, whereas Quicksort may perform asymptotically better in the best case vs worst case.

Title: Difference between O(N^2) and Θ(N^2)


问:
Loading Aggregate Root from Database with Validations

Here is a similar question
  Where to validate domain model rules that depend on database content?

I am asking this new question because I have more descriptions and I don't want to change the previous question mentioned above

Problem

I have Form aggregate root that has Fields collection. On my form I have the SetCustomField(fieldname, value) method. I also have default properties on the form e.g. DateOfBirth, FirstName, and LastName.

```<code>public DateTime DateOfBirth
{
   get { return _dob; }
   set {
      if(value > 2000)
         throw new ArgumentException(null, "You must be 15 yrs old or more");
      _dob = value;
   }
}
</code>```

This works when creating the form. But when you want to edit or view the form, the validation kicks in too. This throws exception for fields that are empty or have invalid values - perhaps changed in the db or loaded from Excel. The expected behavior is to allow the form to show on updating so the Admin can correct those fields.

CQRS

I have been reading about CQRS but so far I don't think it would solve this problem. If I want to edit the form, Form aggregate root still needs to be loaded, modified and updated:

```<code>//repository needs to set the DateOfBirth here and throws exception
var form = repo.GetFormById(1);
form.DateOfBirth = "Some value";
repo.Save(form);
</code>```

Since I need to reconstruct the model, CQRS Read-Model might not help. If I have to use CQRS, how would you reconstruct an Aggregate Root from the Read-Model?

Thanks for your contribution.

答:
CQRS solves one problem for sure - it separates domain models from read models. So with properly implemented CQRS you would not run into this kind of problems and your domain models would be focused about business logic, not about reading outcomes of it.

how would you reconstruct an Aggregate Root from the Read-Model?

You don't; you just use id's from your read side to get domain model with same id from your command side.


答:
Well, his advice is slightly too simple (that's an understatement).

Following it ranges all the way from a good idea over who cares and bad idea to impossible.

You should follow it whenever re-using is cheaper than destroying the old and creating a new one.

```<code>#include <iostream>
#include <string>

int main() {
    std::string s; // Don't needlessly free the buffer
    while ((std::cin >> s))
        std::cout << s;
}
</code>```

You should shun it as a matter of style when it doesn't matter for performance.

```<code>#include <stdio.h>
#include <stdlib.h>
int f(int, int);

int main() {
    for (int i = 0; i < 100; ++i) {
        int x = rand(); // Declared here so you don't need to hunt it down.
        printf("%d => %d\n", x, f(x-1, x+i));
    }
}
</code>```

You really should shun it when it has worse performance or the wrong semantics.

```<code>#include <iostream>
#include <string>
std::string generate(int);

int main() {
    for(int i = 0; i < 100; ++i) {
        std::string s = generate(i); // Using copy-ellision here
        std::cout << s;
    }
}
</code>```

You cannot follow it when the used type allows neither swapping, nor move-assignment nor copy-assignment.

```<code>#include <iostream>
#include <puzzle>

int main() {
    for (int i = 0; i < 100; ++i) {
        Puzzle x(i); // Puzzle is an immutable class. For whatever reasons.
        std::cout << x;
    }
}
</code>```

Body:
Well, his advice is slightly too simple (that's an understatement).

Following it ranges all the way from a good idea over who cares and bad idea to impossible.

You should follow it whenever re-using is cheaper than destroying the old and creating a new one.

#include <iostream>
#include <string>

int main() {
    std::string s; // Don't needlessly free the buffer
    while ((std::cin >> s))
        std::cout << s;
}

You should shun it as a matter of style when it doesn't matter for performance.

#include <stdio.h>
#include <stdlib.h>
int f(int, int);

int main() {
    for (int i = 0; i < 100; ++i) {
        int x = rand(); // Declared here so you don't need to hunt it down.
        printf("%d => %d\n", x, f(x-1, x+i));
    }
}

You really should shun it when it has worse performance or the wrong semantics.

#include <iostream>
#include <string>
std::string generate(int);

int main() {
    for(int i = 0; i < 100; ++i) {
        std::string s = generate(i); // Using copy-ellision here
        std::cout << s;
    }
}

You cannot follow it when the used type allows neither swapping, nor move-assignment nor copy-assignment.

#include <iostream>
#include <puzzle>

int main() {
    for (int i = 0; i < 100; ++i) {
        Puzzle x(i); // Puzzle is an immutable class. For whatever reasons.
        std::cout << x;
    }
}


问:
Etymology of (function) overloading
Where does the phrase "overload" come from?

It's interesting to see the translation of the term in different languages (e.g. list of Wikipedia articles about overloading), some languages translate it directly (in the meaning of "to put too much weight on something"), but some languages don't translate it at all.

答:
This doesn’t answer the question definitively, but the earliest use of it I can find is by John McCarthy in 1966.  As described by John Peck, recalling several years later one of the discussions about the Algol standard in Warsaw: “What I can remember of that meeting was the insistence of John McCarthy, that any new language should have what he called overloading of operators.  This would eventually became the operation declarations of ALGOL 68.”  So the term caught on because of John McCarthy.  Or at least it was so obscure in 1966 that McCarthy needed to explain it to the other leading language designers in the world and his usage stood out to the other participants as remarkable. Unfortunately, he passed away in 2011 and I can’t find anything online where he talked about why he called it that, if he coined the term himself, or if there’s any story behind it.

As a commenter informed me, Bjarne Stroustrup explicitly says that he took the idea from Algol when he designed C++ in the early ’80s. A Google Ngram search shows that the phrases “operator overloading” and “overloaded operators” were virtually unheard-of before the ’80s.  It doesn’t seem to be how mathematicians back then talked about the way the + sign could denote any group operation.

Jules in the comments gives a plausible source for McCarthy’s use of the term: linguists had been referring to the double meanings of words as “semantic overloading” for decades before 1966.  McCarthy’s papers show he was familiar with the field and its terminology.  (He also once wrote, “The squabbles among linguists remind me of a saying of my mother-in-law, a retired farmer’s wife. ‘When the chickens start cannibalizing one another, the only thing to do is to butcher the lot or sell them to someone else and start over.’”)

Title: Etymology of (function) overloading


问:
In CI, should tests be run against src or dist?
I've had a dispute with a colleague about when to run JavaScript unit tests in a CI environment at one of two different times. Let's call the two parties PE (pro-early) and PL (pro-late).

Early (against src)

Running the tests against the source code right out of the version control system.

PE says that we should run the riskiest code first and "fail fast." Both parties agree that we should run unit tests this way during development because the cycle time is much faster. PE says that since we need to have the build configured to run early in any case, an alternate configuration that runs the tests late constitues duplication and bloat.

Late (against dist)

Running the same tests against code has been packaged up (concatenated and minified).

PL says that we should test the code as it ships. PL claims to have experienced time-consuming scenarios where the code worked when run directly from source, but failed because of something that went wrong when the code was packaged for distribution.

PE says a hypothetical "something might go wrong" is a weak argument. And anyway it's not CI's job to catch that kind of problem. The distributable code is tested by QA before it's shipped.

Further details

"Early and late in CI" is not an option, much to PEL's dismay.

The code is modularized using AMD and RequireJS. We're using Karma for unit tests and Grunt for the build script.

So which is it -- early or late?

Is one side definitely right? Are we missing any considerations that may sway one person to the other side?

答:
From a generic testing point of view:

"Testing early" is a workflow optimization. It helps you iterate faster by failing quickly. Tests that are close to source code, like unit tests, are useful here.

"Testing late" is a requirement for quality assurance. You must test code exactly as it ships, because as you said, there are multiple places where things can go wrong even after the source code is validated. High-level tests that integrate multiple components are useful here.

You should be doing both low-level and high-level tests. I'm not sure why "early and late" is not an option, but that is exactly what I'd recommend.


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
The thing about re-inventing the wheel is that sometimes there's no standard, off-the-shelf wheel that will do what you need. There's a lot of good wheels out there, in a lot of sizes, colors, materials, and modes of construction. But some days you just have to have a really light-weight wheel that's green anodized aluminum, and no one makes one. In that case, you HAVE to make your own.

Now that's not to say that you should make your own wheels for every project - most things can use standard parts and be better for it. But every now and then, you find that the standard parts just don't work, so you make your own.

The most important thing is knowing WHEN to make your own. You have to have a good idea of what the standard parts can do, and what they can't, before you start designing your own.


问:
How do I prevent attackers from duplicating submissions?
I want to create a polling website. A client requests to answer the poll using POST, and the server responds with the candidates. The client then sends a POST with the candidate information and the winner to the server, which then stores in the information. I want to prevent a client from manipulating results by repeatedly sending their vote to the server. One way I thought was:

Client requests to vote in the poll.

Server sends a list of candidates, timestamp, and a salted hash created using the candidates and timestamp. The server then stores the hash.

Client picks a candidate, and sends the winner back with the list of candidates, timestamp, and salted hash.

Server computes the hash with the same salt, and checks to see if the hash is a valid hash as stored in the database. If the hash is valid, it honors the vote. If not, then it either silently fails to avoid alerting the attacker or responds with an error.

I want to find a more elegant way to do this though. First, I'm having trouble thinking of a salt which is not static. I don't want the user to be restricted by IP address, so that can't be included in the salt. After that I can't think of a good way of salting my hash.

Second, I want to find a way to not have to store information on the server. If I could create a validation method that can be computed quickly instead of stored that would be better (unless storage is definitively better than computing because it might be faster?).

Third, should I silently fail or explicitly inform the client of an error?

答:
Is it feasible to use the table row number where the record is being stored as the salt? (or a function of this unique number).

I would store the information on the server, just because as a matter of principle I would NEVER trust the client in Internetland.  If you really want to store information on the client you will be digitally signing it or encrypting it using your private key and verifying it or decrypting it at vote time.  Whether this is acceptable depends on the nature of the poll: for election to public office, I would choose the server, where to go for team lunch, I would choose the server for that too.

Give feedback (and log it), otherwise you run the risk of nobody even knowing if legitimate votes being pinched and used before the real voter has time to vote.


问:
How to handle singular and plural parameters for functions
Often when I'm writing a set of utility functions, I find myself wanting a function that applies some logic to multiple items, as well as a function that does the same with just a single item. There are a lot of potential solutions to this, but I always find myself flipping back and forth.

I could write an exclusively singular version of the function (modify_item(item)) and use map, comprehension, or a foreach externally. I don't want to do this every danged time I call it with multiple items though.

I could write an exclusively explicitly plural version of the function (modify_items(items)) that does the iteration inside. But I don't want to call it with a list every time either. Better than always singular, but still awkward to call. This would also support bulk operations better.

I could write an agnostic function that checks the input's type (modify_item(item)). If it's not iterable, it'll wrap it in a list and then iterate. This seems to be the best option, but the lure of star operators always gets me...

I could write an agnostic function that takes a variable number of inputs (modify_item(*items)) and iterates over them. This gives me a good calling syntax and automatically packs the items into an iterable for me. The problem I always run into here is that adding subsequent arguments or keyword arguments is awkward.

Finally, I could just throw up my hands and write a plural function as above, and a singular one that would wrap the parameter in a list and pass it to the plural one. Then I'd have to write double the functions, which is silly.

It seems like javascript libraries usually do the type checking option (#3), and that's the one I like best. In that case, you have the question of naming conventions. I think I favor singular, but I'm not sure about that.

Examples are in python, but this question could be applied to most languages.

答:
In these instances, I usually make two versions of the function, with the multiple version simply calling the singular version, something like this:

```<code>class Foo:
  def transform_entity(bar):
    return do_things(bar)

  def transform_entities(bars):
    return [transform_entity(b) for b in bars]
</code>```

It's pretty self-explanatory, avoids any explicit wrapping, and allows you to use arguments properly without manual wrapping (unlike trying to do something terrible with varargs).

OwnerDisplayName: JStaab

Body:
In these instances, I usually make two versions of the function, with the multiple version simply calling the singular version, something like this:

class Foo:
  def transform_entity(bar):
    return do_things(bar)

  def transform_entities(bars):
    return [transform_entity(b) for b in bars]

It's pretty self-explanatory, avoids any explicit wrapping, and allows you to use arguments properly without manual wrapping (unlike trying to do something terrible with varargs).


问:
Why aren't Java Collections put in a dedicated package
Why do they just reside in java.util and not somewhere more specialized like java.collections or java.util.collections?

It could contribute to mess up with different unrelated code. Couldn't it?
Was it a decision motivated from communicate with the outside of JCF at package level or rather a historic legacy?

答:
While one could, hypothetically, have made java.util.collections for all of the new collections that were part of the collections framework, the thing is that there were some collections classes that existed prior to them.

In particular, java.util.Dictionary (javadoc) would have been in a separate package than java.util.Map (javadoc).  Similarly, you have Hashtable and HashMap.  java.util.Vector (javadoc) implements java.util.List (javadoc) now.

Obviously, moving Vector and Hashtable to a new package is out of the question, and making a copy of the code or subclassing either in a new package causes even more headaches (I don't even want to think about the mess that would cause).

When you look at the java.util package, you will see that it is mostly the collections with a few other utility classes hanging out in there.

So it just doesn't make much sense to try to place the new classes in a different package.

Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).

java.util continues the collection framework.  That is first and foremost. The only collections that are in a different package are the ones used by java.util.concurrent which is focused on concurrency. These are still considered to be part of the collections framework.  From java.util.concurrent.ConcurrentNavigableMap<K,V>:

public interface ConcurrentNavigableMap<K,V>

extends ConcurrentMap<K,V>, NavigableMap<K,V>

A ConcurrentMap supporting NavigableMap operations, and recursively so for its navigable sub-maps.

This interface is a member of the Java Collections Framework.

Since:

1.6


答:
It sounds like you really have two problems here:

Preventing replay attacks.

Preventing the same client from voting twice.

These are subtly different. A replay attack is simply sending a request multiple times, perhaps with slight variations, and possibly by a third party. Voting multiple times is just that: legitimately voting more than once.

The core problem here is you do not know who the clients are. What if a client moves locations (IP or subnet)? Is it a new client? Even if you think you know who they are, at an abstract level, you do not.

This is not a new problem. By and large, most of the Internet solves this problem by demanding that clients create accounts. Authentication occurs over TLS, ensuring that a client is who they say they are. Once this is done the client can send its vote over the TLS connection where the server stores it in the database. One client ID (e.g. email address or account name), one vote.

This prevents replay attacks: TLS is already hardened against these attacks by design. This also prevents voting multiple times: votes are linked against the account ID in the database, making it trivially easy to see if a particular client has voted already. Simply have a multi-part primary key consisting of the poll ID and account ID. Another field stores the vote. You can add optional metadata such as the IP address and date/time of the vote.

There is no reason to reinvent the wheel here: TLS and some basic database design can easily solve your problem and far better than any home-grown solution can.

Title: How do I prevent attackers from duplicating submissions?

Body:
I want to create a polling website. A client requests to answer the poll using POST, and the server responds with the candidates. The client then sends a POST with the candidate information and the winner to the server, which then stores in the information. I want to prevent a client from manipulating results by repeatedly sending their vote to the server. One way I thought was:

Client requests to vote in the poll.

Server sends a list of candidates, timestamp, and a salted hash created using the candidates and timestamp. The server then stores the hash.

Client picks a candidate, and sends the winner back with the list of candidates, timestamp, and salted hash.

Server computes the hash with the same salt, and checks to see if the hash is a valid hash as stored in the database. If the hash is valid, it honors the vote. If not, then it either silently fails to avoid alerting the attacker or responds with an error.

I want to find a more elegant way to do this though. First, I'm having trouble thinking of a salt which is not static. I don't want the user to be restricted by IP address, so that can't be included in the salt. After that I can't think of a good way of salting my hash.

Second, I want to find a way to not have to store information on the server. If I could create a validation method that can be computed quickly instead of stored that would be better (unless storage is definitively better than computing because it might be faster?).

Third, should I silently fail or explicitly inform the client of an error?


问:
Economics of scaling, denormalizing NoSQL for personalized content
I am using Cassandra for a data intensive app. With relatively little operations and deployment experience, the expertise I am looking for is someone that can read the example below and decide whether I am overlooking simpler solutions, or if the resources needed make this problem expensive or intractable.

~A million entries in a book table: each entry ~30 columns - name, array of themes, year, etc

~1-10 thousand book stores that each contain some subset of the main table in (1), perhaps containing the id field from (1). so a book store table for the store metadata, and a book store inventory table will be needed.

A million users - a million entries in a user table.

A sequential recommender algorithm is designed to rank the best choice out of all possibilities for a user in a certain store. first, it can easily score each book in the main book table with a 1 or 0 based on user tastes. thus it can "filter out" what it knows the user wont like, and the 1's move on to the scoring round. second, it can take real time user data and rank the remaining books for the store the user visits.

the question is how to apply the first binary recommendation step to the data.

a) each of the 10,000 "book stores" has its own inventory subset of the main book list. at worst case if all stores have all books(just pretend), thats 10,000 stores X a million books. then a batch operation (spark perhaps) can pull a single store's inventory to score for a user, and in the application logic, each book is checked against a hash-table for whether it passed the first binary recommender filter, which is queried from the user table.

b) create a user-store-book table (since user only has one or two favorite stores) that includes boolean results of first round of recommender for each book. this means a million users X a million books X 2 stores as entries in this table. then the batch job just queries directly for the recommended books in order to rank.

To put my question more succinctly, I am worried that in solution a, the CPU resources required and extra IO would make for a low-performant solution, and that the sheer amount of data in solution b might make this solution intractable.

答:
Can't you regroup the books by genre, or taste groups, to reduce the problem to lower scale ? It seems to me the major issue is that you are trying to use a large set of data that isn't refined enough to provide a real-time insight. You should probably try to cluster the books in this situation. If you can't, then you are down to full iteration, and limited to the two solution you listed.

Edit : i forgot, but clustering the users may make sense too


问:
How to keep a team well-trained?
I'm currently mentoring a small team of 4 junior dev in small software company. They are very smart and often achieve their tasks with a high-quality job but I'm sure they still can do better - actually I have exactly the same feeling for myself :) -. Besides some of them are more "junior" than other.

So I would like to find of a funny way to improve their CS skills (design, coding, testing, algorithmic...) in addition to the experience they acquire in their daily work. For instance, I was thinking of setting up weekly sessions, not longer than 2 hours, where we could get together to work on challenging CS exercises. A bit like a coding dojo.

I'm sure the team would enjoy that but is it really a good idea? Would it be efficient in a professional context? They already spend all their week to code so how should I organize that in order for them to get some benefits?

Any feedback welcome !

答:
Give them 3 hours a week to research/hack on whatever they are interested in for programming. Ideally this would be more, but I think 3 hours is a good start. It could be all in one chunk, it could be broken down into little 30 minute segments along the way. It sounds like these programmers are motivated enough that they would be able to keep things in check.

But allowing them to explorer their own fields of interest will come back to help the team as well. One person that really likes data may look into and write a small app using a NoSQL solution that could help a project that comes up a few months down the line. Another person might right a small utility app for a trivial need (such as parsing log files) that becomes a staple app in your team. Even the knowledge gained from reading up on what the big companies are doing can help evaluate options for the next project that comes up.

We're in an environment that is ever changing, and each member of your team I'm sure brings something unique to the table, so give them the opportunity to expand on their own terms. They'll be appreciative that they haven't been forced into something (even though all intentions are good) and you'll get a good diversity of feedback.

Title: How to keep a team well-trained?


问:
Why are Strings in StringPool considered insecure?
Passwords are recommended to be stored in char[] instead of String, as Strings are stored in StringPool.
Read more here

As per this question Strings in StringPool are not available directly.
To obtain Strings in Stringpool, we would need a password-dictionary to check them in StringPool. If we have a password-dictionary, we don't need to worry about StringPool, we can anyhow try directly on password fields.

To prevent Brute-force attack  we are limiting number of re-tries for passwords and checking for any suspicious activities.

If all that is in place still should we not use "String" as a datatype for passwords?

The answer obtained from similar questions is: We can have access to memory dump and get access to Strings in stringpool.

Follow up questions:

How can one access the memory dump?

Can the access be prevented?

If access to memory dump is prevented, Is it safe to use String as a type for passwords?

答:
The String, once created, exists in memory until a garbage collection is run. If anything has a reference to it, it isn't collected.  Compare this to the code:

```<code>char[] password = somedata;
// test password;
Arrays.fill(password, 0);
</code>```

While the character array may exist for some time, the values within the character array are gone once that Arrays.fill runs.  In this way the password stored within a char[] has a known duration that can be reasoned about, unlike the duration of a String on the heap.

Creating a memory dump is as easy as running a program where you can connect to the various virtual machines.  VisualVM can do it quite nicely.

And...

Go to classes, double click on String...

And then you have every instance of a String that is running in the JVM at the time of the memory dump.

While this implies some access to the machine, the key takeaway is that it is really quite easy to get a heap dump and examine it.  There's even an SQL like language for it called OQL for doing queries against it.

The reason to use a char[] is to limit your exposure to a memory dump. If you note the line right under the String in the memory dump was char[] and they are in there too.

Security minded individuals are especially concerned of this on Android where one could steal a device and do a memory dump of running processes thus collecting passwords to all of the apps that stored their passwords in Strings that haven't been garbage collected yet.

Body:
The String, once created, exists in memory until a garbage collection is run. If anything has a reference to it, it isn't collected.  Compare this to the code:

char[] password = somedata;
// test password;
Arrays.fill(password, 0);

While the character array may exist for some time, the values within the character array are gone once that Arrays.fill runs.  In this way the password stored within a char[] has a known duration that can be reasoned about, unlike the duration of a String on the heap.

Creating a memory dump is as easy as running a program where you can connect to the various virtual machines.  VisualVM can do it quite nicely.

And...

Go to classes, double click on String...

And then you have every instance of a String that is running in the JVM at the time of the memory dump.

While this implies some access to the machine, the key takeaway is that it is really quite easy to get a heap dump and examine it.  There's even an SQL like language for it called OQL for doing queries against it.

The reason to use a char[] is to limit your exposure to a memory dump. If you note the line right under the String in the memory dump was char[] and they are in there too.

Security minded individuals are especially concerned of this on Android where one could steal a device and do a memory dump of running processes thus collecting passwords to all of the apps that stored their passwords in Strings that haven't been garbage collected yet.


答:
As a general case, every change to the code should be tested. Exactly how you do those tests and what tests are done is specific to the situation and environment you find yourself in.

Testing both early and late would be the recommended alternative. You say this will eventually be the case, but until then you need to pick one over the other.

It really just sounds like you are looking for the best compromise until the situation matures and allows for both. Pick the one that tests the highest risk change and then allows for the fastest corrections to the code - by the sounds of it, this is the test early for now. If the QA is done after all of this, it gives you one last opportunity to catch problems.

As already mentioned, the testing early with unit tests identifies logical errors and helps correct those before heading into integration. Once into integration, the testing late identifies integration and compatibility issues. It also offers final system testing and user acceptance testing.

Given that you are using CI, it is most likely a highly automated environment anyway, use that, automate as many of the tests as possible. This gives you a higher level of confidence you are not introducing regression issues. I'm glad you have identified the source of why you can't do both, the ticketing system should support the speedy delivery of quality code, not inhibit it.

Title: In CI, should tests be run against src or dist?

Body:
I've had a dispute with a colleague about when to run JavaScript unit tests in a CI environment at one of two different times. Let's call the two parties PE (pro-early) and PL (pro-late).

Early (against src)

Running the tests against the source code right out of the version control system.

PE says that we should run the riskiest code first and "fail fast." Both parties agree that we should run unit tests this way during development because the cycle time is much faster. PE says that since we need to have the build configured to run early in any case, an alternate configuration that runs the tests late constitues duplication and bloat.

Late (against dist)

Running the same tests against code has been packaged up (concatenated and minified).

PL says that we should test the code as it ships. PL claims to have experienced time-consuming scenarios where the code worked when run directly from source, but failed because of something that went wrong when the code was packaged for distribution.

PE says a hypothetical "something might go wrong" is a weak argument. And anyway it's not CI's job to catch that kind of problem. The distributable code is tested by QA before it's shipped.

Further details

"Early and late in CI" is not an option, much to PEL's dismay.

The code is modularized using AMD and RequireJS. We're using Karma for unit tests and Grunt for the build script.

So which is it -- early or late?

Is one side definitely right? Are we missing any considerations that may sway one person to the other side?


答:
Typically you'd run unit tests early - they're developer tests that the bits you've developed work as expected in isolation. Then you'd run wider integration tests late, as these test that the bits you've developed work as expected with the other bits.

There's no need to run unit tests both early and late - its redundant to run them late if you already run them early, but you can never run integration tests early (obviously). CI is the place to run these.


问:
Should DTO have validators?
I believe that DTO should be as dummy and easy as possible. However, after hint made by my friend, opportunity to validate data that is set in DTO sounds tempting.

Let's have following example:

```<code>//this class only holds bunch of objects from the future

class FooFuture{

    /** @var ArrayObject */
    $collection;

    (other fields ommited for readability)

    /**
     * @param ArrayObject $collection
     */
    public function __construct(ArrayObject $collection = null){

         if(null === $collection){
             $this->collection = new ArrayObject();
         } else {
             $this->collection = $collection;
         }
    }

    /**
     * @param ArrayObject $col
     */
    public function setCollection(ArrayObject $col){

        $now = new DateTime();

        foreach($col as $element){
            if($element->getDateTime() < $now){
                throw new InvalidArgumentException('Collection should only contain objects from the future');
            }
        }
    }

    /**
     * @return ArrayObject
     */
    public function getCollection(){
         return $this->collection;
    }

}
</code>```

What do you think?

答:
While i agree that it can be usefull to have validation for dto-s i think that dto-s should be as simple as possible.

You can achive boths if you are using a programming language that supports Interfaces like java or c# and put the validation logic into a seperate class that consumes interfaces.

Example

```<code>public interface IOrder { ... }

public class OrderDTO implements IOrder { ... }

public class OrderBuisinessObject implements IOrder { ... }

public class OrderValidator {
   void validate(IOrder anOrder) { ... }
}
</code>```

To answer your question: yes to have validation but not in dto

Title: Should DTO have validators?

Body:
While i agree that it can be usefull to have validation for dto-s i think that dto-s should be as simple as possible.

You can achive boths if you are using a programming language that supports Interfaces like java or c# and put the validation logic into a seperate class that consumes interfaces.

Example

public interface IOrder { ... }

public class OrderDTO implements IOrder { ... }

public class OrderBuisinessObject implements IOrder { ... }

public class OrderValidator {
   void validate(IOrder anOrder) { ... }
}

To answer your question: yes to have validation but not in dto


问:
Understanding Flux pattern
I'm actually studying the flux pattern and there's something that I can't understand concerning the stores.

What are they exactly?

I have read many articles, and it seems that it concerns the domain.

Does it mean that this is the "abstract" part related to api calls or backend calls?

It's not very clear for me.

Edit: Could it be the same thing as the angular factory? Fetching remote data, making a business task or store some app states (current user connected for example)?

答:
Ok let me explain you from Step by Step

1 What is Flux?

A pattern

Centralized dispatcher

Unidirectional data flows

List item

They call it Flux for a reason too.

Flux Implementations

Facebook’s Flux

Alt

Reflux

Flummox

NuclearJS

Fluxible

A Chat with Flux

React : Hey Action, someone clicked this “Save Course” button.

Action: Thanks React! I registered an action creator with the dispatcher, so the dispatcher should take care of notifying all the stores that care.

Dispatcher :Let me see who cares about a course being saved. Ah! Looks like the  Store has registered a callback with me, so I’ll let her know.

Store : Hi dispatcher! Thanks for the update! I’ll update my data with the payload you sent. Then I’ll emit an event for the React components that care.

React : Ooo! Shiny new data from the store! I’ll update the UI to reflect this!

Flux API

register(function callback) –“Hey dispatcher, run me when actions happen. -Store”

unregister(string id) –“Hey dispatcher, stop worrying about this action. -Store”

waitFor(array ids) –“Update this store first. –Store”

dispatch(object payload) -“Hey dispatcher, tell the stores about this action. -Action”

isDispatching() –“I’m busy dispatching callbacks right now.”

so the the question raise in our mind is

So Flux Is a Publish-Subscribe Model?

Not quite.

Differs in two ways:

1.Every payload is dispatched to all registered callbacks.

2.Callbacks can wait for other callbacks

Summary

Flux is a pattern for unidirectional data flows
Actions encapsulate events
Dispatcher is a central hub that holds callbacks
Stores hold app state
Many implementations

Title: Understanding Flux pattern


问:
writing a controller file in Python
I need some advice on my idea to write a controller file in Python, and not like the C in MVC type controller but a more simpler idea. Just a Python script that controls the operation of some other Python scripts.

I will outline the idea, and any advice or ideas would be greatly appreciated.

I have to write a system that does some background tasks for a web application. The web app is in PHP and separate from the Python system I am writing, the Python will do some automated tasks and calculate and save some analytical data for the web app to use and display.

I have experience with basic Python but I have not pushed forward to learn much about class/objective Python. So far what I have written for the system is a bunch of separate py scripts that do the jobs they have to do, written totally procedurally. They all work fine, but it's not really a system yet. My initial krux was that I had to keep them all alive and running infinitely in the background. After some research I decided that the best way to do this was to have a process manager like Supervisord look after each script, I would start up the scripts and allow them to run for a certain time with a finite loop (in each script) and then they would exit, then the supervisor would restart them every time they exit and keep them alive. I wanted to avoid using infinite loops because of the possibility of memory leaks (I believe allowing the process to exit totally frees up memory associated with that process and prevents leaks). I have not tested any of this, it's just a concept at the moment.

Something I would prefer to do would be to have one script be the controller of the rest of the scripts and have the supervisor only look after the controller. This saves me having to update the supervisors config file every time I add to the Python system.

The basic idea for the controller would be to have a loop fork new threads for each separate script/process and then have the controller wait for all the other threads to complete before allowing the loop to do another iteration (starting everything again).

I'm guessing what I need to do for this would be to wrap all the code in each script in a function, then import them as modules into the controller and call each function on a new thread inside the 'main' loop of the controller. Then the loop just runs, calls each function on a new thread and waits for each thread to finish before starting again.

How does this sound as a concept?

The only direct coding question I have is about turning my scripts into modules, how do I go from totally procedural code (no functions, no classes) into an importable module? can I wrap the procedures in just a function, or do I need to have them in a class also?

答:
I think you are reinventing the shell. Just make up a bash script that would control your modules

I would start up the scripts and allow them to run for a certain time with a finite loop (in each script) and then they would exit, then the supervisor would restart them every time they exit and keep them alive

This is better done with shell script rather than threading/forking manually

UPD: take a look at this Q/A at stackoverflow:

until myserver; do
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
done

Title: writing a controller file in Python


问:
Java Web Frameworks (JSF vs Wicket) Third-party component suites in Wicket?
A presentation linked in an answer here demonstrated a comparison of several web development frameworks.  It was a good comparison but caused me a little worry based on the technology stack that I have been pushing for awhile now at my current company.

While it seemed like the author was biased towards RoR, he pointed out some major pain points about JSF, which I am using right now and personally have no significant problems with.  It seems hip to hate JSF, and I would like to look into something different like Wicket.  The problem is that rich third-party component libraries like Primefaces have me hooked by the extreme convenience of throwing prebuilt web components onto a page with simple XHTML compliant markup.

Frameworks like Wicket are great because they merge the page with the View, and with Spring this is a powerful combination, but I can't help but wonder how long would it take me to implement the fully featured Primefaces Data Table component in a framework like Wicket?

Clearly JSF is a component based framework like Tapestry, but does Wicket have an answer to rapid component-based web development like JSF+Primefaces?

Further, I am aware of the major drawbacks of JSF, one of which being the level of effort and frustration it takes to develop a component, but with component suites in JSF becoming more stable and fully featured, is this a major issue for relatively simple web applications with loose open ended UI specifications?  If it doesn't have to look exactly like the spec visually, why would custom components need to be developed?

I know there is a lot of JSF hate out there... just mentioning it a developer conference causes people to break out into seizures from so much fail.  The web is littered with JSF Sucks blogs, but I have done some pretty cool things with it.  Any thoughts on this?

答:
JSF is usable for me only with good IDE, such as Eclipse. Making forms / pages by clicking is very nice, like old Delphi / Borland C++. And almost to the same extent bad in long term maintenance, refactoring, making and changing "proof of concept" etc. JSF refactoring is bad, as in real-life clicked Delphi project.
There is good access to a wide range of ready JSF components is positive of-course (few overflow with too many options to choose may apply)

Wicket is very good if You want to develop own reusable components, 2-3 evening with Wicket and You can. With JSF, after one month you can't made really usable components.

In Wicket, I can return to old project leaving on margin and continue to work with type-safe java code

Tests show that Wicket has better speed, lower RAM usage etc. It isn't important in my case, which is high, long term maintenance scale in my projects, but small user count.

You asked about Primefaces Table with suggestion that Wicket doesn't separate View from Model; this is is not true.


答:
This notation has nothing to do with the difference between best/average/worst case complexity. You can apply both notations to each of them.

An algorithm which has linear runtime is in both O(n) and O(n^2), since O only denotes an upper bound. Any algorithm that's asymptotically faster than n^2 is also in O(n^2).  Mathematically O(n^2) is a set of functions which grows at most as fast as c * n^2. For example this set contains c, c * x, c * x^1.5, c x^2, c1 * x^2 + c2 * x for any c.

Θ on the other hand is both a lower and an upper bound. So a linear runtime algorithm is in Θ(n) but not in Θ(n^2). Mathematically Θ(n^2) is a set of functions which don't grow faster that c*n^2 for some c but also doesn't grow slower than c*n^2 for another smaller c. For example this set contains c * x^2, c1 * x^2 + c2 * x, arctan(x) * x^2 for any positive c and other functions where the fastest growing term grows like c * x^2 but not c, c x, c x^1.5 because all the terms grow slower than c * x^2.

See Big O notation on wikipedia

Title: Difference between O(N^2) and Θ(N^2)

Body: What is the difference between O(N^2) and Θ(N^2)? I know that O is the upper bound and Θ is tight bound. Could someone explain me this concept with an example.</p>


问:
End to end testing of write-only apis
In our deployment process for our services, besides unit and integration tests, we also have a little smoke test for our services. Mostly for verifying that the deployment went well, cloud services set up correctly with working connection strings and working domains.

For most services this is quite easy. Make a request to a endpoint you know would hit the db and check the response.

We now have a write only service where fat clients write some data for verification and logging because they are billed for their activities later.

Is there a good way for us to write smoke tests for this kind of service. I'm seeing a analogy to credit cards where I know there exists special test cards which doesn't charge any data. So In our service we could hard code some test guids that won't commit a transaction or something like that.

Is there a better approach?

答:
If the goal of your smoke test is to check that a fat-client can call some function in your write-only-service to make shure that network connectivity is ok and the service is running why not add an extra non-read-only service method called "self-test" that replies something defined to the fat-client and that would not be charged.

it could be something similar to the network "ping"-command

Title: End to end testing of write-only apis


问:
Purpose of `return self` from a class method?
I came across something like this in an open-source project. Methods that modify instance attributes return a reference to the instance. What is the purpose of this construct?</p>

```<code>class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return self
</code>```

答:
In Smalltalk, every method that doesn't explicitly return something, has an implicit "return self".

That's because (a) having every method return something makes the computing model more uniform and (b) it's very useful having methods return self. Josh K gives a nice example.


问:
Should I also mock header files?
So, I am part of a very large project which has, as yet, no unit testing (shudder!) and I want to introduce it.

I plan on using Google Test and Google mocks.

The code is large and unwieldy and suffers from "header spaghetti".

If I wish, for simplicities sake, to test only a.cpp which calls only a single function in b.cpp, then I can use Google Mock to generate a mock for b.cpp.

However, if I #include b.h in a.cpp and in my test suite, I find that b.h #includes a number of other headers, which in turn ... in the end, I am #including hundreds of headers.

There will be no restructuring of header files (any time soon, if ever). I just have to live with that.

Until now, the code has only been built as a complete system, for an ARM processor, and now I want to build a.cpp plus b.cpp plus Google test to run on Linux.

I am having major problems as there are several hundred (!) compiler switches in the system build and I can't easily see which are needed where, which are ARM only, what would replace them for Linux, etc.

Plus, some of them contain #defines which expand to function calls (especially from trace log, but also for others), and I don't know where to find those in order to mock them.

Finally the question: how is this normally handled? Should I make a mock of b.h, which contains only what is needed by a.cpp?

If so, do I have to do it manually, or can Google Mock help in any way?

And, nope, the code won't be restructured; at least not immediately, for fears of destabilizing it.

I really do not like the idea of pulling in the majority of headers in the system, but nor can I find an easy way to mock them :-(

答:
Since you are working on a legacy system (no unit tests), you are going to find it quite hard without modifying the code and refactoring.

The best use of mocks is with some kind of dependency injection. Injecting a mock object, instead of the real class. And not with injecting dependency by linking different object file (what you are trying to do).

The best way to start is to find what you can unit test, without using mocks. Then when you have time for refactoring, adjust the classes to somehow inject dependency and then use mocks.

Title: Should I also mock header files?


问:
Isormophic javascript, request processing
I was wondering why isomorphic JS, like using reactjs in both client and server side increase first page load ?

What is different from simple SPA applications ?

In both cases we are loading the full content of the applications (in build.js or bundle.js for example). So what is different in both cases ?

答:
When using JS isomorphically, the same code can be used to pre-render the page that is sent to the client as would be used to render in the case of a 'simple SPA'. This means that minimal post-processing needs to happen client-side (at least for display purposes), resulting in a faster-appearing page load.

Conversely, in the case of a 'simple SPA' the client-side rendering infrastructure may need to make subsequent requests to the back end in order to retrieve data that is then used for rendering, resulting in a slower-looking page load, as extra details will 'pop-in' after the inital load.

The "Trouble in paradise > Performance" from this article gives a good description of why a client-side only SPA can appear slower, and it's implications.