问:
Create arithmetic expression from number using +-/* that equals target
For example, you are given the source 1234 and the target 24. The task is to use the standard arithmetic operators +-/* placed within source, without changing the order of the digits of source to create target. In this example the solutions are:

```<code>1 * 2 * 3 * 4 = 24 = target
12 + 3 * 4 = 24 = target
</code>```

Another example:

```<code>target=346
source=8675309
# solution
867 - 530 + 9 = 346
</code>```

My question is what data structures and algorithms should I be thinking about for this problem? I've written a solution to this using Python, but it is terribly naive and brute forces the problem. It creates all possible splits in source, and then creates all possible expressions by interleaving every combination of +-\* within the split of source.

It takes a LONG time to find this solution:

```<code>source=314159265358
target=27182
# solution
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8
</code>```

I believe the complexity is O(2^n), where n is the number of digits in source. After each digit you can split or not.

Code below (note it errors if source has a 0):

```<code>#!/usr/bin/env python

from __future__ import print_function
from itertools import combinations
from itertools import product
from sys import argv

def split_number(s):
    """ takes input string number and splits it into strings of separate digits """
    return [_ for _ in s]

def partition_list(aList, indices):
    """ split a list into parts, splitting at the indices """
    indices = list(indices)
    return [aList[a:b] for a, b in zip([0] + indices, indices+[None])]

def create_index_splits(list_len, n):
    """ returns a list of all places to create splits to create n splits in a
    list of len list_len """
    return list(combinations(range(1, list_len), n))

def generate_expression(l, operators):
    """ takes a list of list l and a sequence of operators and creates an
    expression of the intreleaved list and operators """
    expression = [item for pair in zip(l, operators) for item in pair]

    # interleave operands and operators
    return ' '.join(expression + [l[-1]])

def generate_expressions(l):
    """generate all possible combinations of digits splits and operators """
    l = convert_list_ints_to_list_str(l)
    operators = '+/*-'

    # cartesian product of operators
    operator_combinations = product(operators, repeat=len(l) - 1)
    return [generate_expression(l, _) for _ in operator_combinations]

def convert_list_ints_to_list_str(l):
    """converst list of lists of digits to list of numbers """
    return [''.join(map(str, _)) for _ in l]

def find_solutions(a, b):
    l = split_number(a)
    index_splits = [create_index_splits(len(l), _) for _ in range(1, len(l))]
    index_splits = [i for j in index_splits for i in j]
    m = [partition_list(l, _) for _ in index_splits]
    b = int(b)
    expressions = list([generate_expressions(_) for _ in m])
    expressions = [i for j in expressions for i in j]

    return [_ for _ in expressions if eval(_) == b]

def main():
    try:
        a = argv[1]
        b = argv[2]
    except (ValueError, IndexError):
        print("invalid args")

    [print(_) for _ in find_solutions(a, b)]

if __name__ == '__main__':
    main()
</code>```

To run it do python thisfile.py [source] [target]

答: I doubt that there is a solution that is not exponential in the number of digits. It seems similar to The subset sum problem, but with an even larger search space. In other words, you can't do much better than an exhaustive search.</p>


问:
.net Windows app in a web page
I am developing a feature related to Microsoft Outlook which has support only for Windows library.

However, I have to put this into a web page for the users. In the process of consuming the windows application into a web page, I have written a Windows application using C# and integrated it with a WPF solution and trying to package this as an ActiveX.

This would require the users to download the ActiveX on their local machines which I would like to avoid. Is there a better way to achieve this (Windows app to web)?

答:
You are a little far from you objectives.

I assume you are referring to Exchange Server and not MS Outlook.

For Outlook you can develop add-in for your desktop (through a local .dll) but, on the server side is another story. It is very unlikely (and not recommended) to run MS Office on a server.

You can use the same set of API in use by 'OWA' (Outlook Web Access) they are very well documented, however, not for newbies.

Active-X and most of the user-side executables are today, to say the less, obsolete, 'deprecated'. Also, with multitude of different access devices using your application, will be almost impossible to make them compatible. HTML is today the most common minimum denominator.

ContentLicense: CC BY-SA 3.0

Title: .net Windows app in a web page


问:
Entity Component System Coupling
Lately I've been working on a small personal project which is basically an Entity Component System framework with autoupdated Systems.

While I have a pretty good idea on the way the framework should work, because of lack of experience I am having trouble with actually keeping everything decoupled.

Some details on the framework:

Each entity is defined by it's components.

Systems are responsible for the actually modifying the entities by changing their components.

In order to improve locality of reference, instead of keeping each component in the appropriate entity,
all components are stored in homogenous vectors and each entity keeps a list of indices to each vector.

Since each System modifies specific components, it should keep a list only of the entities with the corresponding components.

How I dealt with all of this until now was to have a ComponentManager, an EntityManager and a SystemManager. These classes however have very tight coupling with each other. The EntitManager needs to have access to the ComponentManager in order to handle the size of the the index lists and the mapping of each component type to them. It also needs access to actually add the components in the appropriate vector.
Another coupling is between the EntityManager and the SystemManager. Whenever an entity is created, it needs to be added to the list of the appropriate Systems.

A general event bus would appear to help but I am not sure how to implement it without making it global.

How do I improve this design by removing coupling while still maintaining the system's functionality?

答:
From what I can understand, you have something like this:

And all this tight coupling between these Managers is strictly for optimization purposes (using indices to cut costs on the size of a pointer while gaining easy spatial locality using a vector, e.g.).

In this case, I'm going to suggest something bizarre.

The idea is to get everything you need from a slightly more monolithic EcsManager object consolidating all of these concerns. This might seem like a borderline violation of SRP, but when you have these manager designs so tightly coupled together, it might simplify the practical implementation and design quite a bit over 3 classes that are really tightly coupled together.

Effectively that's what you have to me with these three managers so tightly coupled together. They want to become one manager to rule them all. I think we can get away with this because the needs of an ECS framework won't have varying requirements -- what an ECS needs is well-understood.

You could still keep these "sub-managers" if that simplifies the implementation of EcsManager a bit, though it might be even simpler if you just did this:

A general event bus would appear to help but I am not sure how to
  implement it without making it global.

For this part, I think it'd help both efficiency and simplicity to just use a lazy approach. For example, when new entities are added to a system, new components to an entity, or new component types of interest are added to a system, you can just mark the relevant systems as "dirty". Then when you get to a point where systems are processed, if they are dirty, they can retrieve the latest list of entities containing the components the system is interested in, and perhaps with the indices to the matching entities sorted on the fly (will improve spatial locality).

Your EcsManager then actually stores all the real, meaty data associated with the ECS framework. Your Entity and System and Component classes then just kind of turn into handles for convenience.

I think this is the easiest approach given the kind of design you are establishing, and also make achieving both thread safety and efficiency a little bit easier (though thread efficiency is tough here).

ContentLicense: CC BY-SA 4.0

Title: Entity Component System Coupling


问:
Are exceptions only for handling errors?
I have a script that throws exceptions when something goes wrong. However, for the purposes of testing I also want to capture specific points although I'm not sure whether they would be deemed errors or not.

Below is an example:

```<code>if ($model->fetchCurrentlyProcessing() > 0) {
    throw new App_Exception_CurrentProcess('There is a currently process running. Stopping process.');
}

if ($model->fetchQueuedItems() == 0) {
    throw new App_Exception_NothingInQueue('Nothing in queue. Stopping process.');
}
</code>```

In my tests I want to mock the response from these $model methods and detect which exception was thrown, and whether it was the expected exception or not. By throwing exceptions in these cases I can identify exactly at what point the script stopped. But I'm not sure if this is the correct usage of Exceptions as these possible aren't errors to be precise, as in nothing went wrong.

答:
An exception signifies an "exceptional situation" due to which a piece of code stops working.  This may be an error, but it may also be any other situation which is exceptional and it prevents the code from doing its job.

So, both of your examples appear very good cases of exceptions to me: your code is supposed to do a certain job, and it cannot do it, so it throws an exception.

What it boils down to is how you define an "exceptional situation", and by extension, how you describe what your code does.  If you call your code "process items in queue", then not finding any items in the queue is an exceptional situation.  If you call your code "process queued items, if any", then not finding any items in the queue is not an exceptional situation.


答: While I agree with most of what Mike said, I would say your way is never the right way to use exceptions. You are basically replacing something like "if queue is empty, return" with an exception. That is, you are using exceptions as a way of flow control to implement your basic algorithm and that is not good. Exceptions handle exceptional situations and while those are not necessarily errors, they typically are and should at least indicate a situation that renders continuing pointless. Finding out your queue is empty or there is still some task running so you have to wait a bit longer is hardly a ruin of plans. And since you will be doing this routinely, it will impact performance because exceptions aren't cheap, which is not an issue in case of an abort, but this is not an abort, it is just a loop.</p>

Title: Are exceptions only for handling errors?

Body:
I have a script that throws exceptions when something goes wrong. However, for the purposes of testing I also want to capture specific points although I'm not sure whether they would be deemed errors or not.

Below is an example:

```<code>if ($model->fetchCurrentlyProcessing() > 0) {
    throw new App_Exception_CurrentProcess('There is a currently process running. Stopping process.');
}

if ($model->fetchQueuedItems() == 0) {
    throw new App_Exception_NothingInQueue('Nothing in queue. Stopping process.');
}
</code>```

In my tests I want to mock the response from these $model methods and detect which exception was thrown, and whether it was the expected exception or not. By throwing exceptions in these cases I can identify exactly at what point the script stopped. But I'm not sure if this is the correct usage of Exceptions as these possible aren't errors to be precise, as in nothing went wrong.


问:
Strategy Pattern Implementation
I have to generate a code that will send through SMS or Email to implement the One Time Password (OTP) requirement of our client.

I just finished creating the design using strategy pattern, .
.

This it the first time I've used strategy pattern in real life projects so I would like to ask if I'm doing it right.

Below is just a sample code that will be used by client.

```<code> //OTPGeneratorStrategy generatorStrategy = new EmailGeneratorStrategy("test@gmail.com"); for sending to Email for example
OTPGeneratorStrategy generatorStrategy = new SmsGeneratorStrategy(993454454545);
OTPGeneratorContextgeneratorContext = new OTPGeneratorContext(generatorStrategy);
context.generate("1-12345-0");

OTPValidatorStrategy validatorStrategy = new SmsValidatorStrategy();
OTPValidatorContext validatorContext = new OTPValidatorContext (validatorStrategy );
try {
validatorContext.validate("1-12345-0","e7241f");
} catch (InvalidVerificationKeyException ivk) {
System.out.println("Verification key is invalid!");
} catch(VerificationKeyExpiredException vke) {
System.out.println("Verification key is already expired, Please regenerate");
}
</code>```

Updated:

Thank you for the feedback, actually I was not able to update my latest UML design and already separated the generation and validation.

And the reason why I've used Exception rather than enums because the project was built in java 1.4.

答:
First thing that strikes me as a problem is using exceptions for validation result. Don't use exceptions for application logic. Just return an enum value. I would assume there are not many ways validation can end up.

Next thing I would question is using of two strategies. What would happen if you used SMS generator with Email validator? To me, it seems there should be just one strategy with both generate and validate methods. As for "merging the two violates SRP", I would actually say having them separate violates SRP. SRP is about cohesion. And cohesion works both ways. It separates non-cohesive code and joins cohesive code that was split. Ask yourself "If I changed how Email one-time-password policy worked, would I change only generator or validator or would I have to change both?". I'm quite sure you would need to change both, meaning generation and validation are cohesive parts. If you are worried about putting email sending into the strategy implementation, then that should be strategy's concern. OTPContext doesn't need to be bothered by that. It doesn't need to know generation uses some special logic, that is not relevant to validation.

Last nitpick is that I would prefer if strategy was set to OTPContext in a constructor instead of getters/setters. What would happen if you changed the validator strategy after code was generated? You should keep things read-only unless there is explicit requirement for things to change.

Title: Strategy Pattern Implementation


答: An exception should be thrown whenever a function cannot return a value or a method is unable to meet it's post-condition. This can happen because the inputs are out of range or because of some external condition. It doesn't matter how often the exception is thrown. </p>


问:
different between ES6 and Javascript
What is ES6? Is it JavaScript? Or multiple language supporter?

I searched for it but can't understand it, especially the page on Wikipedia. Is it better than Javascript? And what can I do in my web developing using this language?

So what ES6 is, and how can I use it in my web app developing ?

答:
ES6 is short-hand for EcmaScript 6, which is a deprecated name for the EcmaScript 2015 language specification. ES2015 is the 6th version of EcmaScript, thus why it was previously referred to as ES6. For reasons best known to themselves, those responsible for defining the language standard renamed it to ES2015 with the final version of the v6 spec.

EcmaScript is the "official" name for JavaScript. Now that ES2015 is finalised, it effectively just becomes JavaScript v6 to most people.

Aside from ES4, there is no real difference between JavaScript and EcmaScript. ES4 introduced classes and static typing and was the standard behind Flash's ActionScript 3, but it was never ratified as a JavaScript language, as it introduced too many breaking changes. It was eventually abandoned and ES3.1 became ES5, which is the JavaScript version used in the "HTML5" world.

Title: different between ES6 and Javascript


问:
How do I have a group of numbers which total does not exceed a limit, and each number must be >= 0?
Suppose I have an array of n numbers. The rules for the array is as below:

All the numbers must add up to 1000

If a number changes (positive or negative), all the other numbers in the array must be adjusted so that the sum of the array is still 1000

The hard part - all numbers must be greater than or equal to 0.

Number 1 and 2 can be easily done by getting the delta of change, and spreading the delta among the other numbers. The trick is condition 3.

There's a question asking for its application. The numbers are percentages to be fed into pie chart; the user can adjust each pie segment with a slider. As it is a pie chart using percentages, all the sliders must add up to 100% - meaning if the user drag the slider to reduce the size of one pie slice, all the other pie slices should increase. No slice of the pie should be less than 0 or more than 100.

答:
Basically, your range is 0 to 1000.  When one value is changed, your new range is 0 to sum(N).  You want to then normalize to 0 to 1000.  So you compute the fraction of the total for each value and then multiple by 1000.  Each value is thus multiplied by 1000/sum(N). Here's an example:

```<code>[100,100,300,500]
</code>```

Now suppose we change one value:

```<code>[100,300,300,500] # sums to 1200
</code>```

Now multiple each value by 1000/1200.  (The range you want divided by the sum you have.)

```<code>[83, 250, 250, 417] # sums to 1000
</code>```

Updated

As @AProgrammer points out, depending on how you round, you may be off by one.  You probably want to use the floor as a result and then add one to entries until you reach the desired sum.  Or alternatively, if the APIs that consume this can use floating point values, use those.

Body:
Basically, your range is 0 to 1000.  When one value is changed, your new range is 0 to sum(N).  You want to then normalize to 0 to 1000.  So you compute the fraction of the total for each value and then multiple by 1000.  Each value is thus multiplied by 1000/sum(N). Here's an example:

[100,100,300,500]

Now suppose we change one value:

[100,300,300,500] # sums to 1200

Now multiple each value by 1000/1200.  (The range you want divided by the sum you have.)

[83, 250, 250, 417] # sums to 1000

Updated

As @AProgrammer points out, depending on how you round, you may be off by one.  You probably want to use the floor as a result and then add one to entries until you reach the desired sum.  Or alternatively, if the APIs that consume this can use floating point values, use those.


答:
As a programming problem, there are lots of easy answers to this; three quick brainstormed ones:

When you increase a slice, decrease the size of the last slice with a size greater than zero by an equivalent amount.

When you increase a slice, decrease the size of the largest slice by an equivalent amount.

When you increase a slice, decrease the size of all other slices in proportion to their current values. For example, if your slices where currently sized (10, 20, 30, 40) and you increased the 40 slice to 46, distribute this reduction among the other slices in the ratio 1:2:3 so you end up with (9, 18, 27, 46).

And fairly obvious equivalent algorithms for decreasing a slice.

However, this is probably more interesting as a UX problem - which algorithm produces the most "intuitive" behaviour? As such, it may be worth asking at User Experience.

Title: How do I have a group of numbers which total does not exceed a limit, and each number must be >= 0?

Body:
Suppose I have an array of n numbers. The rules for the array is as below:

All the numbers must add up to 1000

If a number changes (positive or negative), all the other numbers in the array must be adjusted so that the sum of the array is still 1000

The hard part - all numbers must be greater than or equal to 0.

Number 1 and 2 can be easily done by getting the delta of change, and spreading the delta among the other numbers. The trick is condition 3.

There's a question asking for its application. The numbers are percentages to be fed into pie chart; the user can adjust each pie segment with a slider. As it is a pie chart using percentages, all the sliders must add up to 100% - meaning if the user drag the slider to reduce the size of one pie slice, all the other pie slices should increase. No slice of the pie should be less than 0 or more than 100.


问:
Does this class design violate the single responsibility principle?
Today I had an argument with someone.

I was explaining the benefits of having a rich domain model as opposed to an anemic domain model. And I demoed my point with a simple class looking like that:

```<code>public class Employee
{
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastname;
    }

    public string FirstName { get private set; }
    public string LastName { get; private set;}
    public int CountPaidDaysOffGranted { get; private set;}

    public void AddPaidDaysOffGranted(int numberOfdays)
    {
        // Do stuff
    }
}
</code>```

As he defended his anemic model approach, one of his arguments was: "I am a believer in SOLID. You are violating the single responsibility principle (SRP) as you are both representing data and performing logic in the same class."

I found this claim really surprising, as following this reasoning, any class having one property and one method violates the SRP, and therefore OOP in general is not SOLID, and functional programming is the only way to heaven.

I decided not to reply to his many arguments, but I am curious what the community thinks on this question.

If I had replied, I would have started by pointing to the paradox mentioned above, and then indicate that the SRP is highly dependent on the level of granularity you want to consider and that if you take it far enough, any class containing more than one property or one method violates it.

What would you have said?

Update: The example has been generously updated by guntbert to make the method more realistic and help us focus on the underlying discussion.

答:
That the class represents data is not the responsibility of the class, it is a private implementation detail.

The class has one responsibility, to represent an employee. In this context, that means it presents some public API that provides you with functionality you need to deal with employees (whether AddHolidays is a good example is debatable).

The implementation is internal; it so happens that this needs some private variables and some logic. That doesn't mean that the class now has multiple responsibilities.


问:
Do MSBuild project files serve the same purpose as NMAKE makefiles in a build process? (practically equivalent)
I'm finding it difficult to understand Microsoft's motive behind building conceptual "projects" like this. They ship MSBuild.exe and NMAKE.exe together with a Visual Studio 2015 install but they both appear to serve the same purpose.

If they are both (in a practical sense) equivalent but using different formats, I won't bother learning how to write both. If they both have their own purposes, I might reconsider.

The following text is just my current theory on the whole thing... but I asked this question because there could be people here with experience customizing these files unlike myself...

It seems like MSBuild is made for those that depend heavily on the Visual Studio environment (.sln files) for compilation. And upon reading a little bit about it, I asked myself: Couldn't compilation of dependencies be separated by different projects allowing for partial compilation when using MSBuild? That would involve having multiple projects in a solution and then building the solution to build the entire product.

As you can see... I'm trying to understand the philosophy of MSBuild and why it's needed in the build process. At the moment, I'm starting to wonder if it's actually based on NMAKE and compiles down into NMAKE commands. That would make a whole lot of sense because I cannot see why anyone would need both in the same build process.

答:
Both fulfill the same purpose of controlling and automating complex build processes. However, MSBuild is more modern, has more capabilites, and it integrates much (!) better into the build process of the Visual Studio IDE (both use actually the same "input file format" like csproj and sln files). Those project files can actually be edited and maintained (at least,to 98%) by a well structured "project properties" dialog. That is not possible easily with nmake files, because NMake was never designed for this purpose.

IMHO NMake is shipped with Visual Studio because of backwards compatibility, because of better cross platform compatibility, and because it is sometimes better suited for tasks where you have to integrate tools into your build process which are completely outside the VS IDE. The latter can be accomplished with MSBuild, too, but NMake is IMHO often a better fit if you have to create your build configuration manually - because that is what make was designed for.

NMake was Microsoft's implementation of the Unix make command, which has origins back to 1977, according to Wikipedia. Because of that history, there are still lots of projects using makefiles. Especially in the Unix/Linux world, make is still a widely used tool, and a tool like NMake provides better compatibility to the make tools used in that ecosystem.

Couldn't compilation of dependencies be separated by different projects
  allowing for partial compilation when using MSBuild? That would
  involve having multiple projects in a solution and then building the
  solution to build the entire product.

That is the standard approach for any bigger project, nothing really surprising. But on that abstraction level, it is not different from make/NMake.


问:
Are colons ok in a REST API?
I see many REST API examples with URIs like http://<whatever>/widgets or http://<whatever>/widget/123, for a specific thing. For most things I would just stick with the front slash, but when requesting a specific id I'd rather use a colon, like http://<whatever>/widget:123.

According to what I found here about best practices, there wasn't much about using the colon, specifically. It sounds like it's acceptable, but is it/what might be some pitfalls to using them instead of the slash?

Express.js seems fine with them (as far as code is concerned):

app.get('/widgets::id', function(req, res){ <...> });

Update: I just stumbled on this. It's sounding like colons are perfectly fine for this use.

答:
Following the specification for URL laid out in the original RFC1738 or in RFC3986 for URI spec, colon (:) is reserved for specific purposes. The slashes in the path portion of the URL are there to connote a hierarchy.

So while your application does not break when a route with colons in the path matches it does not follow the proposed specification.  The spec is an agreed upon standard.  Your applications can do whatever you want though.

Title: Are colons ok in a REST API?


问:
Set of specific values implementation vs. using some sort of generic set with advanced checks
I am working on a set implementation in JavaScript currently. This should kind of simulate generics as known from Java or C#. I need a mutable version of that (allows for adding/removing set values) and an immutable one.

My constructor signature looks like this:

```<code>new GenericSet( 'number', [ 10, 20, 30 ] );
</code>```

,

```<code> // mutable set of mixed values (allows to add further values via "add")
 new MutableGenericSet( '*', [ 'foo', 42, {}, /./ ] );
</code>```

or

```<code>// DataValues.prototype.equals will be used by the set for determining equality.
new GenericSet( { type: DataValue, valueComparison: 'equals' }, [ dv1, dv2, dv3 ] );
</code>```

Just GenericSet or one set implementation per type?

Initially, my main purpose for this was to have sets of values of one type. E.g. a DataValuesSet which would only accept data Values. I could then define interfaces with functions that require a DataValuesSet instance. I could not use inheritance (and guess that would be bad anyhow), so I would use composition and have a GenericSet / MutableGenericSet instance internally.

An alternative approach would be to always take GenericSet and implement and use GenericSet.requireSetOfType( type ) which would throw an error if the set's type was not the required one. My concern with doing it this way is that my interface definitions would look less explicit.

Take

```<code>/**
 * @param DataValuesSet dataValues
 */
function printDataValues( dataValues ) {
    if( !( dataValues instanceof DataValuesSet ) ) {
        throw Error( '...' );
    }
    // ...
}
</code>```

vs.

```<code>/**
 * @param GenericSet<DataValue>
 */
function printDataValues( dataValues ) {
    // Throws error if dataValues is not a set or it it is a set with values of wrong type.
    GenericSet.requireSetOfType( dataValues, DataValue );
    // ...
}
</code>```

perhaps using @param GenericSet(DataValues) dataValues for documenting the second choice would be alright? Does anyone see any further implications with the second approach or are there any alternative suggestions? To me the, second one looks more intuitive and my concern with the first one is that I would just create more overhead with constructors while I can not see any clear advantage right now.

答:
I would say that the first example is more readable. It does not imply that an error is thrown for the incorrectly typed set. It says that this function takes a DataValueSet. Being explicit in your code adds clarity.

GenericSet.requireSetOfType obfuscates the intent of the type check in the print function. It looks like it is checking for items with type DataValue.


问:
How to design a function that takes a date and gives out a number between 1-6, always the same for all dates
As a part of an algorithm I'm making I need to make a function that takes the current date to a function and gives out a number between 1-6, and not the same number for two consecutive dates. And it should always return the same number for a given date.

A simple solution would be to make any Monday 1, Tuesday 2, Wednesday 3, etc, but since we only have 6 values just give Sunday 3 again. And then next Monday 1.

The problem with this algorithm is that it's really predictable. A good algorithm should be harder to guess for others.

Any tips on how to approach this?

答:
Try setting limit for 1-6 in Random class of java util package ie, Random number generator.

It may help you

```<code>/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int n = 3,j=0;
        Random r = new Random();
        String a[] ={"sunday","monday","tuesday"};
        int i =r.nextInt(3)
        for(;;)
        {
         System.out.println(a[i]+""+i);
            j++;
            if(j>3)
            {
        System.exit(0);
            }
        }
   // check next int value
   //System.out.println("Next int value: " + randomno.nextInt(6));
    }
}
</code>```

Body:
Try setting limit for 1-6 in Random class of java util package ie, Random number generator.

It may help you

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int n = 3,j=0;
        Random r = new Random();
        String a[] ={"sunday","monday","tuesday"};
        int i =r.nextInt(3)
        for(;;)
        {
         System.out.println(a[i]+""+i);
            j++;
            if(j>3)
            {
        System.exit(0);
            }
        }
   // check next int value
   //System.out.println("Next int value: " + randomno.nextInt(6));
    }
}


答:
A compromise between Bent and Doc Brown's approaches might be to take the Julian Date modulus of a multiple of 6 (eg. 36), then lookup the corresponding value (between 1 to 6) in a quasi-random list that satisfies the "consecutive constraint".

For 36, such a list might be:

```<code> 246531451362532614364125615343123456
</code>```

which corresponds to the end word order in a Sestina (with the verses reversed).

Title: How to design a function that takes a date and gives out a number between 1-6, always the same for all dates

Body:
As a part of an algorithm I'm making I need to make a function that takes the current date to a function and gives out a number between 1-6, and not the same number for two consecutive dates. And it should always return the same number for a given date.

A simple solution would be to make any Monday 1, Tuesday 2, Wednesday 3, etc, but since we only have 6 values just give Sunday 3 again. And then next Monday 1.

The problem with this algorithm is that it's really predictable. A good algorithm should be harder to guess for others.

Any tips on how to approach this?

Body:
A compromise between Bent and Doc Brown's approaches might be to take the Julian Date modulus of a multiple of 6 (eg. 36), then lookup the corresponding value (between 1 to 6) in a quasi-random list that satisfies the "consecutive constraint".

For 36, such a list might be:

 246531451362532614364125615343123456

which corresponds to the end word order in a Sestina (with the verses reversed).


答:
Produce the number in two steps:

Step 1: ensure that no consecutive dates have same number

Step 2: make it hard to guess

For step 1 choose a serial number for each date (e.g. number of days since 1.1.2000). If this number is even, let the result be even, if the serial number is odd let the result be odd. This ensures that even and odd days alternate, therefore two consecutive days will never be the same.

For makeing hard to guess you can chose any hash function on the date which gives you one of three results.

```<code>n = serial(date)
if n is even:
   step1 = 1
else:
   step1 = 0

h = hash(date)
step2 = (h % 3) * 2 + 1

result = step1 + step2
</code>```

in this pseudo code step2 is always odd. Therefore after you add step1 you get a result with the same parity as n. This ensures that you never get the same result for consecutive days.

To hide the fact that even and odd numbers alternate, you could add a permutation in the end (e.g. switch results 3 and 4)

Body:
Produce the number in two steps:

Step 1: ensure that no consecutive dates have same number

Step 2: make it hard to guess

For step 1 choose a serial number for each date (e.g. number of days since 1.1.2000). If this number is even, let the result be even, if the serial number is odd let the result be odd. This ensures that even and odd days alternate, therefore two consecutive days will never be the same.

For makeing hard to guess you can chose any hash function on the date which gives you one of three results.

n = serial(date)
if n is even:
   step1 = 1
else:
   step1 = 0

h = hash(date)
step2 = (h % 3) * 2 + 1

result = step1 + step2

in this pseudo code step2 is always odd. Therefore after you add step1 you get a result with the same parity as n. This ensures that you never get the same result for consecutive days.

To hide the fact that even and odd numbers alternate, you could add a permutation in the end (e.g. switch results 3 and 4)


答:
Build a hash based on the following formula...

```<code>2 A(d) + B(d) + 1
</code>```

A(d) is a hash of the date in the range 0 to 2 inclusive.

B(d) is the least significant bit of a day-number representation of the date.

Because consecutive values of 2 A(d) never differ by exactly 1 (or any odd number), and because consecutive values of B(d) always differ by precisely 1, consecutive values of the combined result are never equal.

The easiest way to compute a suitable unpredictable A(d) is probably to use a standard hash algorithm, but take the result modulo 3. Hash algorithms generally give a result in the range 0..(2^n)-1 (or for signed arithmetic, -2^(n-1) .. (2^(n-1))-1). If you have signed hashes, make sure you're using a modulo/remainder that never gives negative results, or else correct for that. Genuine modulo, or remainder for division rounding to negative infinity, always give non-negative results. Remainders for other division rounding schemes such as the common "truncation" (toward zero) scheme may need checks to correct for that. C and C++ leave the division rounding scheme implementation-defined, so the remainder/modulo behaviour for negative values is similarly implementation-defined.

There's a small bias using modulo to convert to a 0..2 range, but that's unavoidable - 2^n distinct domain values cannot be precisely equally shared for 3 range values. The bias will be small, though, if n is anything you're likely to see in practice (32 or 64 bits).

Body:
Build a hash based on the following formula...

2 A(d) + B(d) + 1

A(d) is a hash of the date in the range 0 to 2 inclusive.

B(d) is the least significant bit of a day-number representation of the date.

Because consecutive values of 2 A(d) never differ by exactly 1 (or any odd number), and because consecutive values of B(d) always differ by precisely 1, consecutive values of the combined result are never equal.

The easiest way to compute a suitable unpredictable A(d) is probably to use a standard hash algorithm, but take the result modulo 3. Hash algorithms generally give a result in the range 0..(2^n)-1 (or for signed arithmetic, -2^(n-1) .. (2^(n-1))-1). If you have signed hashes, make sure you're using a modulo/remainder that never gives negative results, or else correct for that. Genuine modulo, or remainder for division rounding to negative infinity, always give non-negative results. Remainders for other division rounding schemes such as the common "truncation" (toward zero) scheme may need checks to correct for that. C and C++ leave the division rounding scheme implementation-defined, so the remainder/modulo behaviour for negative values is similarly implementation-defined.

There's a small bias using modulo to convert to a 0..2 range, but that's unavoidable - 2^n distinct domain values cannot be precisely equally shared for 3 range values. The bias will be small, though, if n is anything you're likely to see in practice (32 or 64 bits).


问:
If AngularJS already takes care of the MVC, would using ReactJS be needed if it is just the View part?
I heard that AngularJS is becoming quite popular, and at the same time ReactJS is also.  But if AngularJS already takes care of MVC with 2 way binding between model and view, would ReactJS actually be needed?

I thought ReactJS is binding model to view, but not binding view to model (say, if it is a form text input field, if the value change, it won't go to the model?)  In fact, ReactJS seem to do what CanJS was doing, by reflecting what the model is by building a template, and whenever the model changes, the view is automatically updated -- there is no need to do anything at all.  But doesn't AngularJS already do that?

答:
AngularJS is a full-featured front-end framework. It takes care of the three parts of MVC, plus the structure of the overall application (dependency injection, routing, ajax, etc.).
You don't need React for Angular. You actually don't need anything else than Angular.

ReactJS is a specific library for the "V" part of MVC. It's only about the view. If you don't need anything else, just use React. If you need routing, ajax, events handling, etc., the philosophy of the React/Flux stack is to use specialized libraries for that (react-router, some Flux implementation, Immutable.js, etc.).

These are two different approaches. You can replace Angular's directives with React's components, thus using Angular for the "MC" and React for the "V", and there are some benefits of this (mostly performance, also, React components are simpler to reason about than Angular directives).

If you are starting a project with Angular or already using it, just stick to Angular, don't make things more complicated that needed.
If you are considering using React, then read about how to structure your application using Flux or a similar approach, because it's going to be completely different than Angular. Then choose the one you like the most (knowing that Angular2 is coming, with a design that is closer to that of Flux/React).


问:
Alternative to Anemic domain objects (Simple example provided)
I want to model (TV)Events and Reminders and I’m wondering what’s ‘the best’ way to model this.

The requirements are roughly

When an Event has no Reminder, a Reminder can be created

When an Event has a Reminder

the Reminder can be deleted

an icon is shown on the Event

A separate Screen exists presenting all Reminders

Reminders are stored in the backend and have multiple properties

Obviously, our real domain is larger and also contains Channels, Recordings, ...

Basically, we need functions to

create a Reminder

delete a Reminder

get the list of all Reminders

check if an Event has a Reminder

This seems a relatively simple problem but I'm struggling with it. Below, I’ve collected a number of possible options and I would greatly appreciate your feedback.

Option 1

Event creates Reminders

Event API

```<code>Reminder createReminder() //adds the Reminder to the backend
boolean  hasReminder()
</code>```

Reminder API

```<code>void deleteReminder() //removes the Reminder from the backend
static List<Reminder> getAllReminders()
</code>```

But

deleting and creating a Reminder are symmetric functions and hence I would expect them on a single API (now both Event and Reminder have an interface to the backend)

I'm not a big fan of the static function on Reminder. It seems to indicate that a higher-order object should exist

Option 2

Reminder API

```<code>Reminder createReminder(Event event) //adds the Reminder to the backend
void deleteReminder() //removes the Reminder from the backend
boolean hasReminder(Event event)
static List<Reminder> getAllReminders()
</code>```

Advantage is that the Event API doesn't change when adding Reminder functionality (=> good wrt extendibility I guess).
But

creating a Reminder for a Event (and checking whether an event has a reminder) seems to be more a function on Event so I would expect them on the Event API

Option 3

Event API

```<code>Reminder createReminder() //adds the Reminder to the backend
void deleteReminder() //removes the Reminder from the backend
boolean hasReminder()
static List<Reminder> getAllReminders()
</code>```

But

the getAllReminders() seems more a function on Reminder

Option 4

Create a ReminderManager/ReminderService (singleton) with the following API

```<code>Reminder createReminder(Event) //adds the Reminder to the backend
void deleteReminder(Reminder) //removes the Reminder from the backend
boolean hasReminder(Event event)
List<Reminder> getAllReminders()
</code>```

This is my preferred option but

This results in anemic Event/Reminder objects (just getters and setters but no logic). There seems to be discussion whether this is an anti-pattern or not

答:
I don't see any OO design in your question so I took the liberty to make some.

--

public interface Event {
    public void setDate(java.util.Date date);
    public java.util.Date getDate();
    public void setDescription();
    public String getDescription();
    public boolean hasReminder();
    public void addReminder(Reminder reminder);
}
```

<hr>

<p>You need to set the <code>Event</code> to create a <code>Reminder</code>, the <code>Reminder</code> will add itself to the <code>Event</code> with the callback <code>addReminder(Reminder reminder);</code> of <code>Reminder</code>.</p>

<pre class="lang-java prettyprint-override"><code>public interface Reminder {
    public void setEvent(Event e);
    public Event getEvent();
    public void setDescription();
    public void setScheduleInfo(ScheduleInfo ei);
    public boolean existsInBackEnd();
    public void save();
    public void delete();
}
</code>```

--

Schedule info can be complex so I resorted to a cron-like string to simplify this

public interface ScheduleInfo {
    public void setPriority(Priority p);
    public void setCronString(String cronstr);
}
```

<p>--</p>

<pre class="lang-java prettyprint-override"><code>public enum Priority {
    NONE,LOW,MEDIUM,HIGH,URGENT
}
</code>```

--

This is a generic ListManager that will work for events and reminders.

import java.util.List;
public interface ListManager<T> {
    public void populateFromBackEnd();
    public void add(T e);
    public void remove(T e);
    public boolean exists(T e);
    public List<T> getAll();
    public void saveAllToBackend();
}
```

<p>--</p>

<pre class="lang-java prettyprint-override"><code>public interface EventListManager extends ListManager<Event> {
}
</code>```

--

public interface ReminderListManager extends ListManager<Reminder>{
}
```

Body:
I don't see any OO design in your question so I took the liberty to make some.

--

public interface Event {
    public void setDate(java.util.Date date);
    public java.util.Date getDate();
    public void setDescription();
    public String getDescription();
    public boolean hasReminder();
    public void addReminder(Reminder reminder);
}

You need to set the Event to create a Reminder, the Reminder will add itself to the Event with the callback addReminder(Reminder reminder); of Reminder.

public interface Reminder {
    public void setEvent(Event e);
    public Event getEvent();
    public void setDescription();
    public void setScheduleInfo(ScheduleInfo ei);
    public boolean existsInBackEnd();
    public void save();
    public void delete();
}

--

Schedule info can be complex so I resorted to a cron-like string to simplify this

public interface ScheduleInfo {
    public void setPriority(Priority p);
    public void setCronString(String cronstr);
}

--

public enum Priority {
    NONE,LOW,MEDIUM,HIGH,URGENT
}

--

This is a generic ListManager that will work for events and reminders.

import java.util.List;
public interface ListManager<T> {
    public void populateFromBackEnd();
    public void add(T e);
    public void remove(T e);
    public boolean exists(T e);
    public List<T> getAll();
    public void saveAllToBackend();
}

--

public interface EventListManager extends ListManager<Event> {
}

--

public interface ReminderListManager extends ListManager<Reminder>{
}


问:
Multi tenancy or multi instance?
I'm trying to build a web-based SaaS solution, and I hit a road where I'm not sure to use multi tenancy or multi instance. I will try to describe what I'm trying to achieve, and each approach advantages and disadvantages (my opinion, according to what I read). Please include your suggestions in case I missed anything in one approach over the other.

The application that I'm trying to build is, as I mentioned, a SaaS solution where companies can create their accounts, and each account/company has it's own users, customers, products, services...etc. Each user; who is a company employee; related to one account/company will have access only to his/her company customers, products, and services. Companies could have unlimited number of customers, products and services, thus each company should have it's own data center.

For that I decided to create a shared database (saving all users credentials for login purposes) and multiple databases shared schema (database per account/company). Basically, Multi Tenancy.

Then somebody suggested to use Multi Instance instead, where each company will have its own instance of the application (i.e. code, libraries, database, frameworks... etc) totally separated from the other companies. This sounds better as I don't have to take care of an extra layer where I need to make sure that each tenant's users have access only to their company's data. I think it's good to mention that I'm depending on Docker to achieve this approach (I've never used it before), but I think it lacks features (more on those later) I will need in the future (at least I didn't find them with a little bit of search).

However, each approach comes with pros and cons, so I couldn't make a decision with which approach to go. Here is a list, but bare with me as I lack the knowledge in them both, so there could be something that I'm not aware of, or a solution for a problem I didn't find on the web: [Each approach has an ordered list of which I followed a one by one comparison]

Multi Tenancy:

Shared host/hardware, shared code, and multi database.

It's easier to extend the functionality of the code and fix bugs (shared code).

It's harder to extend the hardware (could use a cloud service), or move the database of individual tenant to another system without doing changes to the code.

Most importantly, as I mentioned before, I need to add an extra layer to the system to make sure that the user is actually belongs to his/her company, and not accessing other company's information.

Multi Instance:

Shared or unshared host/hardware, code per instance, and database per instance.

It's harder to extend the functionality or fix bugs (I'm not sure if there is a way to do it in Docker where you can add functionality/feature to one instance or Docker container, and deploy it to the others).

It's easier to move the whole instance to a different host/hardware.

As the instance, I don't need to take care of that layer as each instance will have its own database.

All of the advantages and disadvantages are redundant in case I want to do anything manually (as creating an instance for each tenant manually), and that's why I doubt the Docker solution, unless there is a way to solve that, which is maybe the main reason of the question. I would appreciate it if you would answer the question with references to the solutions, and why do you think this approach is better than the other.

In case that would help (maybe?), we're using Laravel as the main framework for the back-end (all RESTfully).

答:
I am asking myself the exact same question at the moment.

I am leaning towards the multi-instance single tenancy solution but have not taken a definitive decision yet. Let me share some of my thoughts :

The main historical advantage of the multi-tenant architecture is a better use of infrastructure resources, by mutualisation (single OS, single Database, single application layer) and better occupying of said resources (when one user is away another can use the same resource).

It also greatly simplifies software lifecycle : you deploy new versions to you one instance, all the customers are updated at the same time.

It seems however, that recent advancements in cloud technology make the first class of advantages largely available in a multi-instance (instance-per-customer) architecture (I am thinking specifically of a platform like Jelastic here but I am sure there are others that provide the same features):

Container-based PaaS

Provisioning and auto-scaling of containers (elastic containers)

So hardware and platform management is not the Software provider's concern any more. Resources are mutualised much more efficiently than before at the infrastructure and plaform levels.

There will still be an overhead for multi-instance (some app and middleware will be ran N times instead of just one), but much lower than when using a separate (virtual) machine per instance. The database could be shared anyway (one schema per instance, several schemas per DB server)

Also :

Automation of creation of new instances is possible via PaaS API

Automation of deployment of new versions is possible via PaaS API, with zero downtime (takes some work to put in place)

Scaling is always out, never up. We don't have to worry about huge datasets at the instance level.

Of course, we would need some kind of central service that manages all this automatically (e.g. creation of instance when a new user creates an account). This would also manage payment and licensing issues, interaction between instances etc. This central service might be quite complex and hard to develop, but the good thing is that we don't have to implement it upfront (now that we don't have much resource) whereas multi-tenant would need to be baked into the app from the start.

Which brings me to the final advantages of developing single-tenant for a very early stage (pre-invesment) startup project :

Same (or almost same) version of the app can be deployed on-premises either as a virtual appliance or docker container or even on customer-managed machine (some companies are still reluctant towards the Cloud and it may help an early stage startup to not push out important early adopters)

Faster to get a product out with limited resources (the application layer and database schema is quite less complex), can get a "dumb" single instance single tenant product out first (MVP) for early adopters and to show the business value of the app to potential investors, and add all the cloud automation later on

Can be seen as a selling argument for customers worried about data security : the data is better encapsulated since every customer has his own schema or even database. Much less risk of "spillage"

NB: I am obviously thinking here of a business app where customers would be businesses (each with multiple individual users) and not individuals. It would not make any sense to run a separate instance of an app for each individual user (or would it ?)

Title: Multi tenancy or multi instance?


问:
Which design pattern to choose when supporting multiple analytic tools?
I have spent quite some time learning all possible design patterns but I cannot find the ideal one for the following case. I am developing an iOS app where we are using multiple analytics tools like Google Analytics/Facebook Analytics and it is possible that in the future we will add some more (our company is obsessed with measuring :D).

Each of them uses their custom SDK to log an event which comes with its own method to send an event and its own parameters. I would love to refactor it and create a module where adding new analytics tool wouldn't lead to code smell and in best case scenario there would be a central place which would dispatch the events at once.

I was thinking about this:

Defining a protocol AnalyticsProtocol which requires implementation of sendEvent method

Defining AnalyticsEvent class for every tool (FacebookAnalyticsEvent, GoogleAnalyticsEvent) which conforms to the protocol above and implements sendEvent method. Each of these classes would have its own init method.

Cental dispatch class which takes an array of id<AnalyticsProtocol> objects and calls sendEvent on every single one of them.

Do you have any better ideas? Thanks.

答:
Each of them uses their custom SDK to log an event which comes with its own method to send an event and its own parameters. I would love to refactor it and create a module where adding new analytics tool wouldn't lead to code smell and in best case scenario there would be a central place which would dispatch the events at once.

This feels like the adapter pattern:

Intent

Convert the interface of a class into another interface clients expect.

Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

And from the same link:

Adapter Pattern and Strategy Pattern

Adapter Pattern and Strategy Pattern - there are many cases when the adapter can play the role of the Strategy Pattern. If we have several modules implementing the same functionality and we wrote adapters for them, the adapters are implementing the same interface. We can simply replace the adapters objects at run time because they implements the same interface.


问:
What is a Collection of Aggregates Referred to in Domain Driven Design?
E.g. in a domain model with two aggregate roots:

book

author

Is there a specific term that refers to a collection of aggregates of the same root type (e.g. a collection of books)?

In Confusion about the meaning of the word aggregate in domain driven design I read the term aggregate type, which might or might not fit, but I haven't found a direct mention in Evan's blue book.

答:
Is there a specific term that refers to a collection of aggregates (e.g. books or authors)?

No.

Keep in mind that the definition of aggregate is

A cluster of associated objects that are treated as a unit for the purpose of data changes. External references are restricted to one member of the aggregate, designated as the root. A set of consistency rules applies within the aggregate's boundaries.

A union of two different transactional units is... not very interesting.


问:
Should images be stored in a git repository?
For a distributed team that uses Git and GitHub as version control, should images also be stored in the git repository?

The images in question are small/medium-sized web-friendly images. For the most part, the images won't be changed. The folder containing them will only grow in size as images are added. A concern is that the image folder may grow to a large size over time by combination of large images or a lot of images.

Is this considered a best practice? What other alternatives are there to sharing binary files needed in projects that a distributed team can easily access?

答:
This question is pretty old but this is a common question that comes up when dealing with Git and there has some progress on modern solutions to storing large files in a Git repo since the last answer.

For storing large files in Git there are the following projects:

git-lfs - While I haven't used this extensively it appears to be the holy grail. It's backed by Github and is available on all their repos as of October 2015 and puts the complexity of file management on site storing your repos. Only downside is that this is fairly new, so beyond Github there isn't much support, though Gitlab also has support, as does Gitea, and Bitbucket has alluded to support in the future.

git-annex - This has been around for awhile but frankly it's complexity gets in the way.

git-media - No personal experience with this one. Seems fairly complex as well.

git-fit - An attempt to create a simpler plugin. Requires S3 storage. While I appreciate the simplicity my main concern with plugin is that it's fairly unknown and maintained by 1 individual (full disclosure, I am the only other committer at this time and it was for a trivial issue).

git-fat - Another, low-dependency approach.

TLDR: if you can, use git-lfs to store images or other binary files in git.


问:
How does an product order payment works during a race condition?
This is a pretty generalized question which I am asking.

Scenario 1

I have a product 'Pen' which has a quantity of 1. Now 2 users a and b has come to buy the product.User 'a' clicked on buy now and has started the payment processing and once the payment is completed the order for the product will be  created and I would reduce the quantity to zero and user b will see the product as 'Out of stock'. This a more macroscopic explanation.

Scenario 2

User a is making a payment and in between user b also clicked on pay and proceeded the payment process. user a completed the order and the quantity was reduced to zero.User b completed the payment and the order failed!

How does this problem is managed by e commerce sites? Is it like, when a user proceed for the payment of a product, is the quantity is reduced to zero and once if that order fails (due to a payment failure), does the quantity is incremented back so that other user can buy it?

How is this condition managed?

答:
There are many specific strategies for handling this.  Generally speaking, mostly it comes down to either using transactions of some sort (e.g. in the db, or locking objects in memory), or, using compensation strategies.  I would say that many business domains use a combination of both.

The concert domain typically allows making reservations, which are good for a few minutes, during which the order can be placed.  The reservation mechanism may use transactions, so the inventory goes from free, to reserved, to purchased (or back to free).  They won't attempt to charge you unless the reservation succeeds, but if your payment fails, they get the inventory back shortly.

Airlines this same problem, and also use reservations, but typically have a wider distributed computing problem in that they allow partner airlines and travel agents to also sell tickets.  As a result, they may end up overbooking a flight, and then they offer rewards for someone to give up their seat.  Especially in the old days, they would distribute some of the inventory in advance to the third party sellers, to try to help with the distributed computing problem.

An E commerce site may try to inform you of low inventory situation when you are viewing the item.  E commerce sites sometimes fail (inventory was just plain wrong, or, too much demand for some item), by taking payment when there is no inventory.  Then they apologize and return the payment.  Like the airlines, they may offer some additional compensation to the unfortunate user.

Fundamentally, in business, one expects to have agreements (i.e. for purchases), that sometimes fail and need to be dealt with. Failure could be at inventory, or the product get damaged/lost in shipping, or the product may be defective. Handling these things typically makes use of compensation strategies. One point of business operation is to tune these strategies (to maximize profit, maximize customer retention, etc...).


问:
How to properly reverse the if statement when you have two conditions in it?
In PHP I have this if statement ( $first and $second will evaluate to true or false):

```<code>if ($first && $second) {
    // evereything is OK
} else {
    throw new Exception()...
}
</code>```

My real code is much more complicated, I am trying to make simple example here.

I want to turn this if/else into one if with negation like this:

```<code>if (!($first && $second)){
    throw new Exception()...
}

// everything is OK
</code>```

As you can see in this example, I've put ! negation sign in front of parentheses. Is this correct ? Do I need to negate every condition itself like this:

if (!$first && !$second)

Or I should use || operator:

if (!$first || !$second) // I am using OR here

I am not sure how these conditions are going to evaluate at the end, and I am confused by my dummy testing results. I really hope that someone can explain to me how all these checks are going to evaluate at the end.

Thanks to everyone who answered my question. Due to my low rep, I can not up-vote or pick some answer as the right one. You are all good for me :)

答:
```<code>if (!$user == 'john' || !$status == 'active')
</code>```

This does not quite do what you think it does.

If you add the brackets as the parser will add them you get:

```<code>if ( (!$user) == 'john' || (!$status) == 'active')
</code>```

While you want:

```<code>if (!($user == 'john') || !($status == 'active') )
</code>```

The fix to this is to add the explicit brackets or to use the not equals operator != or !== depending on if you want the identity check as well.

Besides that this is where de Morgan's laws come in.

These state that !(a||b) == (!a && !b) and that !(a&&b) == (!a || !b)

Body:
if (!$user == 'john' || !$status == 'active')

This does not quite do what you think it does.

If you add the brackets as the parser will add them you get:

if ( (!$user) == 'john' || (!$status) == 'active')

While you want:

if (!($user == 'john') || !($status == 'active') )

The fix to this is to add the explicit brackets or to use the not equals operator != or !== depending on if you want the identity check as well.

Besides that this is where de Morgan's laws come in.

These state that !(a||b) == (!a && !b) and that !(a&&b) == (!a || !b)


答:
Build a truth table:

```<code>p  q    p && q    p || q    !(p && q)    !p || !q    !(p || q)   !p && !q
==========================================================================
0  0    0         0         1            1           1           1
0  1    0         1         1            1           0           0
1  0    0         1         1            1           0           0
1  1    1         1         0            0           0           0
</code>```

Thus, you see that !(p && q) is equivalent to !p || !q, but not equivalent to !p && !q. You see that !(p && q) and !p || !q are the opposite of p && q.

Note that !(p && q) and !p || !q are equivalent and can be proved by using the De Morgan's laws.

Title: How to properly reverse the if statement when you have two conditions in it?

Body:
In PHP I have this if statement ( $first and $second will evaluate to true or false):

```<code>if ($first && $second) {
    // evereything is OK
} else {
    throw new Exception()...
}
</code>```

My real code is much more complicated, I am trying to make simple example here.

I want to turn this if/else into one if with negation like this:

```<code>if (!($first && $second)){
    throw new Exception()...
}

// everything is OK
</code>```

As you can see in this example, I've put ! negation sign in front of parentheses. Is this correct ? Do I need to negate every condition itself like this:

if (!$first && !$second)

Or I should use || operator:

if (!$first || !$second) // I am using OR here

I am not sure how these conditions are going to evaluate at the end, and I am confused by my dummy testing results. I really hope that someone can explain to me how all these checks are going to evaluate at the end.

Thanks to everyone who answered my question. Due to my low rep, I can not up-vote or pick some answer as the right one. You are all good for me :)

Body:
Build a truth table:

p  q    p && q    p || q    !(p && q)    !p || !q    !(p || q)   !p && !q
==========================================================================
0  0    0         0         1            1           1           1
0  1    0         1         1            1           0           0
1  0    0         1         1            1           0           0
1  1    1         1         0            0           0           0

Thus, you see that !(p && q) is equivalent to !p || !q, but not equivalent to !p && !q. You see that !(p && q) and !p || !q are the opposite of p && q.

Note that !(p && q) and !p || !q are equivalent and can be proved by using the De Morgan's laws.


答:
As you can see in this example, I've put ! negation sign in front of parentheses. Is this correct ?

Yes, that is fine.

Do I need to negate every condition itself like this:

```<code>if (!$first && !$second)
</code>```

No, that would actually be wrong.

Or I should use || operator:

```<code>if (!$first || !$second)
</code>```

Yes, that would be correct.

It would also be my personal preference of all the options you propose.

Body:
As you can see in this example, I've put ! negation sign in front of parentheses. Is this correct ?

Yes, that is fine.

Do I need to negate every condition itself like this:

if (!$first && !$second)

No, that would actually be wrong.

Or I should use || operator:

if (!$first || !$second)

Yes, that would be correct.

It would also be my personal preference of all the options you propose.


问:
Blurred line between a framework and an SDK
I have been programming professionally for a couple of decades. Some years ago, the framework word was not so widely used as it is today, but I still believe we've been using "frameworks" for a very long time before they were called that.

For example, the Java SDK has parts that can be considered frameworks; like for example the Collections framework. Also J2EE gives some structure, classes, interfaces and directives for building web solutions. Isn't that a framework? Well, Wikipedia calls it a platform.

Usually throughout the years, one builds up a plethora of interfaces and classes that conform a common practice allowing you to build apps in less time than before by leveraging your previous achievements. Isn't that body of structures, steps, analysis and design products (interfaces to implement and abstract classes to extend) a framework?

Is there a canonical, and quotable, hard line separating what a framework is and what a comprehensive set of APIs or a SDK is?

When was the term framework introduced in computer science?

Note: this other question is about API vs SDK, so it's not a duplicate.

Wikipedia only says this:

"An architecture framework establishes a common practice for creating,
  interpreting, analyzing and using architecture descriptions within a
  particular domain of application or stakeholder community.

答:
There cannot be a canonical definition for these terms, as different people/companies use the terms in different, subjective, ways.

From experience, the following definitions are often used and are likely the nearest one could get to a consensus definition:

Library
A collection of classes/modules/functions with at least some of them being publicly accessible that extend an application.

Framework
A collection of classes/modules/functions that allow an application to be built by extending the framework. JEE is an example of this: your code is under the control of the framework, unlike with a library.

API
An application programming interface is a library that provides access to some other application or piece of hardware.

SDK
A software development kit is a collection of tools (eg compilers, libraries, debuggers, IDEs) for assisting the development of applications against some API using one or more languages.

Having said all that, there are well known examples that break these "rules", eg the ".NET Framework", which is an SDK according to the above definitions.


答:
Yes, it should be fine. By negating the condition in the if, you're only picking up the cases that would have failed before.

Also, !($first && $second) is equivalent to  (!$first || !$second), not (!$first && !$second). (Because DeMorgan's, as other answerers have mentioned).

If your results are confusing you, you could use a truth table to evaluate the expressions and find the one that fits the behavior you're looking for.

Once you have the right expression, you want to make sure you place your parentheses correctly, like ratchet freak mentioned.

These can help get you started:
Truth Tables.
   Truth Table Generator. For the latter, you'll have to convert the operators to the ones they use.


问:
If you can use def to redefine variables how is that considered immutable?
Trying to learn Clojure and you can't help but be told continually how Clojure is all about immutable data. But you can easily redefine a variable by using def right? I get that Clojure developers avoid this but you could avoid changing variables in any language just the same. Can someone explain to me how this is any different, because I think I'm missing that from the tutorials and books I'm reading.

To give an example how is

```<code>a = 1
a = 2
</code>```

in Ruby (or blub, if you prefer) different from

```<code>(def a 1)
(def a 2)
</code>```

in Clojure?

答:
As you already noticed, the fact that mutability is discouraged in Clojure does not mean that it is forbidden and that there are no constructs that support it.
So you are right that using def you can change / mutate a binding in the environment in way similar to what assignment does in other languages (see the Clojure documentation on vars). By changing bindings in the global environment you also change data objects that use these bindings. For example:

```<code>user=> (def x 1)
#'user/x
user=> (defn f [y] (+ x y))
#'user/f
user=> (f 1)
2
user=> (def x 100)
#'user/x
user=> (f 1)
101
</code>```

Notice that after redefining the binding for x, function f has changed as well, because its body uses that binding.

Compare this with languages in which redefining a variable does not delete the old binding but only shadows it,  i.e. it makes it invisible in the scope that comes after the new definition. See what happens if you write the same code in the SML REPL:

```<code>- val x = 1;
val x = 1 : int
- fun f y = x + y;
val f = fn : int -> int
- f 1;
val it = 2 : int
- val x = 100;
val x = 100 : int
- f 1;
val it = 2 : int
</code>```

Notice that after the second definition of x, the function f still uses the binding x = 1 that was in scope when it was defined, i.e. the binding val x = 100 does not overwrite the previous binding val x = 1.

Bottomline: Clojure allows to mutate the global environment and redefine bindings in it. It would be possible to avoid this, as other languages like SML do, but the def construct in Clojure is meant to access and mutate a global environment. In practice, this is very similar to what assignment can do in imperative languages like Java, C++, Python.

Still, Clojure provides lots of constructs and libraries that avoid mutation, and you can come a long way without using it at all. Avoiding mutation is by far the preferred programming style in Clojure.

Body:
As you already noticed, the fact that mutability is discouraged in Clojure does not mean that it is forbidden and that there are no constructs that support it.
So you are right that using def you can change / mutate a binding in the environment in way similar to what assignment does in other languages (see the Clojure documentation on vars). By changing bindings in the global environment you also change data objects that use these bindings. For example:

user=> (def x 1)
#'user/x
user=> (defn f [y] (+ x y))
#'user/f
user=> (f 1)
2
user=> (def x 100)
#'user/x
user=> (f 1)
101

Notice that after redefining the binding for x, function f has changed as well, because its body uses that binding.

Compare this with languages in which redefining a variable does not delete the old binding but only shadows it,  i.e. it makes it invisible in the scope that comes after the new definition. See what happens if you write the same code in the SML REPL:

- val x = 1;
val x = 1 : int
- fun f y = x + y;
val f = fn : int -> int
- f 1;
val it = 2 : int
- val x = 100;
val x = 100 : int
- f 1;
val it = 2 : int

Notice that after the second definition of x, the function f still uses the binding x = 1 that was in scope when it was defined, i.e. the binding val x = 100 does not overwrite the previous binding val x = 1.

Bottomline: Clojure allows to mutate the global environment and redefine bindings in it. It would be possible to avoid this, as other languages like SML do, but the def construct in Clojure is meant to access and mutate a global environment. In practice, this is very similar to what assignment can do in imperative languages like Java, C++, Python.

Still, Clojure provides lots of constructs and libraries that avoid mutation, and you can come a long way without using it at all. Avoiding mutation is by far the preferred programming style in Clojure.


问:
How do I manage quickly changing python modules
I write Python code for scientific computation. As it is research I face among other two problems:

the demands are quickly changing

results need to stay reproducable

Imagine you have a package A that is needed in an old project and then again in a new one. The new project however requires some changes (This would not be a problem if you could keep backwards compatibility. However, I experienced that this is practically impossible in small very specialized modules.). System wide installations would disallow to rerun the old code. So separate installations are required.

Currently, I solve this with git submodules:
Package A is developed in a git repository and included as a submodule in both projects. This way, the code of the projects can always be run and updates of the package can be propagated easily.

However, I ran in a practical problem with python imports.
The folder structure of a package A would look like this:

```<code>A - A - mod.py
 |   |- __init__.py
 |- B
 |- C
</code>```

Where B and C contain packages that are needed by A and the folders are added to the python path in init.py of A. However, this lead to a case where a package was used twice and with different versions:

```<code>A - A - mod.py
 |   |- __init__.py
 |- B - B - mod2.py
 |   |   |- __init__.py
 |   |- C
 |- C
</code>```

I.e. both A and B brought their "own" version of package C. When B adds C to the python path, the folder is ignored, because simply the folder is used, that was added by A. This can be fixed by specifying the correct path when importing. But it gets a bit ugly (see. https://stackoverflow.com/questions/34682638/is-there-a-convenient-way-to-translate-a-from-a-import-b-as-c-to-an-python-imp)

Due to this I started to ask myself if this is the right way to reduce code duplication while assuring a valid code base in a quickly changing environment. Do you see alternatives/better ways?

答:
Here's an option: You can rename the new version of a package and alias back to the old name in modules where you wish to use the new functionality.

When Python upgraded the Unittest package in the standard library for Python 2.7, they made a backport available for Python 2.6 called unittest2 that was in the Python Package Index.

For Python 2.6 users, wanting to use the newer functionality in the newer module, it would be imported like this:

```<code>import unittest2 as unittest
</code>```

and the new features from 2.7 were available in 2.6 as if you were using 2.7., and the old features continued to just work e.g.:

```<code>unittest.main()
</code>```

You are like the Python 2.6 user who wants to use the newer version of the package.

When you upgrade a dependency, you can put a version number on the package name (as they did with unittest2), and then alias it upon import, until such time as you have all your code unittested and migrated to using the new module or you are confident enough to upgrade the core dependency, or (ugh) you could just do this indefinitely. I would hope you don't do this indefinitely, in my mind, it's just a stopgap.

Body:
Here's an option: You can rename the new version of a package and alias back to the old name in modules where you wish to use the new functionality.

When Python upgraded the Unittest package in the standard library for Python 2.7, they made a backport available for Python 2.6 called unittest2 that was in the Python Package Index.

For Python 2.6 users, wanting to use the newer functionality in the newer module, it would be imported like this:

import unittest2 as unittest

and the new features from 2.7 were available in 2.6 as if you were using 2.7., and the old features continued to just work e.g.:

unittest.main()

You are like the Python 2.6 user who wants to use the newer version of the package.

When you upgrade a dependency, you can put a version number on the package name (as they did with unittest2), and then alias it upon import, until such time as you have all your code unittested and migrated to using the new module or you are confident enough to upgrade the core dependency, or (ugh) you could just do this indefinitely. I would hope you don't do this indefinitely, in my mind, it's just a stopgap.


问:
Is it bad practice that a controller calls a repository instead of a service?
Is it bad practice that a controller calls a repository instead of a service?

To explain more:

I figure out that in good design controllers call services and services use repositories.

But sometimes in controller I don't have/need any logic and just need to fetch from the database and pass it to the view.

And I can do it by just calling the repository - no need to call the service. Is this bad practice?

答:
It is not bad practice for a controller to call a repository directly. A "service" is just another tool, so use it where it makes sense.

NikolaiDante commented:

... Pick the right pattern for the right application. What I would say is that you should make your application consistent.

I don't think consistency is the most important aspect. A "service" class is meant to encapsulate some higher level logic so the controller doesn't need to implement it. If there is no "higher level logic" required for a given operation, just go directly to the repository.

To promote good Separate of Concerns and testability, the repository should be a dependency you inject into the service via a constructor:

IFooRepository repository = new FooRepository();
FooService service = new FooService(repository);

service.DoSomething(...);
```

<p>If searching for records in the database needs some sort of parameterized query, a service class might be a good place to take in your view model and build a query that is then executed by the repository.</p>

<p>Similarly, if you have a complex view model for a form, a service class can encapsulate the logic of creating, updating and deleting records by calling methods on your Domain Models/Entities, then persisting them using a repository.</p>

<p>Going the opposite direction, if your controller needs to get a record by its Id, then delegating to a service object for this is like hitting a thumbtack with a sledgehammer -- it's way more than you need.</p>

<p>I have found that the controller is in the best position to handle the transaction, or a Unit Of Work object. The controller or Unit Of Work object would then delegate to service objects for complex operations, or go directly to the repository for simple operations (like finding a record by Id).</p>

<pre class="lang-csharp prettyprint-override"><code>public class ShoppingCartsController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, ShoppingCartForm model)
    {
        // Controller initiates a database session and transaction
        using (IStoreContext store = new StoreContext())
        {
            // Controller goes directly to a repository to find a record by Id
            ShoppingCart cart = store.ShoppingCarts.Find(id);

            // Controller creates the service, and passes the repository and/or
            // the current transaction
            ShoppingCartService service = new ShoppingCartService(store.ShoppingCarts);

            if (cart == null)
                return HttpNotFound();

            if (ModelState.IsValid)
            {
                // Controller delegates to a service object to manipulate the
                // Domain Model (ShoppingCart)
                service.UpdateShoppingCart(model, cart);

                // Controller decides to commit changes
                store.SaveChanges();

                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View(model);
            }
        }
    }
}
</code>```

I think a mix of services and working with repositories directly is perfectly acceptable. You could further encapsulate the transaction in a Unit Of Work object if you felt the need.

The breakdown of responsibilities goes like this:

The controller controls the flow of the application

Returns "404 Not Found" if the shopping cart isn't in the database

Re-renders the form with validation messages if validation fails

Saves the shopping cart if everything checks out

The controller delegates to a service class to execute business logic on your Domain Models (or Entities). Service objects should not implement business logic! They execute business logic.

Controllers may delegate directly to repositories for simple operations

Service objects take data in the view model, and delegate to Domain Models to execute business logic (e.g. the service object calls methods on the Domain Models before calling methods on the repository)

Service objects delegate to repositories for data persistence

Controllers should either:

Manage the lifetime of a transaction, or

Create a Unit Of Work object to manage the lifetime of a transaction

Body:
It is not bad practice for a controller to call a repository directly. A "service" is just another tool, so use it where it makes sense.

NikolaiDante commented:

... Pick the right pattern for the right application. What I would say is that you should make your application consistent.

I don't think consistency is the most important aspect. A "service" class is meant to encapsulate some higher level logic so the controller doesn't need to implement it. If there is no "higher level logic" required for a given operation, just go directly to the repository.

To promote good Separate of Concerns and testability, the repository should be a dependency you inject into the service via a constructor:

IFooRepository repository = new FooRepository();
FooService service = new FooService(repository);

service.DoSomething(...);

If searching for records in the database needs some sort of parameterized query, a service class might be a good place to take in your view model and build a query that is then executed by the repository.

Similarly, if you have a complex view model for a form, a service class can encapsulate the logic of creating, updating and deleting records by calling methods on your Domain Models/Entities, then persisting them using a repository.

Going the opposite direction, if your controller needs to get a record by its Id, then delegating to a service object for this is like hitting a thumbtack with a sledgehammer -- it's way more than you need.

I have found that the controller is in the best position to handle the transaction, or a Unit Of Work object. The controller or Unit Of Work object would then delegate to service objects for complex operations, or go directly to the repository for simple operations (like finding a record by Id).

public class ShoppingCartsController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, ShoppingCartForm model)
    {
        // Controller initiates a database session and transaction
        using (IStoreContext store = new StoreContext())
        {
            // Controller goes directly to a repository to find a record by Id
            ShoppingCart cart = store.ShoppingCarts.Find(id);

            // Controller creates the service, and passes the repository and/or
            // the current transaction
            ShoppingCartService service = new ShoppingCartService(store.ShoppingCarts);

            if (cart == null)
                return HttpNotFound();

            if (ModelState.IsValid)
            {
                // Controller delegates to a service object to manipulate the
                // Domain Model (ShoppingCart)
                service.UpdateShoppingCart(model, cart);

                // Controller decides to commit changes
                store.SaveChanges();

                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View(model);
            }
        }
    }
}

I think a mix of services and working with repositories directly is perfectly acceptable. You could further encapsulate the transaction in a Unit Of Work object if you felt the need.

The breakdown of responsibilities goes like this:

The controller controls the flow of the application

Returns "404 Not Found" if the shopping cart isn't in the database

Re-renders the form with validation messages if validation fails

Saves the shopping cart if everything checks out

The controller delegates to a service class to execute business logic on your Domain Models (or Entities). Service objects should not implement business logic! They execute business logic.

Controllers may delegate directly to repositories for simple operations

Service objects take data in the view model, and delegate to Domain Models to execute business logic (e.g. the service object calls methods on the Domain Models before calling methods on the repository)

Service objects delegate to repositories for data persistence

Controllers should either:

Manage the lifetime of a transaction, or

Create a Unit Of Work object to manage the lifetime of a transaction


问:
Can I make a closed-source implementation from scratch of a GPL-licensed library?
I've found a paper describing a particular algorithm I'd like to use, and published with the paper is a GPL licensed source code for the algorithm. I am wondering if I can re-implement the algorithm from the paper (obviously without using any of the original code), distribute it closed source, and not be in violation of the original GPL license agreement.

As a corollary, what if I make some (minor) modifications to the algorithm along the way?

答:
I am not a lawyer, and this is not legal advice:

In the US as regards to software there are generally two kinds of IP you need to worry about: Patents and Copyrights.

If an algorithm published in an academic paper is patented then you cannot use it -- the ideas and methods themselves are protected intellectual property. You would need to license it from the patent holder.

If it is only that the reference implementation is copyrighted, then if you reimplement the algorithm from scratch without using the original source code, it is then not a derivative work of the copyrighted material.

As I understand, a very safe way to do it is if you give the part of the paper describing the algorithm to your coworker, and she implements it, having never seen the reference implementation. But again, I am not a lawyer.


答:
The fact that the code is GPL licensed affects what you are allowed to do with that code. It does not affect what you are allowed to do with the paper, or what code you are allowed to write yourself.

Unless the paper itself came with some kind of license stating "you may not create closed-source implementations of this algorithm or modified versions thereof", you should be fine.

Of course, if by "reimplementing" you really meant "transcribing the GPL-licensed code token by token", then you'd be creating a derivative work and the GPL restrictions would be in full force. But I assume that's not what you meant.

And this does not exclude the possibility that the algorithm in the paper is patented or copyrighted. You'd definitely need to talk to a lawyer if that happens to be the case.

Title: Can I make a closed-source implementation from scratch of a GPL-licensed library?

Body:
I've found a paper describing a particular algorithm I'd like to use, and published with the paper is a GPL licensed source code for the algorithm. I am wondering if I can re-implement the algorithm from the paper (obviously without using any of the original code), distribute it closed source, and not be in violation of the original GPL license agreement.

As a corollary, what if I make some (minor) modifications to the algorithm along the way?


问:
Circular dependencies: Recursive grammar parser (e.g. json)
(TLDR) To build a parser for a recursive grammar by composition of individual parsers (e.g. with a parser combinator framework), there are often circular dependencies between some of the individual parsers. While circular dependencies are generally a sign of bad design, is this a valid case where the circular dependency is inevitable? If so, which solution would be preferable to deal with the circular dependency? Or are parser combinators just a bad idea altogether? (/TLDR)

There are other questions asking about dependency injection with circular dependencies. Typically, the answer is to change the design to avoid the circularity.

How to solve circular dependency?

How to handle "circular dependency" in dependency injection

Is circular Dependency Injection a good practice?

I have come across a typical case where I encounter circular dependencies: If I want to have different services to inspect a recursive structure.

I have been thinking about other examples, but so far the best I come up with is a parser for a recursive grammar. Let's use json as an example, because it is simple and well-known.

A json "value" can be a string (".."), an object ({..}) or an array ([..]).

A string is simple to parse, and has no further children.

An object is made up of keys and values, and the surrounding object syntax.

An array is made up of values, and the surrounding array syntax.

A "key" within an object is basically the same as a string.

Now I am going to create a number of parser objects:

A value parser, which depends on the other 3 parsers.

An object parser, which depends on string parser and value parser.

An array parser, which depends on value parser.

A string parser.

I want to manage the 4 parsers with a dependency injection container.
Or, even if I don't want a container, we still have to figure out in which order to create the different parsers. There is a chicken-and-egg problem.

There are known solutions to this, which can be observed in existing parser libraries. So far I have mostly seen the "stub" solution.

Avoid the circular dependency..

.. by passing the value parser as an argument to the object and array parsers' parse() method.

This works, but it taints the signature of the parse() method. Imagine we want this to be something like a parser combinator, which can be reused for other grammars. We would want a parser interface that is generic and independent of the specific grammar, so we can't have it require a specific parser to be passed around.

Use a stub.

Instead of requiring each dependency in the constructor, we could use a set() or add() method on one of the parsers. E.g. we first create an empty value parser ("stub"), and then add the object, array and string parsers to it via the add() method.

Use a proxy.

Instead of creating the actual value parser, we create a proxy object, with a reference to the container. Only when the parse() method is called the first time on the proxy value parser, the real value parser is created.

Now this is all fine, and I suppose it is just a matter of taste, which solution I prefer.

But how does this fit with the typical high-horse response that circular dependencies are a sign of bad design? The example seems totally valid, and there is an entire class of problems like this.

答: Don't make 4 parsers; make 1 parser.  You're not parsing 4 different languages; you're parsing 1 language with 4 major grammatical components.  The "circular dependency problem" can be handled quite easily with a bog-standard recursive-descent parser whose ParseObject and ParseValue methods can both call each other.


问:
How to make sure that the destructor cannot throw an exception?
I know that we can specify the compiler that a function is not throwing an exception by using noexcept specifier but noxecept functions can still throw exceptions . So, how to prevent destructor from throwing an exception ?</p>

答:
Just mark it noexcept.

In C++11 and following, your destructor is automatically declared noexcept unless at least one (base- or member-) subobject's destructor can throw, or you explicitly give a different exception-specification.

And if your function is marked non-throwing, it won't throw, ever, whatever you try.

Instead, it will:

If your exception-specification is dynamic (throw()), call std::unexpected().

If your exception-specification is not dynamic, or std::unexpected() throws, call std::terminate() to abort the program.