问:
Using bool/flags to govern C++ program flow
I find myself consistently creating flags within my C++ program, that are later checked to determine if I need to do something, and it honestly feels kind of "hack-y" despite being a simple solution.

For example, Let's say I have a function:

```<code>update_employee_salary(EmployeeList employees_to_update )
</code>```

update_employee_salary:

Connects to the database

Iterates through all employees in the EmployeeList and gets their status (salaried, or hourly) and creates two separate employee list (hourly_emp, salary_emp)

Updates my employee_data in cache

Writes that employee data to the database

If the employee is an executive, I want to generate notices/logs that Executive salaries were updated.

I also want to ensure that if for some reason, after reading from the database, I am unable to write to the database, that I back everything out. For this reason, I don't want to generate the notice until I guarantee it's been written to the database, so I'll create a bool elist_contains_execs flag that is checked after the database has been updated to generate the notice.

I find myself doing things like this for all sorts of situations, and it feels gross every time I do it, but often it seems better than iterating through the list a second time to determine if it contains executives after the database update.

Question: Is using flags in C++ feel hacky to anyone else? Or do we just accept that it's often a simple solution. What are the cons of using flags. For example, can it make code more difficult to maintain.

答:
It sounds like these "flags" of yours are what we would call "global variables", variables declared at the highest possible scope so that they can be read from and written to from anywhere in your program.

The problem with globals is, of course, that they can be read from and written to from anywhere, which effectively means any piece of code that touches a global is impossible to (fully) understand without searching for every other piece of code touching the same global. This is indeed a classic maintenance headache. Globals should always be an option of last resort, used only when you're sure that every alternative would somehow be even worse.

For the specific example you gave, the first alternative that comes to my mind is a simple output parameter:

```<code>bool execUpdated = false;
int rcode = update_employee_salary(employees_to_update, &execUpdated);
if(rcode != 0) {
  // handle the error
} else {
  // handle the success
  if(execUpdated) {
     // show your notification
  }
}
</code>```

Now anyone who sees update_employee_salary will instantly be aware of this special check for executive updates, and it's impossible to "break" this function "from the outside" by having other code that fiddles with the wrong globals at the wrong time.

Body:
It sounds like these "flags" of yours are what we would call "global variables", variables declared at the highest possible scope so that they can be read from and written to from anywhere in your program.

The problem with globals is, of course, that they can be read from and written to from anywhere, which effectively means any piece of code that touches a global is impossible to (fully) understand without searching for every other piece of code touching the same global. This is indeed a classic maintenance headache. Globals should always be an option of last resort, used only when you're sure that every alternative would somehow be even worse.

For the specific example you gave, the first alternative that comes to my mind is a simple output parameter:

bool execUpdated = false;
int rcode = update_employee_salary(employees_to_update, &execUpdated);
if(rcode != 0) {
  // handle the error
} else {
  // handle the success
  if(execUpdated) {
     // show your notification
  }
}

Now anyone who sees update_employee_salary will instantly be aware of this special check for executive updates, and it's impossible to "break" this function "from the outside" by having other code that fiddles with the wrong globals at the wrong time.


问:
What are you telling yourself if you can't understand new concept, paradigm, feature ...?
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?

答:
There are lot of 3-letter techniques, which are big nothings. Some time ago, I was depressed, if I didn't understand a new one at first sight, but now I know, I was just confused, because the new stuff is just too simple and trivial, but I was anticipated something new and vibrant. Okay, it's only 99% of cases, for the rest 1% I'm trying to find a good article of it.

Example: when I was jumped into JS programming, it was complete dark for me, what does a JavaScript framework do. I have had a pre-conception, and it was good, but I needed a confirmation, and I wanted to understand it more deep. I've visited lot of framework's homepage, but the darkness didn't go away. After a week(!) of googling, I felt myself very dumb. I'm an ulrasenior, and I couldn't even found a f. document in a trendy programming topic! Then, I've found DomAssistant, which has excellent documentation. I've felt statisfaction just reading the first sentence.

The idea of DOMAssistant is to provide
  a simpler and more consistent way to
  script against the Document Object
  Model (DOM) in web browsers. The idea
  is that everything starts with the
  element(s) in question, selected
  through id or CSS selectors, and then
  perform various methods on it, such as
  adding or removing classes, events
  etc.

Example code:

$("#container input[type=text]");

$("#navigation a").addEvent("click",
  myFunc);

$("#news-list").load("updated-news.php");

Clear scope, definition 2. Precise examples! 3. On the opening page!!! And the light came to my mind.

So, if you can't understand, maybe only the documentation is poor.

ContentLicense: CC BY-SA 2.5


问:
Methodology for exploring APIs in dynamic languages
As a regular user of Standard ML and, to a lesser extent, Haskell, the following pattern is deeply ingrained into my "instinctive" approach to navigating and learning new APIs:

Understand the types.

Derive and use free theorems.

Hoogle and Djinn are my friends.

Only if and when I'm not getting any more information from 1, 2 and 3; use test cases (either handcrafted or generated by a QuickCheck-like tool).

Obviously, this pattern doesn't carry over to dynamic languages, so I need a different methodology. The Python REPL has the function help(), which provides documentation for a function provided I already know its name. The Lisp REPL is somewhat smarter, and, in addition to the describe function (which is analogous to Python's help()), also provides the apropos function, which lists all functions whose name contains a given string. But, what if I'm confronted with a totally new library, which I must learn starting from the basics? How do I determine what has to be learned first? Even if "start with the types" doesn't work, there must be something else that does - what is it?

答:
Read the documentation. When you have no compiler to do the “understanding” for you, you'll have to put in that effort yourself.

Ideally, a project has various kinds of documentation:

example code snippets

introductions, tutorials, how-tos

reference documentation

I find a bit of example code extremely helpful to get a cursory overview of a module's capabilities. Here is an example from a Perl module I recently looked at:

SYNOPSIS

use Term::ProgressBar;

$progress = Term::ProgressBar->new ({count => $count});
$progress->update ($so_far);
```
</blockquote>

<p>This is not a complete program, but it illustrates the most important facets of its API. Given such a synopsis, I can often make a quick judgement whether that code will be useful for me. If so, I continue reading with overview-level or tutorial-style documentation.</p>

<p>The overview and tutorial will give me a broad overview of the parts of the system, and introduce the most commonly used parts. For small and simple APIs, a tutorial might not even be necessary as you can simply look at the example code and skim the whole reference documentation in a couple of minutes. Once I have an overview, I can often intuit where some functionality I would want to use might be implemented, e.g. which class or which namespace.</p>

<p>When I then try to use that module, the reference documentation becomes more important for me. Ideally, this documentation has an entry for each type/class/function/method/variable/symbol that is part of the API. It should describe its meaning in the context of its system, and clearly describe its type. E.g. a class should describe all its methods, its invariants, its initialization, …. A function or method should describe the meaning of each parameter and the accepted types, what the function will do with that data, what it will return, and whether it will throw an exception. Here is an example from a project I am currently working on:</p>

<blockquote>
  <h1>next_token</h1>

<pre class="lang-perl prettyprint-override"><code>my ($type, $value) = $self->next_token;
</code>```

Retrieves the next token from the input, applying special commands as needed.

This method is the main parsing driver. It implements various special syntax and delegates to command_*() functions when a command is encountered. Note that whitespace and comments are directly written to the currently selected buffer rather than returning them as a token.

Returns a two-value list: $type is the token type ID of the found token. This should be only used for comparisons with the token type constants. To get the name of the token type, use $self->TOKEN_NAMES->{$type}. $value is the arbitrary value of the token, which in general would be a string.

Throws on illegal syntax.

Stability: The interface of this method is not expected to change, though new behaviour might be added in a backwards-compatible manner.

Example:

my ($type, $value) = $self->next_token;
if ($type != $type->IDENT) {
    die "expected IDENT";
}
```
</blockquote>

<p>The types are still there, though they are obscured by the plain-text description. I personally find that satisfactory, but the corresponding type signature for a pure-functional version would be something like</p>

<pre class="lang-hs prettyprint-override"><code>next_token :: ParserState -> Try (ParserState, TokenId, String)
-- where type Try 'a = Either 'a Exception
</code>```

Finally, if the reference documentation is not sufficiently precise, I will look at the source code. Many programmers do not take writing documentation seriously, and will forget to mention basic information, such as what kind of input is accepted, and what will be done on errors.

Obviously, starting with the reference documentation, or starting to use a system without knowing anything about it, will always be confusing. Therefore, built-in help systems such as Python's help(symbol) are not generally sufficient to build an initial understanding of a system. Fortunately, many project host their documentation on their website so that you can comfortably read their overview docs.

ContentLicense: CC BY-SA 3.0

Body:
Read the documentation. When you have no compiler to do the “understanding” for you, you'll have to put in that effort yourself.

Ideally, a project has various kinds of documentation:

example code snippets

introductions, tutorials, how-tos

reference documentation

I find a bit of example code extremely helpful to get a cursory overview of a module's capabilities. Here is an example from a Perl module I recently looked at:

SYNOPSIS

use Term::ProgressBar;

$progress = Term::ProgressBar->new ({count => $count});
$progress->update ($so_far);

This is not a complete program, but it illustrates the most important facets of its API. Given such a synopsis, I can often make a quick judgement whether that code will be useful for me. If so, I continue reading with overview-level or tutorial-style documentation.

The overview and tutorial will give me a broad overview of the parts of the system, and introduce the most commonly used parts. For small and simple APIs, a tutorial might not even be necessary as you can simply look at the example code and skim the whole reference documentation in a couple of minutes. Once I have an overview, I can often intuit where some functionality I would want to use might be implemented, e.g. which class or which namespace.

When I then try to use that module, the reference documentation becomes more important for me. Ideally, this documentation has an entry for each type/class/function/method/variable/symbol that is part of the API. It should describe its meaning in the context of its system, and clearly describe its type. E.g. a class should describe all its methods, its invariants, its initialization, …. A function or method should describe the meaning of each parameter and the accepted types, what the function will do with that data, what it will return, and whether it will throw an exception. Here is an example from a project I am currently working on:

next_token

my ($type, $value) = $self->next_token;

Retrieves the next token from the input, applying special commands as needed.

This method is the main parsing driver. It implements various special syntax and delegates to command_*() functions when a command is encountered. Note that whitespace and comments are directly written to the currently selected buffer rather than returning them as a token.

Returns a two-value list: $type is the token type ID of the found token. This should be only used for comparisons with the token type constants. To get the name of the token type, use $self->TOKEN_NAMES->{$type}. $value is the arbitrary value of the token, which in general would be a string.

Throws on illegal syntax.

Stability: The interface of this method is not expected to change, though new behaviour might be added in a backwards-compatible manner.

Example:

my ($type, $value) = $self->next_token;
if ($type != $type->IDENT) {
    die "expected IDENT";
}

The types are still there, though they are obscured by the plain-text description. I personally find that satisfactory, but the corresponding type signature for a pure-functional version would be something like

next_token :: ParserState -> Try (ParserState, TokenId, String)
-- where type Try 'a = Either 'a Exception

Finally, if the reference documentation is not sufficiently precise, I will look at the source code. Many programmers do not take writing documentation seriously, and will forget to mention basic information, such as what kind of input is accepted, and what will be done on errors.

Obviously, starting with the reference documentation, or starting to use a system without knowing anything about it, will always be confusing. Therefore, built-in help systems such as Python's help(symbol) are not generally sufficient to build an initial understanding of a system. Fortunately, many project host their documentation on their website so that you can comfortably read their overview docs.


问:
Why are C string literals read-only?
What advantage(s) of string literals being read-only justify(-ies/-ied) the:

Yet another way to shoot yourself in the foot

```<code>char *foo = "bar";
foo[0] = 'd'; /* SEGFAULT */
</code>```

Inability to elegantly initialize a read-write array of words in one line:

```<code>char *foo[] = { "bar", "baz", "running out of traditional placeholder names" };
foo[1][2] = 'n'; /* SEGFAULT */
</code>```

Complicating the language itself.

```<code>char *foo = "bar";
char var[] = "baz";
some_func(foo); /* VERY DANGEROUS! */
some_func(var); /* LESS DANGEROUS! */
</code>```

Saving memory?
I've read somewhere (couldn't find the source now) that long time ago, when RAM was scarce, compilers tried to optimize memory usage by merging similar strings.

For example, "more" and "regex" would become "moregex". Is this still true today, in the era of digital blu-ray quality movies? I understand that embedded systems still operate in environment of restricted resources, but still, the amount of memory available has increased dramatically.

Compatibility issues?
I assume that a legacy program that would try to access read-only memory would either crash or continue with undiscovered bug. Thus no legacy program should try to access string literal and therefor allowing to write to string literal would not harm valid, non-hackish, portable legacy programs.

Are there any other reasons? Is my reasoning incorrect? Would it be reasonable to consider a change to read-write string literals in new C standards or at least add an option to compiler? Was this considered before or are my "problems" too minor and insignificant to bother anyone?

答:
Compilers couldn't combine "more" and "regex", because the former has a null byte after the e while the latter has an x, but many compilers would combine string literals which matched perfectly, and some would also match string literals that shared a common tail.  Code which changes a string literal may thus change a different string literal which is used for some entirely different purpose but happens to contain the same characters.

A similar issue would arise in FORTRAN prior to the invention of C.  Arguments were always passed by address rather than by value.  A routine to add two numbers would thus be equivalent to:

```<code>float sum(float *f1, float *f2) { return *f1 + *f2; }
</code>```

In the event that one wanted to pass a constant value (e.g. 4.0) to sum, the compiler would create an anonymous variable and initialize it to 4.0.  If the same value was passed to multiple functions, the compiler would pass the same address to all of them.  As a consequence, if a function which modified one of its parameters was passed a floating-point constant, the value of that constant elsewhere in the program could get changed as a result, thus leading to the saying "Variables won't; constants aren't".

Title: Why are C string literals read-only?

Body:
Compilers couldn't combine "more" and "regex", because the former has a null byte after the e while the latter has an x, but many compilers would combine string literals which matched perfectly, and some would also match string literals that shared a common tail.  Code which changes a string literal may thus change a different string literal which is used for some entirely different purpose but happens to contain the same characters.

A similar issue would arise in FORTRAN prior to the invention of C.  Arguments were always passed by address rather than by value.  A routine to add two numbers would thus be equivalent to:

float sum(float *f1, float *f2) { return *f1 + *f2; }

In the event that one wanted to pass a constant value (e.g. 4.0) to sum, the compiler would create an anonymous variable and initialize it to 4.0.  If the same value was passed to multiple functions, the compiler would pass the same address to all of them.  As a consequence, if a function which modified one of its parameters was passed a floating-point constant, the value of that constant elsewhere in the program could get changed as a result, thus leading to the saying "Variables won't; constants aren't".


问:
What's the use of .Any() in a C# List<>?
I've been discussing this with colleagues, and we couldn't figure out what the use is of .Any for any given List<>, in C#.

You can check the validity of an element in the array like the following statement:

```<code>if (MyList.Any()){ ...}  //Returns true or false
</code>```

Which is exactly the same as

```<code>if (MyList.Count() != 0) { ... }
</code>```

and is much more common, readable and clear about the intent of the if statement.

In the end, we were stuck with this thought:

.Any() can be used, will work just as well, but is less clear about
  the intent of the programmer, and it that case it should not be used.

But we feel like this can't be right; we must be missing something.

Are we?

答:
Maybe it's just the word? Any is an adjective, not really saying anything. Coming from Java, I'd call it isNonEmpty which contains a verb. A SQL guy might prefer EXISTS. But maybe Any fits best in the C# system.

Whatever the word choice, once you get used to it, it must be way clearer. Would you ask "Is there more than zero beer bottles left". Would you expect one or more persons starting to count them before they answer "No, there isn't any"?


问:
How to abstract from a display?
I'm building an embedded text editor consisting of a keyboard, an LCD display and a PIC32 microcontroller, to be programmed in C. The application should look, for example, like the GNU nano editor. The display is 40x16 characters big.

I'm currently wondering what would be a good abstraction from the display. We could conceptualise a simple terminal as follows:

```<code>typedef struct {
    char* content;              // Current and past content
    void (*update)(Terminal);   // Update function
} Terminal;
void append(Terminal, char*);   // Append to content & execute update function
void discard(Terminal, int);    // Discard last n characters & execute update f.
</code>```

By adding a function pointer to the Terminal type, we basically have a model and a view. The Terminal can be controlled by the append() and discard() functions. With this Terminal we could make a simple terminal with stdin and stdout.

However, that's not enough for a nano-like editor, where text can be inserted and removed anywhere on the screen, not just at the end of the current data.

I have now made up the following type:

```<code>typedef struct {
    unsigned short rows, columns,     // Screen size
            first_visible_row, first_visible_column,  // Left-top coordinates
            cursor_x, cursor_y;       // Cursor coordinates
    char* content;                    // Current and off-screen content
    void (*update)(Screen);           // Update function
} Screen;
</code>```

This Screen holds off-screen content as well, and its visible section is determined by its left-top coordinates. This makes scrolling easier. But, functions to write to this screen at some position would be complicated, because there is no direct relationship between a position in content and its coordinates on the actual display.

An easier to work with type would hold an array of rows char arrays, for different lines on the screen. Then, content would be an array of char arrays, i.e. char** content.

Basically, I'm asking if there are problems with my suggested approach and if there is an easier approach.

To sum up, here are some of the requirements for the screen:

Should be easy to scroll in

It should be possible to add and remove text at any point on the screen

答:
It's a good idea to have a content represented as char*, because that's what it is conceptually.

char** is bad as a model of content, because it's tied to a fixed screen size and line lenght. So it only makes sense as a 'viewmodel' of the screen.

As for the relationships between cursor coordinates and the position within content array, I see two options which should both work fine:

have a function that calculates an index into content based on current cursor coordinates and screen position (don't see why it would be too difficult)

maintain a two-dimensional array of indexes into content, where each element corresponds to one possible cursor position; it will need to be updated on every update of the screen

Title: How to abstract from a display?


问:
Algorithm for determining transactions among weekly data series?
I'm trying to develop a small reporting tool (with sqlite backend). I can best describe this tool as a "transaction" ledger. What I'm trying to do is keep track of "transactions" from weekly data extract:

"new" (or add) - resource is new to my app since my app may not have tracked this resource before as it hasn't been seen via extracts.

"update" (or hit) - there is a recent use of that resource, update retention period by another week.

"delete" (or drop) - this item saw no use since last report (optional, but would be nice to have for graphing week-to-week changes in demand for resources).

All I've got is a weekly data extract (pipe-delimited flat file) coming from a legacy archiving/record-management system that I have no control over.

Each line can be distilled to basically this:

resource_id | resource info | customer_id | customer_info

Sample data:

```<code>10| Title X       | 1 | Bob
11| Another title | 1 | Bob
10| Title X       | 2 | Alice
</code>```

The goal is make it easy to report on resources that haven't seen use for X-months (based on last hit). There is a retention period where resources are kept around for ease of access if they're popular. A resource that hasn't seen use for 18 months is marked for long-term archival elsewhere.

This must be a common problem. Wondering if there a general-purpose algorithm to determine what's new/same/removed between data sets (db vs. latest extract)?

答:
Well your answer is... Yes. There is a simple algorithm you can implement that doesn't require any of that other stuff. It's a net present value algorithm. It's easy to implement and all it requires on the DB end is that you date stamp the weekly data and write one simple query and one small recursive function or for loop, or you could do one of those other solutions.

NPV = PV-(PV(CP/T) or the New Present Value equals the Present Value times the Current Period (months since last entry) divided by the Term (e.g. 18 months) when the resource value falls to 0 it's net present value is expended.

If you give me a lang you want it in I'll post the code here in an edit


问:
Best way to handle nulls in Java?
I have some code that is failing because of NullPointerException.  A method is being called on the object where the object does not exist.

However, this led me to think about the best way to fix this.   Do I always code defensively for nulls so that I future proof code for null pointer exceptions, or should I fix the cause of the null so that it won't occur downstream.

What are your thoughts?

答:
Do not use the Optional type, unless it truly is optional, often the exit is better handled as an exception, unless you were truly were expecting null as an option, and not because you regularly write buggy code.

The problem is not null as a type it has its uses, as Google's article points out. The problem is that nulls should be checked and handled, often they can be exited gracefully.

There are a number of null cases that represent invalid conditions in areas outside the routine operation of the program (invalid user input, database issues, network failure, missing files, corrupt data), which is what checked exceptions are for, handling them, even if it's just to log it.

Exception handling is permitted different operational priorities and privileges in the JVM as opposed to a type, like Optional, that makes sense for the exceptional nature of their occurrence, including early support for prioritized lazy loading of the handler into memory, since you don't need it hanging around all the time.

You don't need to write null handlers all over the place, only where they are likely to occur, anywhere you are potentially accessing unreliable data service, and since most of these fall into few general patterns that can easily be abstracted you really only need a handler call, except in rare cases.

So I guess my answer would be wrap it in a checked exception and handle it, or fix the unreliable code if it's within your capability.

Title: Best way to handle nulls in Java?


问:
Refactoring numerical code for TDD and encapsulation
I am coming to terms with TDD, and the fact that I need to re-factor some code that I'm (re)writing. I am having a problem that I think is a classic conflict---TDD vs. encapsulation of private methods/data---and I need advice on how to structure my code properly so that everything is testable through its public interface.

I am writing a class which does some heavy computation for a performance critical code. It contains ~10 std::valarrays which, in typical use, may have between 50 and 200 floats. All of the methods pound on some or all of those arrays---usually by zipping through them in loops. Additionally, there is a fist full of constants common to all of the methods.

Because these methods all use the same data, they really do belong in a class together. (In my first iteration of the code (in C) my function call signatures were horrifying but repetitive.)

The class really only needs one or two public methods which returns a comparatively small and simple array of POD structures. So, the input is simple, the output is simple but there is HEAVY computation on a lot of self generated data in between.

A simplified illustration might look something like this:

```<code>class HighPerformingDoohicky(){
 private:
  std::valarray a, b, c,
   ...
  float some_constants // all methods depend on these.

  void method1() // pounds on a, b, c.
  void method2() // pounds on c, d, e.
  void method3() // pounds on all of them

 public:
  HighPerformingDoohicky(a_few_numbers) some_constants{a_few_numbers} : {}
  std::valarray<float> method4() // loop/iterate calls to methods 1, 2 and 3 to produce output
}
</code>```

So there is a *LOT* of private data so any one datum is only a small part of the generated output. Testing the output methods really doesn't help me develop the numerics and it would be easy for subtle problems to go unnoticed in the public interface.

I am happy to restructure (friend classes maybe?) and I am not fixated on the solution having a particular form as long as it is easy to read, is testable, is correct and is efficient.

Addendum: In case someone finds it illuminating to know more specifically about the calculations here is a summary. Six of the variables are the state space for a dynamical system. One of the methods is an Euler integrator that use the equations of motion (and control) to project a state space trajectory based on initial conditions (input). Another method will compute a set of Lagrange multipliers based on that trajectory. Another method will compute a gradient vector that depends on the trajectory and the Lagrange multipliers. Method 3 will repeatedly call those functions to solve an optimization problem. All of these things (including the gradient) are valarray which are N elements long, with N somewhere between 20 and 200 in normal operation.

答:
Six of the variables are the state space for a dynamical system. One of the methods is an Euler integrator that use the equations of motion (and control) to project a state space trajectory based on initial conditions (input). Another method will compute a set of Lagrange multipliers based on that trajectory. Another method will compute a gradient vector that depends on the trajectory and the Lagrange multipliers. Method 3 will repeatedly call those functions to solve an optimization problem. All of these things (including the gradient) are valarray which are N elements long, with N somewhere between 20 and 200 in normal operation.

I do not know the internals of your class, but this description sounds a lot like different responsibilites, which could be separated to different classes, each one with its own public interface. The fact some of them operate on the same data does not make it mandatory to put all of them into the same class - noone forbids you to design classes taking a reference to the data of another class if that helps you to get things in a better shape. The key to make this work is as always to get the different abstractions right (and in C++: by having a clear plan for ownership of the data).

However, if you really think you are not able to design this program in more separated fashion, may be for the sake of performance, then it may be a tradeoff between different design goals - performance vs. the "do not test private functions" mantra. Actually, I would not hesitate to question the latter in such a situation a bit. Sometimes adding "maintenance hatches" to your classes can help - public helper methods, which will allow you to access some internals/inner workings only for testing purposes.


问:
Are there any arguments that can make a contractor reconsider working on fixed price?
I've been working for a contractor who brings in some good projects, but they are all fixed-price and often fixed-time.

As a result he always has me making a quote over loose requirements, which never fails to bring a lot of tension due to feature creep.

He claims he'd never get a contract if he couldn't agree on a price with his clients first, but as far as I'm concerned I don't wanna go through another project under these terms.

Is there any argument I could make to have him pay me by the hour, or should I just suck less at estimating ?

答:
Assuming you're the full time employee of this contractor. Show him how much money he's losing by not accounting for scope-creep.

If the contractor is sub-contracting you, tell him you can only work by the hour, and be honest with why. (That is, the requirements are not well defined, you might not be paid for all of the work you might end up doing.  Also you might save the contractor money if it goes faster than expected.)


问:
How to properly manage "business" constants with AngularJS?
I'm working with AngularJS on a browser game and I have a bunch of "business" constants.

These constants will be often updated during game testing (game balancing) and are used by different modules/features.

I'm currently managing them in a single file like that:

constants.js

```<code>var gameConstants =  {
    BASE_COST: 100,
    MULTIPLIER_COST: 1.07
};
</code>```

myFactory.js

```<code>app.factory('MyFactory', function () {
    return {
         getRealCost: function() {
              return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
         }
    }
});
</code>```

But I'm thinking about a service provider for game constants.
Something like:

constantServices.js

```<code>app.factory('ConstantServices', function () {
    var baseCost: 100,            //Should I use UPPER_SNAKECASE here too?
        multiplierCost: 1.07

    return {
         getCost: function() {
              return baseCost;
         }
         getMultiplierCost: function() {
              return multiplierCost;
         }
    }
});
</code>```

myFactory.js

```<code>app.factory('MyFactory', ['ConstantServices' function (ConstantServices) {
    return {
         getRealCost: function() {
              return ConstantServices.getCost() * ConstantServices.getMultiplierCost();
         }
    }
});
</code>```

What do you think about it? Is it a good idea to create a service provider for constants only (i. e. call a service without any logic)? Do you think about a better way to manage these constants?

答:
Just use the constant service from AngularJS:

```<code>app.constant('gameConstants, [
  { BASE_COST: 100 },
  { MULTIPLIER_COST: 1.07 }
]);
</code>```

And then inject the gameConstants wherever you need them:

```<code>app.factory('MyFactory', ['gameConstants', function (gameConstants) {
    return {
         getRealCost: function() {
              return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
         }
    }
}]);
</code>```

Body:
Just use the constant service from AngularJS:

app.constant('gameConstants, [
  { BASE_COST: 100 },
  { MULTIPLIER_COST: 1.07 }
]);

And then inject the gameConstants wherever you need them:

app.factory('MyFactory', ['gameConstants', function (gameConstants) {
    return {
         getRealCost: function() {
              return gameConstants.BASE_COST * gameConstants.MULTIPLIER_COST;
         }
    }
}]);


答:
Alternative idea:

Parse your list of transactions into some kind of data structure, such as an an array.  (In C++, think Vector, and in Java, ArrayList.)

Perform a query on your SQL backend such as SELECT DISTINCT customer_id FROM Transactions ORDER BY customer_id and pack the sorted distinct customer IDs into a set, old.  If you do the exact same thing with a WHERE clause separating the old and new transactions, you can skip step 3.

Get the unique customer IDs from the new updates into a separate data structure, in sorted order.  There are a couple of data structures you could use to get is into a data structure, new.  Insertion sort into a double-linked list is very simple, but using an intermediate hashtable would run in close to linear time, or if you’re sorting the original array anyway, getting a set out of that is easy.

Take the set difference new - old using your favorite language’s   standard library.  Your favorite language does have this algorithm in its standard library?

The other things you want to do are definitely SQL queries after you’ve updated your transaction database.

Note on step 3: Consider the nature of your data.  Suppose that your text file lists orders chronologically, and in a typical week, there are a lot of first-time customers who are given a new customer_id in ascending order.  Suppose that most other orders are from a small number of loyal repeat customers, with lower customer_id.  Then your inputs are already mostly-sorted.  An insertion sort where you try to insert low customer_id at the front of a double-linked list and high customer_id at the back would, in that situation, perform well in practice.

Title: Algorithm for determining transactions among weekly data series?

Body:
I'm trying to develop a small reporting tool (with sqlite backend). I can best describe this tool as a "transaction" ledger. What I'm trying to do is keep track of "transactions" from weekly data extract:

"new" (or add) - resource is new to my app since my app may not have tracked this resource before as it hasn't been seen via extracts.

"update" (or hit) - there is a recent use of that resource, update retention period by another week.

"delete" (or drop) - this item saw no use since last report (optional, but would be nice to have for graphing week-to-week changes in demand for resources).

All I've got is a weekly data extract (pipe-delimited flat file) coming from a legacy archiving/record-management system that I have no control over.

Each line can be distilled to basically this:

resource_id | resource info | customer_id | customer_info

Sample data:

```<code>10| Title X       | 1 | Bob
11| Another title | 1 | Bob
10| Title X       | 2 | Alice
</code>```

The goal is make it easy to report on resources that haven't seen use for X-months (based on last hit). There is a retention period where resources are kept around for ease of access if they're popular. A resource that hasn't seen use for 18 months is marked for long-term archival elsewhere.

This must be a common problem. Wondering if there a general-purpose algorithm to determine what's new/same/removed between data sets (db vs. latest extract)?


问:
IoC invalidation
I have a bunch of services that get registered as singletons by my IoC container on startup, all of these services have a constructor which takes in a connection string which is used by the underlying storage provider.

This has been fine given the connection string was static and never changed during a session, however, I now need to implement the ability for users to change the connection string at runtime (e.g. they can choose to point to a local/cloud DB).

Ultimately, what this means is I need to somehow invalidate all my services in the IoC container and as far as I could see my chosen IoC container doesn't appear to provide a means of doing this, so it's down to me to come up with a practical solution.

Now there are many ways I could do this but I am looking for feedback, suggestions (from experience if possible) on what would be considered the optimal solution. Here is a simplified service

```<code>public class Service
{
    public Service (string connectionString)
    {
        this.ConnectionString = connectionString;
    }

    // marked as protected as derived services may need access to them
    protected string ConnectionString { get; set; }
    ...
}
</code>```

And here is how it is currently registered

```<code>public static void StartUp(IAppSettings appSettings)
{
    container.Register<IService, Service> (new Service(appSettings.ConnectionString));
    ...
}
</code>```

The simplest solution, which I personally don't like, is simply to have all my services take a reference to IAppSettings rather than ConnectionString and use a read-only property e.g.

```<code>protected string ConnectionString { get { return appSettings.ConnectionString; } }
</code>```

However, given all that the services need from IAppSettings is the connection string this just seems wrong from a modelling point of view. Keeping with this approach, but improving on it slightly would be to introduce a new interface which exposes only the information needed from IAppSettings e.g.

```<code>public interface IDbSettings
{
    string ConnectionString { get; set; }
}

public class AppSettings : IAppSettings, IDbSettings
{
    ...
}
...
container.Register<IService, Service> (new Service(appSettings as IDbSettings));
</code>```

I say slightly because ultimately I still have the same problem (services are still referencing a large object for one simple property).

The type of approach I would like, and what I feel would be best, would be to extend the current IoC container to introduce an Invalidate method whereby I can simply set the internal instance to null and have it re-initialized when resolved. I see this looking something like

```<code>appSettings.ConnectionString = "database=db1";
container.Register<IService, Service>(new Service(appSettings.ConnectionString));
...
var svc = container.Resolve<IService>(); // connects to db1
appSettings.ConnectionString = "database=db2";
...
var svc = container.Resolve<IService>(); // still connects to db1
container.Invalidate<IService>();
var svc = container.Resolve<IService>(); // connects to db2
</code>```

For me this gives all round benefits

You control exactly when you want the changes to take affect

It keeps with the Singleton pattern

It means the only thing that changes is the IoC container

I would be interested in everyones thoughts, critiques etc.

答:
I am not familiar with TinyIoC, but assuming you are caching or you can cache registered services in some kind of container, such as map/dictionary, you could set the key as the hash from the connectionString and the value as the concrete Service.

You could have a Service getService(string hash) method which would return the service based on the hash passed.

```<code>Service connection = IoCContrainer.getService(appSettings.ConnectionString.hashCode());
// use the connection
</code>```

Title: IoC invalidation

Body:
I am not familiar with TinyIoC, but assuming you are caching or you can cache registered services in some kind of container, such as map/dictionary, you could set the key as the hash from the connectionString and the value as the concrete Service.

You could have a Service getService(string hash) method which would return the service based on the hash passed.

Service connection = IoCContrainer.getService(appSettings.ConnectionString.hashCode());
// use the connection


答:
When working alone you really can't win in a fixed-price + fixed-time project. You have no ability to increase capacity apart from working late nights and weekends.

In my experience "loose requirements" based estimates only become larger and larger when you add detail, never smaller. Keep asking for details until you feel safe.

Discussions about high level requirements and what's included and what's not are easily won when push comes to shove, client is usually drawing the short end of the stick here. Your business relationship may suffer though.

Sad thing about this construct is that everything you build tends to be the lowest possible quality needed to satisfy the high level requirements.

(yeah so you can logon with a password, you never said you wanted a separate logon for each user...)

With fixed-price I would just waterfall, big-design-upfront, the thing. Have the contractor sign based on a full detail stack of papers, then build.

To improve your estimates you could just double or triple whatever you think you need, this might be more realistic but may price you out of the market.

Scrum's velocity tracking may prove to be useful to get a grip on your own estimates and how they pan out compared to actual time needed.

Unless you want to speculate on the fixed-price looking for a healthy profit I would really prefer to just get payed by the hour. This keeps risk at the contractors side.

Estimates are a guess not a promise.

Title: Are there any arguments that can make a contractor reconsider working on fixed price?

Body:
I've been working for a contractor who brings in some good projects, but they are all fixed-price and often fixed-time.

As a result he always has me making a quote over loose requirements, which never fails to bring a lot of tension due to feature creep.

He claims he'd never get a contract if he couldn't agree on a price with his clients first, but as far as I'm concerned I don't wanna go through another project under these terms.

Is there any argument I could make to have him pay me by the hour, or should I just suck less at estimating ?


答:
A surprising question - I find the intent of list.Any() to be much clearer than the intent of list.Count()!=0.

Intent means: If you read someones code (and you didn't write it yourself), is it completely obvious what the programmer wants to achieve and why it written written like it is? If a common problem is solved in a needlessly complex way, you immediately gets suspicious and wonder why the developer didn't use the simple way. You look through the code and try to see if you have missed something. You are afraid to change the code because you worry there is some side effect you are missing and changing it may cause unexpected problems.

The intent of using the Any() method is completely clear - you want to know if there are any elements in the list or not.

The intent of the expression Count()!=0 on the other hand is not obvious for the reader. It is of course not hard to see that the expression tells you if the list is empty or not. The questions arises because you write it this particular way rather than using the standard method. Why do you use Count() explicitly? If you really just need to know if there are any elements in a list, why do you want to count the whole list first? As soon as you reach 1 you already have have your answer. If the source was an iterator over a large (perhaps infinite) collection or is translated to sql, it could make a big difference performance wise. So maybe the explicit use of Count() is to force a deferred query to execute or to traverse an iterator?

But the source is actually a List<T> where Count() is O(1) and has no side effects. But if the code relies of this property of List<T>, then why not use the Count-property which more clearly indicate that you expect an O(1) operation with no side effects?

As it is written, list.Count()!=0 does exactly the same as list.Any() except it is needlessly more complex and the intent is unclear.

Title: What's the use of .Any() in a C# List<>?

Body:
I've been discussing this with colleagues, and we couldn't figure out what the use is of .Any for any given List<>, in C#.

You can check the validity of an element in the array like the following statement:

```<code>if (MyList.Any()){ ...}  //Returns true or false
</code>```

Which is exactly the same as

```<code>if (MyList.Count() != 0) { ... }
</code>```

and is much more common, readable and clear about the intent of the if statement.

In the end, we were stuck with this thought:

.Any() can be used, will work just as well, but is less clear about
  the intent of the programmer, and it that case it should not be used.

But we feel like this can't be right; we must be missing something.

Are we?


问:
Better application design - where to place interfaces
Where to place interfaces in a typical multi-layered app with DataAccess, BusinessLogic and an Endpoint modules? I propose 2 options

In both cases there's only dependency from abstractions, but in first one we place interfaces in the same module with implementation, in second - we move all interfaces in the separate module.

I have these pros and cons:

First approach

more stupid-simple (why shall we need this extra module? it's too complicated etc)

Second approach

more TDD-friendly as it allows us completely to separate from the
module that implements contract when we mock it.

more DI friendly - we can succeed in complete isolation of modules.

Yet the second option leads to greater overhead and requires more effort while developing.

So, my question is - what approach is generally better (or are there any other, more appropriate options)?

答:
These days, I have been using the following structure and it's worked pretty well for me so far:

It shows a fictional client/server system with 3 application features or modules called Foo, Bar and Baz. Users can access the system via a command line, UI or web based interface.

This sort of structure is very TDD and DI friendly in my experience.

```<code>Features

    Assembly: Contoso.Features.FooFeature
        Folder: Contracts                               contains interfaces unique to "FooFeature"; is available at both client and server ends
        Folder: Models                                  contains models unique to "FooFeature"; is available at both client and server ends
        Folder: Services                                contains services unique to "FooFeature"; is available at both client and server ends
        References:
            * Contoso
    Assembly: Contoso.Features.FooFeature.Services      contains services unique to "FooFeature"; is available only at server end
        References:
            * Contoso
            * Contoso.Features.FooFeature
    Assembly: Contoso.Features.FooFeature.Tests
        Folder: Models                                  contains tests for models unique to "FooFeature"
        Folder: Services                                contains tests for services unique to "FooFeature"
        References:
            * Contoso
            * Contoso.Features.FooFeature
            * Contoso.Features.FooFeature.Services

    Assembly: Contoso.Features.BarFeature
        Folder: Contracts                               contains interfaces unique to "BarFeature"; is available at both client and server ends
        Folder: Models                                  contains models unique to "BarFeature"; is available at both client and server ends
        Folder: Services                                contains services unique to "BarFeature"; is available at both client and server ends
        References:
            * Contoso
    Assembly: Contoso.Features.BarFeature.Services      contains services unique to "BarFeature"; is available only at server end
        References:
            * Contoso
            * Contoso.Features.BarFeature
    Assembly: Contoso.Features.BarFeature.Tests
        Folder: Models                                  contains tests for models unique to "BarFeature"
        Folder: Services                                contains tests for services unique to "BarFeature"
        References:
            * Contoso
            * Contoso.Features.BarFeature
            * Contoso.Features.BarFeature.Services

    Assembly: Contoso.Features.BazFeature
        Folder: Contracts                               contains interfaces unique to "BazFeature"; is available at both client and server ends
        Folder: Models                                  contains models unique to "BazFeature"; is available at both client and server ends
        Folder: Services                                contains services unique to "BazFeature"; is available at both client and server ends
        References:
            * Contoso
    Assembly: Contoso.Features.BazFeature.Services      contains services unique to "BazFeature"; is available only at server end
        References:
            * Contoso
            * Contoso.Features.BazFeature
    Assembly: Contoso.Features.BazFeature.Tests
        Folder: Models                                  contains tests for models unique to "BazFeature"
        Folder: Services                                contains tests for services unique to "BazFeature"
        References:
            * Contoso
            * Contoso.Features.BazFeature
            * Contoso.Features.BazFeature.Services

Apps

    Clients
        Assembly: Contoso.CmdApp                        is the command line application client
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.BarFeature
                * Contoso.Features.BazFeature
        Assembly: Contoso.WinApp                        is the Windows application client
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.BarFeature
                * Contoso.Features.BazFeature
        Assembly: Contoso.WebApp                        is the Web application client
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.BarFeature
                * Contoso.Features.BazFeature

    Servers
        Assembly: Contoso.WebSvcApp                     is the Web application server; exposes services via REST or WCF, etc.
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.FooFeature.Services
                * Contoso.Features.BarFeature
                * Contoso.Features.BarFeature.Services
                * Contoso.Features.BazFeature
                * Contoso.Features.BazFeature.Services

Core
    Assembly: Contoso
        Folder: Contracts                               contains interfaces common to the entire system
        Folder: Models                                  contains models common to the entire system
        Folder: Services                                contains services common to the entire system
        References:
            * None
    Assembly: Contoso.Tests
        Folder: Models                                  contains tests for models common to the entire system
        Folder: Services                                contains tests for services common to the entire system
        References:
            * Contoso
</code>```

Body:
These days, I have been using the following structure and it's worked pretty well for me so far:

It shows a fictional client/server system with 3 application features or modules called Foo, Bar and Baz. Users can access the system via a command line, UI or web based interface.

This sort of structure is very TDD and DI friendly in my experience.

Features

    Assembly: Contoso.Features.FooFeature
        Folder: Contracts                               contains interfaces unique to "FooFeature"; is available at both client and server ends
        Folder: Models                                  contains models unique to "FooFeature"; is available at both client and server ends
        Folder: Services                                contains services unique to "FooFeature"; is available at both client and server ends
        References:
            * Contoso
    Assembly: Contoso.Features.FooFeature.Services      contains services unique to "FooFeature"; is available only at server end
        References:
            * Contoso
            * Contoso.Features.FooFeature
    Assembly: Contoso.Features.FooFeature.Tests
        Folder: Models                                  contains tests for models unique to "FooFeature"
        Folder: Services                                contains tests for services unique to "FooFeature"
        References:
            * Contoso
            * Contoso.Features.FooFeature
            * Contoso.Features.FooFeature.Services

    Assembly: Contoso.Features.BarFeature
        Folder: Contracts                               contains interfaces unique to "BarFeature"; is available at both client and server ends
        Folder: Models                                  contains models unique to "BarFeature"; is available at both client and server ends
        Folder: Services                                contains services unique to "BarFeature"; is available at both client and server ends
        References:
            * Contoso
    Assembly: Contoso.Features.BarFeature.Services      contains services unique to "BarFeature"; is available only at server end
        References:
            * Contoso
            * Contoso.Features.BarFeature
    Assembly: Contoso.Features.BarFeature.Tests
        Folder: Models                                  contains tests for models unique to "BarFeature"
        Folder: Services                                contains tests for services unique to "BarFeature"
        References:
            * Contoso
            * Contoso.Features.BarFeature
            * Contoso.Features.BarFeature.Services

    Assembly: Contoso.Features.BazFeature
        Folder: Contracts                               contains interfaces unique to "BazFeature"; is available at both client and server ends
        Folder: Models                                  contains models unique to "BazFeature"; is available at both client and server ends
        Folder: Services                                contains services unique to "BazFeature"; is available at both client and server ends
        References:
            * Contoso
    Assembly: Contoso.Features.BazFeature.Services      contains services unique to "BazFeature"; is available only at server end
        References:
            * Contoso
            * Contoso.Features.BazFeature
    Assembly: Contoso.Features.BazFeature.Tests
        Folder: Models                                  contains tests for models unique to "BazFeature"
        Folder: Services                                contains tests for services unique to "BazFeature"
        References:
            * Contoso
            * Contoso.Features.BazFeature
            * Contoso.Features.BazFeature.Services

Apps

    Clients
        Assembly: Contoso.CmdApp                        is the command line application client
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.BarFeature
                * Contoso.Features.BazFeature
        Assembly: Contoso.WinApp                        is the Windows application client
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.BarFeature
                * Contoso.Features.BazFeature
        Assembly: Contoso.WebApp                        is the Web application client
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.BarFeature
                * Contoso.Features.BazFeature

    Servers
        Assembly: Contoso.WebSvcApp                     is the Web application server; exposes services via REST or WCF, etc.
            References:
                * Contoso
                * Contoso.Features.FooFeature
                * Contoso.Features.FooFeature.Services
                * Contoso.Features.BarFeature
                * Contoso.Features.BarFeature.Services
                * Contoso.Features.BazFeature
                * Contoso.Features.BazFeature.Services

Core
    Assembly: Contoso
        Folder: Contracts                               contains interfaces common to the entire system
        Folder: Models                                  contains models common to the entire system
        Folder: Services                                contains services common to the entire system
        References:
            * None
    Assembly: Contoso.Tests
        Folder: Models                                  contains tests for models common to the entire system
        Folder: Services                                contains tests for services common to the entire system
        References:
            * Contoso


问:
Are debugging skills important to become a good programmer?
Along with the other qualities should a programmer need good debugging skills? If I have an applicant who was not able to find the error in the given program, but was able to solve all puzzles and programs, should I consider him for the job? </p>

<p>EDIT :- The puzzles are normal red,blue and red-blue balls like. The programs are like  finding continuous k zeros in an array. The debugging program is something which fails because of condition which should be >=, but instead is >. Everything is on paper. </p>

答: I have such coding style, which requires miminal debugging. When I'm finished with 3 lines of code, I run it, and test it, often printing out a couple of variables. In the cases, when I got unwanted result or behavior, I put many dumps in my code - instead of debugging. I use real debugger very rare. Strange, but true.</p>


问:
Domino Solitaire Algorithm
Problem Statement -

Given a 2xN grid of numbers, the task is to find the most profitable tiling combination (each tile covers 2x1 cells; vertically or horizontally) covering all tiles.

I thought of approaching it in the greedy way, enqueuing the max possible for any cell, but it has a fallback that a low-profit choice at i, could yield a greater profit at i+n tiles.

So what should be the approach?

EDIT - Test Data Range - N<=105

Source - INOI 2008 Q Paper

UPDATE -
Working out the plausibility of a Dynamic programming Approach.

UPDATE 2 -
Worked out an answer using DP.

答:
Here's C++ implementation in O(n) :

Using dynamic programming, we are building from the bottom-up, the best solution for each and every column.

Base cases are column 0 and 1 :

Best[0] => The score for mini tiles of column 0

Best[1] => The maximum out of 2 possible solutions set!
(1. Row wise pairing and
 2. column wise pairing)

Otherwise :

Best[n] => The maximum out of 2 possible solutions set again
(1. The sum of new column and the older best solution B[n-1]
2. The sum of older best solution B[n-2] and the new 2x2 tile square formed)

```<code>#include<iostream>
using namespace std;
int abs(int n) { if(n < 0) return -1*n ; else return n; }

int main()
{
    int n, A[100001][2], B[100001], i, j;
    cin>>n;
    for(i=0;i<2;i++)
    {
        for(j=0;j<n;j++)
            cin>>A[j][i];
    }

    B[0] = abs(A[0][0] - A[0][1]);
    B[1] = max( B[0] + abs(A[1][0]-A[1][1]) , abs(A[1][0]-A[0][0])+abs(A[1][1]-A[0][1]) );
    for(i=2;i<n;i++)
        B[i] = max( B[i-1] + abs(A[i][0]-A[i][1]) , B[i-2] + abs(A[i][0]-A[i-1][0]) + abs(A[i][1]-A[i-1][1]) );

    cout<<B[n-1]<<endl;
    return 0;
}
</code>```

Title: Domino Solitaire Algorithm

Body:
Here's C++ implementation in O(n) :

Using dynamic programming, we are building from the bottom-up, the best solution for each and every column.

Base cases are column 0 and 1 :

Best[0] => The score for mini tiles of column 0

Best[1] => The maximum out of 2 possible solutions set!
(1. Row wise pairing and
 2. column wise pairing)

Otherwise :

Best[n] => The maximum out of 2 possible solutions set again
(1. The sum of new column and the older best solution B[n-1]
2. The sum of older best solution B[n-2] and the new 2x2 tile square formed)

#include<iostream>
using namespace std;
int abs(int n) { if(n < 0) return -1*n ; else return n; }

int main()
{
    int n, A[100001][2], B[100001], i, j;
    cin>>n;
    for(i=0;i<2;i++)
    {
        for(j=0;j<n;j++)
            cin>>A[j][i];
    }

    B[0] = abs(A[0][0] - A[0][1]);
    B[1] = max( B[0] + abs(A[1][0]-A[1][1]) , abs(A[1][0]-A[0][0])+abs(A[1][1]-A[0][1]) );
    for(i=2;i<n;i++)
        B[i] = max( B[i-1] + abs(A[i][0]-A[i][1]) , B[i-2] + abs(A[i][0]-A[i-1][0]) + abs(A[i][1]-A[i-1][1]) );

    cout<<B[n-1]<<endl;
    return 0;
}


问:
Could Java import C++ classes from a library using JNA or JNI?
In past, I used JNI to access some winapi functions, however winapi is C and therefore just procedural. Now my plan is different and I need to know whether I'm going in the right direction. What I want is:

to make a dynamic C++ OOP library for Linux (Debian) that, possibly based on WiringPi C library, allows object oriented approach to Raspberry PI GPIO

wrap this library in Java classes.

Note that I am also planning to use the library in it's original form, but in some cases I will need to just add the WiringPI functionalities to existing Java programs.

I am asking here because Google has failed me on figuring out whether my plan is possible and sane.

答:
Yes you can use JNI for this, even with objects... if it makes sense is another question.

Put wiringPi into a own C++ library seems a little bit strange to me because you can use the library, even in c++ code and the method calls are really simple.
Here's an tutorial how to use JNI with c++: wrapping a c library with JNI

wiringPi is C based, this way I wouldn't create a c++ lib for use with JNI, just write a wiringPI-wrapper/adapter for your JNI calls in C?!


答:
I would say the debugging is essential, unless the programmer is so good that he never makes any mistakes. I'm not convinced that that is impossible, but I can't imagine it with current popular languages and tools.

I dislike the concept of being put on the spot like that in an interview. If the candidate is nervous (and who isn't), he/she could draw a blank wheras as a programmer he may be able to routinely handle such problems. Then, if it was a well known interview or comp-sci test problem the candidate might know the result by rote, but not have the ability to think his way through a novel problem. Also if the candidate isn't familiar with the language, he is going to have to struggle. Many bugs are difficult because a good programmer knows what he meant to type, and his brain takes shortcuts while reading code. I can't find C style
use of = where == should have been used by inspection, because I know what the intent was, and my brain will take a parsing shortcut reading it.

Title: Are debugging skills important to become a good programmer?

Body:
Along with the other qualities should a programmer need good debugging skills? If I have an applicant who was not able to find the error in the given program, but was able to solve all puzzles and programs, should I consider him for the job? </p>

<p>EDIT :- The puzzles are normal red,blue and red-blue balls like. The programs are like  finding continuous k zeros in an array. The debugging program is something which fails because of condition which should be >=, but instead is >. Everything is on paper. </p>


问:
Create a globally visible method for an API
I'm trying to create a Java API that I will use in other projects.

I understand that if I create new classes I can make objects in the other projects that have those classes. But what I want right now is a way to just create a method that isn't part of an objects that I can call upon whenever I wish without having to create a new object.

So what I'm asking is, how would I create a method like this where I can pass in parameters from another project and the api project will do whatever I put in the method involving those perameters? Do I need to make the methods static or what?

When I try to just access the class with the class name and then import that class from the api, it doesn't allow me to use a public void method that I created.

答:
Yes, a static method is what you will need for this.  An example of a static method is java.lang.Thread.currentThread().

However, be advised that static methods are usually a bad idea, and best avoided. Also, be advised that it is especially people who are new to programming that are prone to make bad use of static methods.  So, if you are new to programming, you are most likely a prime example of someone who is about to make bad use of static methods.

I would recommend that you sit down and think hard how you could make this a regular ("instance") method of a normal object.  Your "other projects" would create an instance of that object, and invoke its methods.

If you absolutely have to use static methods, you should still minimize them or hide them.

To minimize static methods, consider the singleton pattern: declare just one static method called getTheOneAndOnlyInstanceOfMyObject() and make it return an object containing non-static ("instance") methods that can be invoked by your "other projects".

To hide static methods, create a facade object which your "other projects" can instantiate and invoke, and then have this facade object internally invoke the static methods.

Edit:

For a discussion of why static methods can be (or are potentially) bad, see this answer: https://stackoverflow.com/a/752805/773113


问:
Storing persistent data that only has a single instance but can change
I'm creating a website CMS in Rails (for fun and learning) and I'm trying to figure out how I'm going to store the data for an "about" page. Due to the nature of this page, the data will only have one instance, it may change and will be persistent so I want to store it in my database but I'm not sure if this is the best approach.

While a database is obviously quite capable but I feel like it's not the best place for it, as this data is not an object that will ever have multiple instances such as something like a user account.

Is there a normal way of doing this, is storing it in the database the normal thing to do and instead just pull forward a single row form the database?

答: I'd store it there, since you have a database anyway and each release can just update the row as needed.  I don't see why it matters how many instances you'll have of the class which uses the data.  I sometimes create a system table that holds configuration data for the application even though there will only ever be one row.  If your app needs a database connection to do anything useful, there's no reason to not put this sort of thing there.  You may find you have other similar pages, and so you may restructure your table at some point for their data as well.</p>


答:
The recommended way is to read carefully the official JNI documentation.

(Disclaimer: my description below may contain errors.)

This requires not one, but two layers of wrappers (item 2 and 3):

Java application code

Java JNI wrapper classes (to give an object model to the library)

C JNI wrapper (to marshal the data between JNI environment and C/C++ code)

C++ library code

The C JNI wrapper is responsible for gaining access to Java arrays, strings, object member fields, etc. This is necessary because Java can move around arrays and objects in memory, as part of garbage collection. In some sense, C code cannot get hold of anything in the Java environment unless it obtains a reference (which signifies the thing's lifetime to the VM). Even so, one can only obtain addresses of arrays if the array and the VM support pinning (being pinned down at its current memory address). Otherwise, every access to Java data requires copying, and this copying can only be performed with the help of the JNI.

The C JNI function cannot be a class member function, by design. To be able to call C++ object member functions, the C JNI method must obtain the address of the C++ object (typically stored as a 32-bit or 64-bit integer field in the Java JNI wrapper class), and cast it into the C++ object pointer.

The biggest problems are:

It is hard for wrapper generators to generate a satisfactory Java object model given the C/C++ code, regardless of whether the latter was written in an OOP style. Wrapper generators written in the last decade do not understand C/C++ styles deep enough to be able to recognize OOP idioms. (Most might even fail to parse legal C/C++ code, due to the language's syntax complexity.)

A human wrapper-writer will make plenty of style adaptations between the two languages. Until recently, it was hard to imitate such preferences (which are not mechanical and not straightforward) in wrapper generators.

Please also take a look at

SWIG

JavaCPP

Title: Could Java import C++ classes from a library using JNA or JNI?

Body:
In past, I used JNI to access some winapi functions, however winapi is C and therefore just procedural. Now my plan is different and I need to know whether I'm going in the right direction. What I want is:

to make a dynamic C++ OOP library for Linux (Debian) that, possibly based on WiringPi C library, allows object oriented approach to Raspberry PI GPIO

wrap this library in Java classes.

Note that I am also planning to use the library in it's original form, but in some cases I will need to just add the WiringPI functionalities to existing Java programs.

I am asking here because Google has failed me on figuring out whether my plan is possible and sane.


问:
How Should I Design JSON Serializable Data Classes To Respect Future @NonNull Fields
I have an app that uses Gson to serialize/deserialize data classes and persist data between runs.

My code uses @NonNull annotations for many fields/parameters/method returns and one thing that was What if I (or another developer) adds a new @NonNull annotated field (or even just annotates an existing field) to a data class and Gson sets it to null because the JSON was saved in a previous version of the app?

Well I answered that question today. As the user guide says and my tests confirm:

This implementation handles nulls correctly

While serialization, a null field is skipped from the output

While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null

Indeed, if I add a new field to my data class, it might be initialized to null.

So I looked for a solution. I found that if I add a private no-args constructor to the data class, there is enough information for the IDE to flag that the field could indeed be null. An example of this implementation is listed below.

```<code>public void testDataClass1() throws Exception {
    int value1 = 23;
    int value2 = 48;
    final DataClass1Version1 inputClass = new DataClass1Version1(value1, value2);
    final String dataClass1Json = getGson().toJson(inputClass);
    final DataClass1Version2 outputClass = getGson().fromJson(dataClass1Json, DataClass1Version2.class);
    assertEquals(outputClass.getValue1(), value1);
    assertEquals(outputClass.getValue2(), value2);
    assertNotNull("New @NonNull field shouldn't be null.", outputClass.getSomeNewValue());
}
</code>```

DataClass1Version1.java:

```<code>public class DataClass1Version1 {
    private int value1;
    private int value2;

    public DataClass1Version1(int value1, int value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1() {
        return value1;
    }

    public void setValue1(int value1) {
        this.value1 = value1;
    }

    public int getValue2() {
        return value2;
    }

    public void setValue2(int value2) {
        this.value2 = value2;
    }

    @Override
    public String toString() {
        return "DataClass1Version1{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                '}';
    }
}
</code>```

DataClass1Version2.java:

```<code>import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class DataClass1Version2 {
    private int value1;
    private int value2;
    @Nullable
    private String someNullableString;
    //@NonNull
    //private String someNewValue; //you'll get a warning for not initializing this value
    @NonNull
    private String someNewValue = ""; //if you don't initialize this field here, it could be null after json deserialization

    private DataClass1Version2() {
        //adding this constructor caused a warning when someNewValue didn't have an initializer
    }

    public DataClass1Version2(int value1, int value2, @Nullable String someNullableString, @NonNull String someNewValue) {
        this.value1 = value1;
        this.value2 = value2;
        this.someNullableString = someNullableString;
        this.someNewValue = someNewValue;
    }

    public int getValue1() {
        return value1;
    }

    public void setValue1(int value1) {
        this.value1 = value1;
    }

    public int getValue2() {
        return value2;
    }

    public void setValue2(int value2) {
        this.value2 = value2;
    }

    @Nullable
    public String getSomeNullableString() {
        return someNullableString;
    }

    public void setSomeNullableString(@Nullable String someNullableString) {
        this.someNullableString = someNullableString;
    }

    @NonNull
    public String getSomeNewValue() {
        return someNewValue;
    }

    public void setSomeNewValue(@NonNull String someNewValue) {
        this.someNewValue = someNewValue;
    }

    @Override
    public String toString() {
        return "DataClass1Version2{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                ", someNullableString='" + someNullableString + '\'' +
                ", someNewValue='" + someNewValue + '\'' +
                '}';
    }
}
</code>```

The problem with this solution is that I generally use final fields in my data classes and as such, a no-args constructor won't work. What should I do?

While writing this up, I thought of just initializing to some default values and then I guess since Gson uses reflection, it will overwrite those defaults, even though they are final fields. I still want to know what others think. Does this add extra weight to deserialization; if I have a bunch of ArrayLists and I create new instances in the no-args constructor, won't the new instances be instantly replaced with the instance Gson generated?

Here's DataClass2Version2 with final fields and default initializers:

```<code>import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class DataClass2Version2 {
    private final int value1;
    private final int value2;
    @Nullable
    private final String someNullableString;
    @NonNull
    private final String someNewValue;

    private DataClass2Version2() {
        value1 = 0;
        value2 = 0;
        someNullableString = null;
        someNewValue = "";
    }

    public DataClass2Version2(int value1, int value2, @Nullable String someNullableString, @NonNull String someNewValue) {
        this.value1 = value1;
        this.value2 = value2;
        this.someNullableString = someNullableString;
        this.someNewValue = someNewValue;
    }

    public int getValue1() {
        return value1;
    }

    public int getValue2() {
        return value2;
    }

    @Nullable
    public String getSomeNullableString() {
        return someNullableString;
    }

    @NonNull
    public String getSomeNewValue() {
        return someNewValue;
    }

    @Override
    public String toString() {
        return "DataClass2Version2{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                ", someNullableString='" + someNullableString + '\'' +
                ", someNewValue='" + someNewValue + '\'' +
                '}';
    }
}
</code>```

答:
If there are files in the wild which do not contain the field (or which have the field as null) and which you need to parse, then by definition the field is nullable.  @NotNull is inappropriate in such cases.

So what can you do?

For starters, you can put a version number at the top level of the file, like this:

```<code>{
 "version": 1,
 ...other fields...
}
</code>```

Then, you have one class for parsing version 1 files, one class for version 2 files, and so on.  You throw nullable fields onto the old classes and non-nullable fields onto the new classes.  Then you just need a common interface and (perhaps) a method which converts old classes into the newest class.

This has an important downside: if you do this a lot, you will end up with a lot of classes.  Unfortunately, the best advice I can offer is "don't do this a lot."  The fact is, schema changes are difficult once you have live (production) data.  It does not matter if you're using SQL, JSON, or something entirely different.  You have to be prepared to deal with legacy data in one way or another, and that will always be challenging, regardless of how you go about it.

Body:
If there are files in the wild which do not contain the field (or which have the field as null) and which you need to parse, then by definition the field is nullable.  @NotNull is inappropriate in such cases.

So what can you do?

For starters, you can put a version number at the top level of the file, like this:

{
 "version": 1,
 ...other fields...
}

Then, you have one class for parsing version 1 files, one class for version 2 files, and so on.  You throw nullable fields onto the old classes and non-nullable fields onto the new classes.  Then you just need a common interface and (perhaps) a method which converts old classes into the newest class.

This has an important downside: if you do this a lot, you will end up with a lot of classes.  Unfortunately, the best advice I can offer is "don't do this a lot."  The fact is, schema changes are difficult once you have live (production) data.  It does not matter if you're using SQL, JSON, or something entirely different.  You have to be prepared to deal with legacy data in one way or another, and that will always be challenging, regardless of how you go about it.


问:
When using the Apache license, is there still a need for a Contributor License Agreement (CLA)?
I can certainly see the need for CLAs with a terser license like MIT or BSD, but the more verbose Apache seems to already have that type of verbiage in it. I would prefer to not add this level of complication an open source project if it is not necessary with the Apache 2.0 license.

CLAs seem to primarily grant a copyright license and a patent license from the contributor to the project, both of which are already in the text of the Apache 2.0 license (sections 2 and 3). If I am using the Apache license, do I really need to also add the extra requirement for contributors to sign a CLA? I basically want to get the general benefits of a CLA (like the non-ambiguous right to relicense, though the contributor maintains ownership) without making contributors fill out a bunch of information and sign a contract in some third-party form.

Doesn't the act of cloning a repository, modifying code, and sending a pull request indicate agreement to the terms of the associated license? Section 5 of the Apache 2.0 License explicitly states that contributions shall also be under Apache 2.0:

Submission of Contributions: Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

When combined with Sections 2 & 3 regarding grant of copyright license and patent license "...to reproduce, prepare Derivative Works of, sublicense..." it would seem that Apache 2.0 already covers the project's bases regarding submissions. Or am I misunderstanding a possible difference between a "sublicense" and actually changing the license of the project?

(Since the Open Source Licensing Q&A site is still a just a proposal, I will accept IANAL answers here.)

答: In my (rather limited) experience a CLAs often grant the project owners permission to use the contributed code not only under the license in effect when the contribution was made, but under others as well. So if for some reason you decide to switch the whole project from Apache 2 to MIT or GPL 2 or whatever, doing so can be fine if your contributers signed a CLA which covered such scenarios, but with Apache 2 behavior you'd still have to ask each such contributor for their agreement.</p>


问:
Oscillations detector: how to effectively detect oscillations of a variable?
I monitor a variable in real-time where new value is generated every 1/25 second. Depending on the conditions, this variable may either be stable, i.e. fluctuate a little (+/-1%) around some value (for simplicity, I'll take real value of 40 from my recent experiments) or fluctuate widely from 0 up to 6x or 8x times bigger than stable value (200-370 for the example). My goal is to detect these stable periods.

Right now, I solve this problem like follows:

measure mean and deviation of the incoming variable since the
begginning of measurements;

if at any given point the ratio of
deviation/mean is greater than a threshold (0.15 right now) I
consider that the variable has entered unstable period, otherwise - the
variable is considered stable.

This approach generally worked, but not so good. Sometimes, detector fails to detect unstable periods. Here is the picture of recent experiment where ratio (in percentage) was less than 15%, detector considered period as a stable, however it can be clearly seen that variable becomes unstable towards the end of the graph (left axis is for the mean and "delta" - value of the variable; right axis for the deviation/mean ratio in percents):

As you can see, variable (blue line, delta) starts to fluctuate wildly at the end of the graph, however ratio deviation/mean stays under threshold (the maximum is around 8%) and doesn't trigger detector.

So I'm wondering, whether there are some existing oscillation detectors techniques/algorithms which can help to adjust the sensitivity of the detector? Currently, I'm thinking of using sliding average for the mean value and lowering the threshold up to 8%.

High-level system description

There is a producer which generates packets at constant rate, though it might get interrupted and inter-producing delay may not be exactly the one chosen (i.e. target is 25fps, but delay may vary between 30 and 50ms, very rarely it can be interrupted and delay may become twice as much). These packets are available on the network and cached. Consumer asks for these packets by issuing requests. It aims at exhausting the cache - by issuing large amount of requests. Those requests that ask for non-existent data, will become pending and answered as soon as corresponding packets are generated. Therefore, consumer will know that it has exhausted the cache once the data will arrive with "stable" period, i.e. the one that "roughly" corresponds to the target producer rate. As one can see, this inter-arrival delay is affected 1/ by producer (it's not exactly 40ms) and 2/ network disruptions.

Here's the sample data; there are bunch of additional parameters, but the real observed value is in "delta" column.

答:
I tested a solution that keeps a running average of the previous N samples, and N samples before that. This has the effect of smoothing the noise out, but you can compare the differences between the two averages to determine if any significant change has occurred between the two.

If this solution doesn't work, I have other ideas, but this is simple and seems to work well with the sample data you posted.

I did a mock up in Python. I'm not sure of your comfort level with that, so I didn't make it very pythonic, so that it could be easily transcribed to whatever language you're using.

```<code>import numpy as np
from collections import deque
import pylab as plt

N = 25
windowA=deque(maxlen=N)
windowB=deque(maxlen=N)

avgA = []
avgB = []

with open('stab-estimator - Sheet1.tsv', 'r') as f:
  f.readline() # skip header
  for line in f:
    delta = float( line.split()[1] )
    windowB.append(delta)
    windowA.append(windowB[0])
    # I'll store the averages so we can plot them, but you can just use
    # avgA/avgB as a metric for stability, without storing a history.
    avgA.append(np.sum(windowA)/len(windowA))
    avgB.append(np.sum(windowB)/len(windowB))

# Plot the result:
avgA = np.array(avgA)
avgB = np.array(avgB)
plt.figure()
# plt.plot(avgA-avgB)
# Or equally telling:
plt.plot(avgA/avgB)
plt.show()
</code>```

The plot of that ratio looks like this:

As you can see, it presents a good metric for your observed instability. You could easily set a threshold of 10% and catch that instability at the end. You may also want to tune N. The size of N will be a compromise between smoothing and sensitivity to changes. If N is too large, then the signal will have to grow more quickly to overcome the large averaging window.

Also, you will have to mute the alarm at the beginning while the averages converge to running values.

HTH.

Body:
I tested a solution that keeps a running average of the previous N samples, and N samples before that. This has the effect of smoothing the noise out, but you can compare the differences between the two averages to determine if any significant change has occurred between the two.

If this solution doesn't work, I have other ideas, but this is simple and seems to work well with the sample data you posted.

I did a mock up in Python. I'm not sure of your comfort level with that, so I didn't make it very pythonic, so that it could be easily transcribed to whatever language you're using.

import numpy as np
from collections import deque
import pylab as plt

N = 25
windowA=deque(maxlen=N)
windowB=deque(maxlen=N)

avgA = []
avgB = []

with open('stab-estimator - Sheet1.tsv', 'r') as f:
  f.readline() # skip header
  for line in f:
    delta = float( line.split()[1] )
    windowB.append(delta)
    windowA.append(windowB[0])
    # I'll store the averages so we can plot them, but you can just use
    # avgA/avgB as a metric for stability, without storing a history.
    avgA.append(np.sum(windowA)/len(windowA))
    avgB.append(np.sum(windowB)/len(windowB))

# Plot the result:
avgA = np.array(avgA)
avgB = np.array(avgB)
plt.figure()
# plt.plot(avgA-avgB)
# Or equally telling:
plt.plot(avgA/avgB)
plt.show()

The plot of that ratio looks like this:

As you can see, it presents a good metric for your observed instability. You could easily set a threshold of 10% and catch that instability at the end. You may also want to tune N. The size of N will be a compromise between smoothing and sensitivity to changes. If N is too large, then the signal will have to grow more quickly to overcome the large averaging window.

Also, you will have to mute the alarm at the beginning while the averages converge to running values.

HTH.


问:
What are you telling yourself if you can't understand new concept, paradigm, feature ...?
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?

答:
Even if you've never met someone smarter than you - and chances are you have - it's highly improbable that you're the smartest. And even if you're smartest, there's probably someone who has more luck than you and will stumble on correct combination of keywords which you have to type in Google to get to the right answer.

So, learn to live with your limited mental resources and remember that endurance and perseverance are generally more important than smarts and usually make all the difference.

Of course, sometimes all the perseverance in the world won't help you. There are some problems which simply require greater intelligence than you posses. There are also problems which nobody in all of the human history was able to solve because they require greater intelligence than anyone living or dead has ever had. And a lot of problems are probably unsolvable.

Remember that it's not about you and your ego, it's about solving a problem at hand. If you lack discipline to think about problem instead of you, get over yourself and train your mind to keep your emotions in check.


问:
What's the correct way to architect multiple ASP.NET MVC applications dealing with similar data?
I am currently working to replace a bunch of legacy applications. The first one is getting close to being released, which will mean I will be starting the second one.

Each application deals with a specific part of a sales process. Initial customer acquisition (with potentially very little customer data, with a lot of it being optional intentionally), through to actual quote/sale process, and then on to an application looking at how to get customers back into the beginning of the sales acquisition process.

Now I have built applications for many years, used different techniques, all with their pro's/con's, without really knowing the preferred way.

One large database, re-used by all of the applications to share customer data etc. This can make it a lot of work to maintain, having loads of developers all working on the same schema and services, having a dependency to most likely have to release all applications at the same time following changes

Database split per area (Customer, Sales, Business Hierarchy etc), gives a logical split, but they are all still used by all of the applications, yet joins for data across databases can cause problems unless you do cross-database joins/link servers etc

Each individual application has it's own set of databases. This makes development of each application a lot quicker and simpler. Yet also gives a lot of duplication in data copying it across each application. Then any changes in data needs synced somehow with other databases. For some areas you could open up a web API to get to some data between them, but a lot of the time you may end up having to read from one database to use that info to get more info from another etc rather than doing simple quick joins.

Can anyone give some info on the correct way? Yes, things can possibly be subjective, but I'm sure one of these ways would be more recommended than the other.

答:
Schemas are a middle road between different databases and the drawbacks of having different databases.  You can have your Customer and your Sales schemas, keeping them totally independeent or mixed as needed.

That gives you (2) without the major headaches with different databases: joins are in database, setup is easy (no linked servers), the data is all kept together (depending on size and usage this may be either positive or negative).


问:
Why do languages such as C and C++ not have garbage collection, while Java does?
Well, I know that there are things like malloc/free for C, and new/using-a-destructor for memory management in C++, but I was wondering why there aren't "new updates" to these languages that allow the user to have the option to manually manage memory, or for the system to do it automatically (garbage collection)?

Somewhat of a newb-ish question, but only been in CS for about a year.

答:
Here is a list of inherent problems of GC, which make it unusable in a system language like C:

The GC has to run below the level of the code whose objects it manages. There is simply no such level in a kernel.

A GC has to stop the managed code from time to time. Now think about what would happen if it did that to your kernel. All processing on your machine would stop for, say, a millisecond, while the GC scans all existing memory allocations. This would kill all attempts to create systems that operate under strict real-time requirements.

A GC needs to be able to distinguish between pointers and non-pointers. That is, it must be able to look at every memory object in existence, and be able to produce a list of offsets where its pointers can be found.

This discovery must be perfect: The GC must be able to chase all the pointers it discovers. If it dereferenced a false positive, it would likely crash. If it failed to discover a false negative, it would likely destroy an object that's still in use, crashing the managed code or silently corrupting its data.

This absolutely requires that type information is stored in every single object in existence. However, both C and C++ allow for plain old data objects which contain no type information.

GC is an inherently slow business. Programmers that have been socialized with Java may not realize this, but programs can be orders of magnitude faster when they are not implemented in Java. And one of the factors that make Java slow is GC. This is what precludes GCed languages like Java from being used in supercomputing. If your machine costs a million a year in power consumption, you don't want to pay even 10% of that for garbage collection.

C and C++ are languages that are created to support all possible use cases. And, as you see, many of these use cases are precluded by garbage collection. So, in order to support these use cases, C/C++ cannot be garbage collected.