Remove pixel patch in image which is stored as array

On my computer it takes 1.745 seconds to run the code in the post.
There's no need for the array of random indexes to be two-dimensional:

IDX = np.random.randint(0,P,(N,1))

In fact this is harmful for performance, because it means that x0[i] is an array of length 1 (not a scalar) and so img[x0[i]+x,y0[i]+y] requires "fancy indexing" which is slower than normal indexing.

It would be simpler to make the array of indexes one-dimensional:

IDX = np.random.randint(P, size=N)

This reduces the runtime to about 0.459 seconds (26.3% of the original).
There is no need to reassign I[i] at the end of the loop. When you call the reshape method on a NumPy array, what you get is a view onto the original array (not a copy) if possible. (And it is possible in this case.) So updating the view also updates the original.

This reduces the runtime to about 0.449 seconds (25.8%).
Instead of looping over range(N) and then looking up I[i] and x0[i] and y0[i], use zip to loop over all the arrays simultaneously:

for img, xx, yy in zip(I, x0, y0):
    img = img.reshape(q,q)
    for x in range(ps):
        for y in range(ps):
            if xx + x < q and yy + y < q:
                img[xy + x, yy + y] = 0.0

This reduces the runtime to about 0.358 seconds (20.5%).
Instead of looping over all the pixels in the patch and updating each pixel individually, use slices to update the whole region in one step:

for image, x, y in zip(I, x0, y0):
    image.reshape(q, q)[x:x + ps, y:y + ps] = 0.0

This works because NumPy (and Python generally) ensures that the bounds of a slice do not go beyond the end of the array. See the slicing documentation:

  The slice of \$s\$ from \$i\$ to \$j\$ is defined as the sequence of items with index \$k\$ such that \$i \le k < j\$. If \$i\$ or \$j\$ is greater than len(s), use len(s).

This reduces the runtime to about 0.025 seconds (1.4%).
We can vectorize the additions x + ps and y + ps:

for image, x, y, x1, y1 in zip(I, x0, y0, x0 + ps, y0 + ps):
    image.reshape(q, q)[x:x1, y:y1] = 0.0

This reduces the runtime to about 0.021 seconds (1.2%).
We could avoid the reshape inside the loop by doing a single reshape of the whole I array:

images = I.reshape(N, q, q)

and then:

for image, x, y, x1, y1 in zip(images, x0, y0, x0 + ps, y0 + ps):
    image[x:x1, y:y1] = 0.0

This reduces the runtime to about 0.018 seconds (1.0%).
We can halve the number of indexing operations by indexing the images array just once on each loop iteration:

for i, x, y, x1, y1 in zip(range(N), x0, y0, x0 + ps, y0 + ps):
    images[i, x:x1, y:y1] = 0.0

This reduces the runtime to about 0.011 seconds (0.6%).

That's about 150 times speedup overall, so calling this a million times will still take about 3 hours on my computer. There may be other improvements to be had if only we could see more of your code, but you'll need to make a new post for that.


General Comment

This looks like exercises from Functional Programming in Scala.  It's some time since I read that, but I'm pretty sure you are expected each time to use the functions you have already written, better to learn their use, rather than reach for Scala's core library functions or build-in control structures like for loops.

List Concatenation

Are you using your own implementation or the library version?  Either way, it looks as if you are doing this inefficiently because the first parameter in the library function passed to foldLeft is the accumulator, the second the list element.  As I recall, the book version does the same.

When concatenating immutable lists, the list on the left is entirely recreated, while the list on the right is shared and not copied at all.  foldLeft is the worst solution here because you start with the leftmost list and repeatedly add a new list on the right.  So with the first two lists, you copy the one on the left.  Then, when you add the third on the right, you completely copy your first two lists.  And so on, until you reach the final list.  This means that with n lists, the first list is copied n-1 times, the second n-2 times and so on.  Very wasteful.

With a foldRight solution, where you start by appending the seed (empty list) on the right of the rightmost list and then in each subsequent operation append the accumulated value on the right and not the left, each list is only copied once.

By the time you reached this challenge, you should have written a stack-safe version of foldRight.

You could, alternatively, reverse the outer list and then foldLeft.  Either way, remember that you want the accumulator to be on the right hand side of ++

add1

By using a for loop you have learned nothing about how to use the functions you have already written to build other functions.

You should, at this point, have written two stack-safe functions which make it possible to traverse a list: foldLeft and foldRight.  Either can be used but remember that you need to preserve the original order.

map

Again, using a for loop you have learned nothing about how to use the functions you have already written.  In fact, since Scala will actually rewrite the for loop using the core library map function, you've implemented map using map.
 Which works buy isn't in the spirit of the challenge.

map is just the general case of add1, so the same answer applies as in that challenge.

Summary

Your first solution didn't meet the requirements at all, since it scales exponentially and not linearly.  The other two work functionally but don't meet the explicitly given (and often repeated) requirement to reuse functions you've written.

Forgive me for not providing you with any code examples but I don't want to rob you of the challenge to learn (which is the whole point of the book).


Concatenate several CSV files in a single dataframe

Here is my untested feedback on your code. Some remarks:

Encapsulate the functionality as a named function. I assumed folder_path as the main "variant" your calling code might want to vary, but your use case might "call" for a different first argument.
Use PEP8 recommandations for variable names.
Comb/separate the different concerns within the function:

gather input files
handle column types
read CSVs and parse dates

Depending on how much each of those concerns grows in size over time, multiple separate functions could organically grow out of these separate paragraphs, ultimately leading to a whole utility package or class (depending on how much "instance" configuration you would need to preserve, moving the column_names and dtypes parameters to object attributes of a class XyzCsvReader's __init__ method.)
Concerning the date parsing: probably the bottleneck is not caused by caching or not, but how often you invoke the heavy machinery behind pd.to_datetime. My guess is that only calling it once in the end, but with infer_datetime_format enabled will be much faster than calling it once per row (even with your manual cache).

import glob
import os
import pandas as pd

def read_xyz_csv_folder(
        folder_path,
        column_names=None,
        dtypes=None):
    all_files = glob.glob(os.path.join(folder_path, "*.csv"))

    if column_names is None:
        column_names = [
            'COLUMN_A',
            'COLUMN_B',  # ...
            'COLUMN_Z']
    if dtypes is None:
        dtypes = {
            'COLUMN_B': bool,
            'COLUMN_D': int,
            'COLUMN_Y': float}
    dtypes.update({col: str for col in column_names
                   if col not in dtypes})

    result =  pd.concat((
            pd.read_csv(file, index_col=False, dtype=dtypes)
            for file in all_files),
        ignore_index=True)

    # untested pseudo-code, but idea: call to_datetime only once
    result['date'] = pd.to_datetime(
        result[[6, 14]],
        infer_datetime_format=True,
        errors='coerce')

    return result

# use as
read_xyz_csv_folder('PATH_TO_FOLDER')

Edit: as suggested by user FMc in their comment, switch from a list comprehension to a generator expression within pd.concat to not create an unneeded list.


You could do better on your time complexity. Your current method runs in O(n^2), where n is the length of the concatenated newArr. However, if you sorted arr1 and arr2 first and then merged them, you could reduce the time complexity to O(n*log(n)), where n is the length of the longer of the two arrays:

function compareInventoryItems(a, b) {
  return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
}

function updateInventory(arr1, arr2) {
  arr1.sort(compareInventoryItems); // O(n*log(n))
  arr2.sort(compareInventoryItems); // O(m*log(m))

  var newArr = [],
    i1 = 0,
    i2 = 0;

  while (i1 < arr1.length && i2 < arr2.length) { // O(n+m)

    switch (compareInventoryItems(arr1[i1], arr2[i2])) {
      case -1:
        newArr.push(arr1[i1++]);
        break;
      case 1:
        newArr.push(arr2[i2++]);
        break;
      case 0:
        arr1[i1][0] += arr2[i2][0];
        newArr.push(arr1[i1]);
        i1++;
        i2++;
        break;
    }
  }
  while (i1 < arr1.length) {
    newArr.push(arr1[i1++]);
  }
  while (i2 < arr2.length) {
    newArr.push(arr2[i2++]);
  }

  return newArr;
}

// Overall complexity = O(n*log(n)) + O(m*log(m)) + O(n+m) = O(n*log(n))

One problem is that the passed in arrays are mutated. You have this problem in your current solution too when you add the amounts of a matched item. Another issue is that the new array share pointers to the original inventory items. This could result in someone inadvertently mutating the updated inventory when working with the original arrays passed into updateInventory. If any of that's a concern to your project, then you could create copies of the items to avoid them all:

function updateInventory(arr1, arr2) {
  arr1.map((x) => x.slice(0)).sort(compareInventoryItems); // O(n*log(n))
  arr2.map((x) => x.slice(0)).sort(compareInventoryItems); // O(m*log(m))
  // ...


Best accuracy and performance with timers in JS

BUGs
First some logic and flow bugs.

The function release uses indexOf to get the timer index i then you use the statement if(i) { ... which fails to remove the first item in the instances array. The result is the worker is never shut down.

Calling UberTimer.stop(timer) from within the callback function timer.callback fails to stop the timer, the callback continues to be called. Because you set lastTickTime to -1 your code then tries to catch up by calling the callback at the full rate of the worker's messages.

And related to how you call the callback function.

If the callback function timer.callback fails to return (throws an error) on the function timer.start the timer.lastTickTime property is not set and remains the init value of -1. The callback is then call in rapid succession, and if the callback continues the throw it just continues tring to catch up every time the worker sends a message. The is in  effect an infinite message incomplete loop

Because you call the callback function from the function timer.start any error in the callback will stop current execution context. This is not what one would expect from a timer.

When you have many timers. If any callback throws the remaining callbacks (higher on the instance array) will not get called as the UberTimer.__tick does not get to complete the timer iteration loop.

Danger potencial silent bug.
Because the property UberTimer.worker is exposed there is a danger that you loose the reference to the worker, if it is accidentally or deliberately overwritten. This could result in a silent bug that makes its way to release degrading performance. You should make it safer (protect your state).
Some style notes

Underscore prefixes do not create private / protected variables. If you wish to protect your object's state don't expose functions and properties that you don't want messed with.

C like languages allow the lazy programmers to save milliseconds typing by not including {...} for single line statement blocks. The irony is that the cost is hours of bug hunting. Your eyes don't look for { and } when you think you are looking for a logic bug.
For your coding sanity ALWAYS delimit blocks with {...}

if(foo === blah)
    foo = 1;

 // then later you make the change

 if(foo === blah)
    foo = 1;
    blah = 1;

// Yes obvious in isolation. But in 100's of lines of code with many unblocked statements
// the eye sees the indent and the mind puts in the {}

// never an issue if you always do
if (foo === blah) { foo = 1 }
// or
if (foo === blah) {
    foo = 1;
}

Use === or !== never use == or !=

For variables that never change declare them with const

Don't define a variable in one type only to convert it to another when you use it. The worker function can be defined as a constant string.

Don't add redundant or superfluous code it only reduces the quality of the code. module.exports = UberTimer = function UberTimer( reassigning the UberTimer serves no purpose in your code.

 this.blocking = {};
 this.blocking.maxTime = blockThreadMaxMs;
 this.blocking.startTime = -1;

 // should be

 this.blocking = {
     maxTime : blockThreadMaxMs,
     startTime : -1,
 };

Use object function shorthand if you can.

UberTimer.prototype.__makeCall = function() { ... }

UberTimer.prototype.__workerTick = function() { ... }

UberTimer.prototype.start = function() { ... }

UberTimer.prototype.stop = function() { ... }

Is better as
UberTimer.prototype = {
     __makeCall() { ... },
    __workerTick() { ... },
    start() { ... },
    stop() { ... },
};


No, it's not correct (and thus of course also not best practice). For example the condition c == Color.GREEN will be true if the method is called as brickVal(Color.GREEN), but false if it is called as brickVal(new Color(0, 255, 0)). Since Color.GREEN is equal to new Color(0, 255, 0) this behavior is most likely unintentional (at least I can't imagine a scenario where you'd want for brickVal(Color.GREEN) to behave differently than brickVal(new Color(0,255,0)).

Of course if you know that the method will only ever be called using the "pre-made" colors and never using new Color, it will behave correctly. However I'd still advise against using ==. I can see no good reason to not use equals and using == comes with the danger that someone might call brickVal with new Color anyway, not knowing that they're not supposed to.

Further given the fact that brickVal apparently is meant to be only called with some specific colors as arguments and it doesn't use any properties of the colors other than their identity, I think an enum might be more suitable here than using the Color class. This way you can use switch instead of if ... else if ... and don't have to worry about anybody passing in new Color as the argument.

As a somewhat unrelated note, I find it confusing that the brickVal variable is set in every case except if the argument is RED and in the else case. Obviously I don't know how and where the brickVal variable is going to be used, but this seems like a design smell to me. I also think it's a bad idea to have a variable with the same name as the method.


Calculating sum of similarities of strings

I think you need a suffix tree.

Its a data structure that puts all the prefixes of a string in a tree. This makes a number of operations faster, and I think you can make your similarity metric qualify.


String manipulation over 2 tables in database to application

Even if I don't know the actual content, joining tables on client-side is basically a bad idea because you have to load the whole content to the client.

As BCdotWEB mentioned in the comment, the prefered way is to consolidate your data model to avoid such hacks. If that is not possible, your solution with the convert_string should work. If you need a more efficient solution, you could use function-based-indexes or virtual columns with indices, which should significantly increase query performance.

One comment to the posted code: The oracle function as well as the c# method do not check the length of the string before accessing the 6'th element which may result in an index out of range exception.


Bug

dequeue doesn't set last to null when the queue becomes empty. On the other hand, isEmpty relies on last being null.
enqueue should be streamlined to

    if (first == null) {
        first = p;
    } else {
        last->next = p;
    }
    last = p;
    size++;

to clearly state common vs different actions.


Groovy Map>> data manipulation method optimization

You can use Groovy's regular expression operators to create Java Matchers.

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,',
'5|20150301|INV WITH WHITESPACE|29,']

def lines = invoices
    .findAll { it.contains('|') }
    .collect { it.tokenize('|') }

def headers = lines.first()
def invoiceMap =  lines.tail().collect{
    [headers, it].transpose().collectEntries()
}.groupBy{ it.INVOICE_NUMBER }

class InvoiceError {
    String errorMessage
    String invoiceNumber
}

[
    ['INV-Error_Test1', 'File Error : The file is in an unsupported format'],
    ['INV-Error_Test1', 'Line : 1 Invoice does not foot Reported'],
    ['INV-Error_Test1', 'Line : 2 MATH ERROR'],
    ['INV-Error_Test2', 'Line : 3 MATH ERROR'],
    ['INV-Error_Test2', 'Line : 3 Invoice does not foot Reported']
].collect {
    [['invoiceNumber', 'errorMessage'], it].transpose().collectEntries()
}.collect { it as InvoiceError }
.each {error ->
   def matcher = error.errorMessage =~ /Line : (\d+) (.*)/

   if(matcher) {
       def lineNumber = matcher.group(1)
       def errorDescription = matcher.group(2)
       def line = invoiceMap[error.invoiceNumber]
           .find() { it.LINE == lineNumber }

       if(line.errors) {
           line.errors = "$line.errors |  $errorDescription"
       } else {
           line.errors = errorDescription
       }
   } else {
       if(!invoiceMap.errors) invoiceMap.errors = []
       invoiceMap.errors << [(error.invoiceNumber): error.errorMessage]
   }
}

invoiceMap

In this example, I build the InvoiceError instances from a list that's transposed (btw, thank you for that trick). Each resulting map is coerced into an instance of InvoiceError.

I took a different approach by iterating through the errors and inserting them into the invoiceMap, rather than iterating through the invoiceMap and looking up the errors.


Small function for getting character value

The easiest code to maintain is code that doesn't exist.  For parsing XML, use an XML-parsing library, preferably with XPath support.  Sometimes it might be justified to whip up your own code to extract values from XML, but it clearly does not make sense in this case.  Not only is the code ugly by your own admission, low-level string- and memory-manipulation also distracts you from thinking about the big picture.  Furthermore, your code will be less robust than a proper XML parser, and it will fail if the text is encoded in a semantically equivalent variant (for example, if a value is escaped).


Displaying separated multi-line text fields

Just do a string replace to swap the html breaks for commas, then trim the end to remove any extra commas:

retailBreaks.Replace("<br/>",",").TrimEnd(',')


Emitting event on close of other event (event chaining)

You should note that there's a significant difference between events and Promises. Events listen and fire multiple times. However, Promises are a one-time deal. Once it resolves/rejects, the callback won't fire again. You'll have to recreate the whole sequence for another series. With that:

  is it possible to chain the events?

Yes and no. It depends on the event source. In your case, assuming downloadfile, extract and collect are event sources for a single operations, you can simply wrap that event source in a promise that resolves/rejects.

  If so, how could i achieve that?

Assuming emit is a trigger to start the operation, error as the error listener and close as success, you can simply wrap them in promises, where error calls rejectand close calls resolve.

function downloadFiles(downloader, options){
  return new Promise((resolve, reject) => {
    downloader.emit('copy', file);
    downloader.on('error', reject);
    downloader.on('close', resolve);
  });
}

function extract(extractor, file){
  return new Promise((resolve, reject) => {
    extractor.emit('copy', file);
    extractor.on('error', reject);
    extractor.on('close', resolve);
  });
}

function collect(collector, data){
  return new Promise((resolve, reject) => {
    collector.emit('copy', data);
    collector.on('error', reject);
    collector.on('close', resolve);
  });
}

function createSequence(){
  var downloader = createDownloadFileThingy();
  var extractor = createExtractThingy();
  var collector = createCollectThingy();

  return Promise.resolve(options)
    .then(options => downloadFiles(downloader, options))
    .then(file => extract(extractor, file))
    .then(file => collect(collector, file.data));
}


I made a guess the number game in Python

Aside from the notes already given, here are two big ideas to think about:

Don't repeat yourself (DRY)

This is something you'll hear repeated a lot in discussions of code.  Any time you see the same "magic values" repeated more than one place (e.g. 0 and 20), or you see two lines of code that do exactly the same thing for exactly the same reason (e.g. your input() statements or the multiple CORRECT checks) it's a clue that you have an opportunity to share some code.

In the case of the magic numbers, one solution is to define them as constants at the top of the file.  The approach I'd prefer, personally, would be to make them parameters -- rather than hardcoding 0 and 20, have your function(s) take a range as a parameter.

In the case of the multiple "CORRECT" checks, this is just a matter of restructuring the loop a little.

Have each function do one thing well

This is significantly more subjective, but in looking at your function, I see two very separable things it's doing within its single main loop -- prompting the user for valid input, and giving them feedback on their guess.  If you have one piece of code that just has to get the input without having to worry about the game loop, and you have another that handles the game loop without having to worry about whether the input is valid, then both of them can be simpler.

When you start doing larger projects, breaking logic apart into simple functions makes it easier to test the individual units of your code independently.

I messed around with the code for a bit using those two principles and came up with this:

import random

def describe_range(numbers: range) -> str:
    """Nice English-language description of a range."""
    return f"between {numbers[0]} and {numbers[-1]}"

def input_number(numbers: range) -> int:
    """
    Prompt the user for a number within the range,
    retrying on invalid input.
    """
    while True:
        try:
            number = int(input())
            if not number in numbers:
                raise ValueError(f"The number needs to be {describe_range(numbers)}")
            return number
        except ValueError as e:
            print(e)

def guess_number(numbers: range) -> None:
    """
    Play a guessing game with the user within a range of numbers.
    Tell them whether their guess is too big or too small.
    They win when they get it right!
    """
    print("Enter a random number", describe_range(numbers))
    answer = random.choice(numbers)
    while True:
        guess = input_number(numbers)
        if guess > answer:
            print("too big")
        elif guess < answer:
            print("too small")
        else:
            print("CORRECT")
            break

if __name__ == "__main__":
    guess_number(range(21))

Note that I'm using Python 3's type annotations to say what type of argument each function takes and what it returns -- this is really handy because you can use the mypy tool to automatically check your code for errors (for example if you say a function returns an int and there's a line in that function that returns a str, mypy will throw an error), and therefore you don't need to worry as much about your code getting the wrong type at runtime.  The type annotations also serve as documentation for your functions so that human readers can easily see what sorts of values they should expect the code to be working with.


Adding, deleting elements as per autocomplete results - updated

Structurally, it doesn't look too bad, although it seems inconsistent.

By convention, JavaScript uses camelCase naming - not snake_case. All your code is snake_case, but then you have things like keyCode and charCodeAt because that's what JS's own APIs use. So I'd encourage you to switch you code to camelCase in keeping with JS conventions.

You've got a number of "constants" (in quotes, since JS doesn't actually have constants), like EV_ENTER_KEY, which, judging from your comment, is a string (enterKey in this case). Sometimes you use the constants by name, other times you use them by value.

While it's true you can't do this:

CONST = "foo";
obj = {
  CONST: "bar"
};

and get an object like {foo: "bar"} (because JS interprets the CONST: literally), you can do this:

obj = {}
obj[CONST] = "bar";

And your object will be {foo: "bar"}.

So that would clean things up, and allow you to actually use constants. E.g.

categoryBoxEvents = {}
categoryBoxEvents.keyup = function (e) {
  bind_events(this, e);
};

categoryBoxEvents[EV_ENTER_KEY] = function () {
  enter_category($(this), EV_ADD_CATEGORY, [{
    cat_list: CATEGORY_LIST_ADD,
    trigger_obj: undefined,
    next_trig: undefined
  }]);
};

categoryBoxEvents[EV_ADD_CATEGORY] = function (e, data) {
  add_category(this, e, data);
};

CATEGORY_BOX.on(categoryBoxEvents);

However, don't rely on undefined being undefined. For mysterious reasons, undefined isn't a reserved word in JS, meaning that some (older) runtimes allow it be defined. Instead, use null or just don't set a value at all.

For instance, the event-key event handler above could simply be:

enter_category($(this), EV_ADD_CATEGORY, [{
  cat_list: CATEGORY_LIST_ADD
}]);

If you don't define trigger_obj and next_trig, they're - by definition - undefined.

Where you need to to check for these values, you can simply do

if (!data.trigger_obj) { ... }

because undefined is false'y (and so is false, null, 0, and "").

Or, if you feel you should be (needlessly) exact:

if (typeof data.trigger_obj === 'undefined') { ... }

I'd also skip a lot of the proxy-functions you've got going on. For instance, add_category is called from 2 identical wrapper functions, only so its 1st argument can be set. Don't bother. Try this instead:

function add_category(e, data) {
  var $this = $(this); // just use `this`
  $.ajax({
    url: URL_CATEGORY,
    data: { value: $this.val() },
    success: function (output) {
      data.cat_list.append(output);
      $this.val("");
      if(data.trigger_obj && data.next_trig) {
        data.trigger_obj.trigger(data.next_trig);
      }
    }
  });
}

// ... snip ...

categoryBoxEvents[EV_ADD_CATEGORY] = add_category;

Now, when add_category is called, its this will automatically be the right object. No need for you to specify it. And if you ever need to call add_category in a different context, you can use call() or apply(), or bind it to an object with bind() (not supported on all browsers) or jQuery.proxy().

Lastly, I think you may be a bit trigger-happy (pardon the pun). You're handling events by triggering a lot of other events, which in turn seem to trigger events and so on. While that does decouple your code, it also introduces some overhead. It might make the code simpler to skip some of the trigger-cascades in favor of just calling functions directly. Same goes for the constants, which, while useful in many cases, seem a little excessive. Functions are first-class objects, so you can simply pass them around instead of referring to them.


This looks way too overengineered. Is there really a need for all the complexity? Use the KISS principle!

I'm assuming you have this pool because you want to avoid the cost of constructing and destructing Objects, and possibly to allocate a lot of instances of Object up front to avoid latency later on. If that's the case, I would instead write the pool like so:

template<typename Object>
class ObjectPool: private NonCopyable
{
    std::deque<std::unique_ptr<Object>> m_objects;

public:
    ObjectPool(size_t count = 0) {
        for(size_t i = 0; i < count; ++i) {
            auto object = std::make_unique<Object>();
            enqueue(object);
        }
    }

    std::unique_ptr<Object> dequeue() {
        if (m_objects.empty()) {
            return std::make_unique<Object>();
        } else {
            auto object = std::move(m_objects.back());
            m_objects.pop_back();
            return object;
        }
    }

    void enqueue(std::unique_ptr<Object> &object) {
        m_objects.emplace_back(std::move(object));
    }
};

First, the constructor of this object pool just takes the initial size of the pool as a single value, so it doesn't have to know the specifics of chunk sizes.

Second, the dequeue() function creates a new object for you automatically if the pool is empty. Maybe that is not desired, in which you could return an empty std::unique_pointer instead.

Last but not least, instead of leaving it up to the destructor of an ObjectFromPool to return the object back to the pool it came from, there is now a counterpart to dequeue(): enqueue(). It simply returns an object back to its pool. This avoids having to wrap objects in custom classes.

The only issue with this solution might be that you forget to return an object to its pool, but on the other hand it will still safely destruct itself once its lifetime ends.


Extracting key information from a directory of XML files

A few short comments:
Use Option Explicit:
Why? because It makes thinks easier by orders of magnitude when developing.
You get more useful error messages and it becomes harder to misspell variable names without realizing.
That brings us right to the next:
Variable Names:
Your variable names are not consistently cased. You are mixing up "camel casing" (e.g. myDir) and "Pascal Casing" (e.g. StrFile)
Also temp 1 through 4 are not really good variable names. Neither is x, but hey ;)
Error Handling:
You should really make sure your "Application" is in a clean state after exit, even when you got unexpected errors:
Sub ImportXMLToList()
    On Error GoTo ErrorHandler

    ' Code goes here:

:CleanExit
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Application.StatusBar = False
    Application.DisplayStatusBar = oldStatusBar

    Exit Sub
:ErrorHandler
    'Close resources, maybe errormessage
    Resume CleanExit
End Sub


There is currently no error checking to validate that this is valid UTF-8. If this is deliberate it should be documented.

You are testing the 1's at the top of a UTF-8 encoded string. But not correctly validating the trailing 0.

  if ((*cptr & 0xC0) == 0x80) { ...
  if ((*cptr & 0xF8) == 0xF0) { ...
  if ((*cptr & 0xF0) == 0xE0) { ...
  if ((*cptr & 0xE0) == 0xC0) { ...
         ///   ^^^^  You should extend the mask one more bit
         ///         So that your test validates that the next
         ///         bit is zero.

The way your function is written it will mutate the string if it finds a partial. This may not always be necessary I would break this into two functions. One that finds the amount of mutation needed and another that does the mutation. That way another user can potentially use only the non mutating part and get better performance (say if they were passing it to a function using iterators).

 std::size_t trimEndUTF8(std::string& str) {
     std::size_t trim = findEndUTF8Trim(str);
     str.resize(str.size() - trim);
     return trim;
 }

If you implement the above function split. You now make it easy for your self to implement a slight return optimization.

 if ((*cptr & 0xF8) == 0xF0) {
     if (num == 4) {
         return 0;
     }

     // break;
     // Change your break into a return.
     //
     // Because we are not mutating we don't need to worry about
     // changing the input in thus function and can just return the
     // size of the trim. Since this is the head character of a UTF-8
     // sequence the next character must be end of a UTF-8 character.
     //
     return num; // or is it num + 1 you should check.
 }

Prefer not to use yoda conditionals.

 for (int i = 0; 6 > i; ++i)
                 ^^^^^  Yoda conditional

They are a cognitive drain and less intuitive to read (unless you are yoda). Prefer the more traditional style as it makes it easy to read fof developers.

 for (int i = 0; i < 6; ++i)

Note you are assuming there are at least 6 characters in the string. I would not do that (especially since people are likely to throw all kinds of crap at it). A badly formed UTF-8 string is going to cause undefined behavior.

Standard warning about:

using namespace std;

Read any other C++ review on this site. We say don't use this. Read another review and you will find why.

Naming conventions. It is more traditional to use an initial lowercase letter for objects(this includes functions/methods).

ssize_t findEndUTF8Trim(std::string const& str) {

    // If the last character is a single character return
    // Don't need to do any further checking or trimming.
    if ((str.back() & 0x80) == 0x00)
        return 0;
    }

    // Check that we have a valid UTF-8 sequence.
    char const* cptr = &str.back();
    int const   end  = std::min(6, str.size()); // Max theoritical len == 6
    for (int num = 1; num <= end; ++num, --cptr) {
        if ((*cptr & 0xF8) == 0xF0) { return (num == 4) ? 0 : num; }
        if ((*cptr & 0xF0) == 0xE0) { return (num == 3) ? 0 : num; }
        if ((*cptr & 0xE0) == 0xC0) { return (num == 2) ? 0 : num; }
    }
    // If reach here then there is a malformed UTF-8 character sequence.
    throw std::runtime_error("Unexpected UTF-8 string");
}


You write:

map snd . filter ((==0) .fst) $ map (first (mod x)) table

To make it clearer that we have three operations applied one after another, I would rather write:

map snd . filter ((==0) .fst) . map (first (mod x)) $ table

But I think this gets easier to read if we merge the filter and the second map:

map snd . filter ((== 0) . mod x . fst) $ table

Some people prefer pointful style, that is, they prefer \ over .:

map snd . filter (\(number, text) -> x `mod` number == 0) $ table

Personally, I would prefer a list comprehension here:

[text | (number, text) <- table, x `mod` number == 0]


Better way to set number of threads used by NumPy

What are the pitfalls of my approach?

Calling the functions setting the maximum number of threads to use change a global state inside the respective libraries which makes the decorator not thread safe. When you use the numpy functions from several different threads, the threads not using your decorator might also get a single threaded implementation called.

AFAIK there is no good way to solve this. OpenBLAS FAQ even states that you should disable threads in OpenBLAS if your application uses threads itself.


Is it a good style to run external commands in Python?

No, it is a security risk, and furthermore, os.popen() has been deprecated since Python 2.6.  The replacement is to use the subprocess module.

The security risk is that os.popen() expects its command as a string.  That means that the command will be interpreted by a shell to split it up into the command and its arguments.  If report_file, report_dir, or _export_dir contain any spaces or characters with a special meaning to the shell, horrible unexpected things can happen, including arbitrary command execution.


back_inserter for several container arguments

The general structure seems fine to me. However, some things can still be improved!
Iterator requirements
Iterators are required to satisfy the Swappable and CopyAssignable named requirements, but the current implementation doesn't. (This is also why the std::back_inserter implementation you looked at used pointers instead of references, the latter cannot be reseated.)
And from a design perspective, this provides an interesting dilemma: Do you want to support assignment from different underlying container types? For example, like this:
std::deque<int> copy1{};
std::list<int> copy2{};

auto out = stx::back_inserter(copy1, copy2);
// out is of type stx::back_inserter_iterator<std::deque<int>, std::list<int>>

std::vector<int> copy3{};

out = stx::back_inserter(copy2, copy3, copy1);
// assignment from stx::back_inserter_iterator<std::list<int>, std::vector<int>, std::deque<int>>

If no, the solution is easy: Change the container references to pointers (to make assignment possible), add assignment operator overloads, and either use std::swaps default implementation or write your own swap function for stx::back_inserter_iterator.

This is the easy way, but in reality likely not very useful, since assignment only allows for the exact same container types.

If yes, the solution becomes more complicated, as the actual container types need to be abstracted away. One idea for this is using inheritance in an external storage class (rough idea):
template<typename ValueType>
class container_storage_base {
public:
    virtual ~container_storage_base() {}
    virtual void push_back(const ValueType&) = 0;
    virtual void push_back(ValueType&&) = 0;
};

template<typename Container, typename... Containers>
class container_storage : container_storage_base<typename Container::value_type> {
    std::tuple<Container&, Containers&...> containers; // can use references here

public:
    void push_back(const typename Container::value_type& value) override { ... }
    void push_back(typename Container::value_type&& value) override { ... }
};

Inside of stx::back_inserter_iterator, you could then simply store a std::shared_ptr<container_storage_base<ValueType>>, thus freely allowing assignment between different stx::back_inserter_iterator<ValueType> instances (as long as ValueType remains the same).

Why std::shared_ptr?
We need some indirection in order to allow for virtual dispatch to work, and using a pointer seems to be the easiest solution for that. However, we also need to release the container_storage object once we no longer need it, and for that, smart pointer come in very handy.
But: Iterators need to be copyable, and that isn't something supported by std::unique_ptr (only allowing for a unique owner), thus std::shared_ptr was chosen.

Other Nitpicks

Most functions could be marked noexcept (even if only conditionally).

Q & A

does the operator= method with the r-value work as intended or do I need to pass the value differently to the lambda?

Works as intended.
Well, mostly. With the expansion, value will be moved from for every container, i.e. every container but the first will move from an already moved-from value. To get the initial value to all containers, copies will need to be made.

do I need an extra static_assert to check that each Container supports the same value_type or at least some that are convertible to avoid overloading the user with template errors in case they are different?

Do you need to? Not necessarily.
Would it be nice for users of the implementation? Absolutely!

is there another solution where I could let the user provide and optional argument for execution policy, for example std::execution::par

I'm confused: Execution policies are for algorithms, not iterators themselves.
Of course, you can always add a data member to store a value if you want to, but I fail to see how storing an execution policy would be helpful here, as there aren't any calls to algorithms internally (and just adding an execution policy to data doesn't accomplish anything).

the original std::back_inserter saves the container as pointer - is there any advantage versus my inserter which saves them per reference?

See above, you cannot reassign references.


Your code looks overly complex to me, using three different collections when one, the hash map, would be enough. Use your code from the wordList loop when emptying the scanner, and update the word count there:

while (scanner.hasNext()) {
    String word = scanner.next()
    Integer count = wordCount.get(word)
    wordCount.put(word, count == null ? 1 : ++count)
}


Can someone help me optimize my DFS implementation in Python?

def dfs(graph, node):

This isn't a depth first search

    """Run DFS through the graph from the starting
    node and return the nodes in order of finishing time.
    """
    seen = set()
    stack = {node}

You aren't using this as a stack, don't call it that

    while True:
       flag = True

avoid flag variables, they confound code. Also that's a very undescriptive name.

       for x in stack:
           if x not in seen:

Seen these are sets, you should be probably use: for x in stack - seen: which should be more efficient

                stack = stack.union(set(graph[x]))

Using this approach will make things rather slow, you just keep making stack bigger and bigger.

                seen = seen.union({x})

Use seen.add to add things to the set. Using union like this will be much slower

                flag = False
                break
        if flag:
            break
    return list(stack)

The set gives you no guarantees as to the order of the elements. I'm guessing that's now what you wanted. As it stands,this will end up giving you all the elements in your graph in a random order.

My approach

def breadth_first_search(graph, start):
    seen = set()
    current = {start}
    history = []

    while current:
         history.extend(current) # record when we found all these elements
         seen.update(current) # add them to the list of elements we've already seen
         neighbours = set() # generate a set of all elements that we can reach from these ones
         for node in current:
             neighbours.update(graph[node])
         current = neighbours - seen # the next round of elements is this one, except those we've already seen

    return history


Looks pretty good to me. If I were doing this for an interview question, I would take on the challenge of implementing it recursively. Here are some minor changes I would make:

You are hard-coding your for loop to 31 iterations. That ought to be a const uint32_t num_iterations = 31; at the top of your code. That makes it more clear to future users what to change if they want a different number of iterations.
You are using int64_t. These are all going to be positive numbers, so uint64_t is more appropriate.
Your variables i and size are int64_t. But your values are going to overflow 64-bits well before the line they are on gets that big. I'm guessing that uint32_t is enough.
In regards to the memory management, all of the allocing and freeing is expensive and slow. If you wanted to minimize that, you should alloc 2 rows of max length up front and then ping-pong them as previous/next rows.
In your next_pascal_row routine, you're using an array pointer called retval. I see that name way overused. It would be better called this_row or next_row.
There is no need for a first_row pointer. Just use the previous_row pointer in initialization.


Replicating the norwegian flag using CSS

Quick implementation idea
Create a container div with two divs inside. Position those divs as a cross lust like in the Norwegian flag. After that give those divs a thick white border and the flag's red color would be simply the container div's background-color.
Code review

Sections are not an appropriate HTML element in this case. Use div's instead.
Do not style using html tags like body. Use CSS classes instead. Read about the css specificity
.red-square2, .red-square4{ this selector has both margin and margin-righ properties at once. margin: a b c d should be enough.
Tidy up your CSS. In one line You style .red-square3 and some lines below You style the same element. Why? Can't you use one CSS rule for that? :)

Improvement ideas

Move the CSS color to variables and place them in a separate file.


Typically this scenario is done with a decorator pattern where you would wrap just the one and have the cache functionality in the one class. You would put the code in the CacheDataAdapter that I assume is currently in the code of the IDataAdapter cache.  Most of the time this will simplify your code as you can call base method to get the values if not in the backing store for the cache.

For example if you are using the ConcurrentDictionary or MemoryCache they will have methods to GetOrCreate or AddOrUpdate that will take a lamba expression that you can call into your base method to get the value if missing.  Since you are doing async work while caching you should check out the AsyncLazy

If you don't want to do the decorator pattern I would swap Save and Delete to do it in the primary store before removing them from the cache.  You could have a situation where the save fails in the primary but your cache is updated to say it's good.

As far if you should await the ReadAllAsync or not it doesn't matter a lot.  I personally wouldn't await it but either way is fine.  See answer on SO


You always terminate the reading of the row if the element isn't found. This means you can have just one Try-Catch block that wraps your If statement.
Instead of checking for && in your first statement, use || (or instead of and). You don't really care if ReadUntilEmpty is set at that point; only ReadUntilCellError matters. This eliminates an entire block from the If statement.
You could go one step further and only check the flag just before, or with, the null value check.

public IEnumerable<string> ReadRow(string spreadsheet, int column, int row, ReadOptions readOptions = ReadOptions.ReadUntilEmpty)
{
    var values = new List<string>();

    try
    {
        for (var currentColumn = column; ; currentColumn++)
        {
            var value = ReadCell(spreadsheet, currentColumn, row);

            if readOptions.HasFlag(ReadOptions.ReadUntilCellError))
            {
                // Cell has errors, so we exit from the loop
                if (value == null) break;
            }

            values.Add(value);
        }
    }
    catch (ElementNotFoundException)
    {
        // The row is terminated
        // so we exit the loop withouth loggin any
    }

    return values;
}

Ultimately I realized there's never actually a need to check the ReadUntilEmpty flag, so you could probably just drop the Enum and change ReadUntilError to a Boolean with a default value of false.

Abstracting this to work on columns instead of rows is easy. The logic doesn't change at all. You just call it with the row number passed into the column argument and the column number passed into the row argument. So, really, naming the hard part and I'm drawing a blank on any actually useful names, but for the sake of giving an example...

public IEnumerable<string> ReadRow(string spreadsheet, int iteratorIndex, int secondaryIndex, ReadOptions readOptions = ReadOptions.ReadUntilEmpty)
{
    var values = new List<string>();

    try
    {
        for (var index = iteratorIndex; ; index++)
        {
            var value = ReadCell(spreadsheet, index, secondaryIndex);

            if readOptions.HasFlag(ReadOptions.ReadUntilCellError))
            {
                // Cell has errors, so we exit from the loop
                if (value == null) break;
            }

            values.Add(value);
        }
    }
    catch (ElementNotFoundException)
    {
        // The row is terminated
        // so we exit the loop withouth loggin any
    }

    return values;
}

One final note: I'm not entirely comfortable with the fact that the catch block doesn't actually contain any code. It feels a bit hacky.


Map associative array to another array php

array_replace() is the perfect call here -- it can be used to overwrite the master array with the array containing actual integer values.

Code: (Demo)

var_export(array_replace(array_map('intval', $all_states), $country_states));

To streamline the process futher, you should declare your master list with 0 values instead of null values, then you can omit the array_map() call like this:

Code: (Demo)

var_export(array_replace($all_states, $country_states));

Additional suggestions, caveats, and considerations:

You might reconsider your variable names, as they don't seem to do a great job of describing the data that they contain.  $all_states might be $statesLookup or $statesDefault.  I don't know what is being counted in the second array, but $country_states might be better declared as $state_counts or something.
If $country_states has any elements with keys that are not represented in $all_states, then these new elements WILL be appended to the end of the output array.  If this is a legitimate concern, you can call array_intersect_key($country_states, $all_states) to filter out any expected elements.
The order of the elements in the output array will be ordered by $all_states.  No matter what order the country_states are in.


You can build up the string like this:

def animation(counter, length):
    stage = counter % (length * 2 + 2)
    if stage < length + 1:
        left_spaces = stage
    else:
        left_spaces = length * 2 - 1 - stage
    return '[' + ' ' * left_spaces + '=' + ' ' * (length - left_spaces) + ']'

for i in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation(i, 6))
    sys.stdout.flush()
    time.sleep(0.2)

Alternatively store the animation strings in a tuple or list:

animation_strings = ('[=      ]', '[ =     ]', '[  =    ]', '[   =   ]',
                     '[    =  ]', '[     = ]', '[      =]', '[      =]',
                     '[     = ]', '[    =  ]', '[   =   ]', '[  =    ]',
                     '[ =     ]', '[=      ]')
for i in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation_strings[i % len(animation_strings)])
    sys.stdout.flush()
    time.sleep(0.2)

You can replace the animation function with cycle from itertools:

import sys, time
from itertools import cycle
animation = cycle('[=      ]', '[ =     ]', '[  =    ]', '[   =   ]',
                  '[    =  ]', '[     = ]', '[      =]', '[      =]',
                  '[     = ]', '[    =  ]', '[   =   ]', '[  =    ]',
                  '[ =     ]', '[=      ]')
# alternatively:
# animation = cycle('[' + ' ' * n + '=' + ' ' * (6 - n) + ']'
#                   for n in range(7) + range(6, -1, -1))

for _ in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation.next())
    sys.stdout.flush()
    time.sleep(0.2)

Finally, you could make your own generator function.

def animation_generator(length):
    while True:
        for n in range(length + 1):
            yield '[' + ' ' * n + '=' + ' ' * (length - n) + ']'
        for n in range(length + 1):
            yield '[' + ' ' * (length - n) + '=' + ' ' * n + ']'

animation = animation_generator(6)
for _ in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation.next())
    sys.stdout.flush()
    time.sleep(0.2)

EDIT: made the above suggestions less reliant on global variables


My suggestions focus on style issues and pointless code and assume you're using a modern compiler.

In the identification division and environment division:

Delete the comment paragraphs. They were deleted from the standard 15 years ago and have been obsoleted by version control systems.
Rather than use the TITLE statement, name your program FIZZBUZZONACCI. All contemporary compilers support program-names longer than six characters.
Delete the non-functional SOURCE- and OBJECT-COMPUTER paragraphs.

In the data division:

WS-LIMIT is a constant, so it's good idea to declare it as such. Change its declaration to

01  WS-LIMIT CONSTANT AS 10.

or, if your compiler doesn't support that, try the common non-standard extension:

78  WS-LIMIT VALUE 10.

Some of the variables begin with WS- and some don't. I suggest getting rid of the WS- prefix: there's nothing to gain here from indicating a variable is in working-storage.
Similarly, there's nothing to gain from putting variables in the WS-STORAGE, COUNTERS and REMAINDERS group (except for the OCCURS items).

In the procedure division:

Get rid of the redundant END-COMPUTE's. They're only needed for the SIZE ERROR handlers and clutter the code otherwise.

Quuxplusone raises a good point that FIZZ and BUZZ aren't strictly necessary. You could rewrite the EVALUATE like so, and not hide the meaning of FIZZ and BUZZ in the data division:

EVALUATE mod-three ALSO mod-five
    WHEN 0 ALSO 0
        DISPLAY "FizzBuzz"
    WHEN 0 ALSO ANY
        DISPLAY "Fizz"
    WHEN ANY ALSO 0
        DISPLAY "Buzz"
    WHEN OTHER
        DISPLAY current-num
END-EVALUATE


Although you didn't explicitly ask this (and I should now, as I am you) it's worthwhile to first look at why the first piece of code doesn't work, and why the approach is ill-advised.

Observable.ToEnumerable() has a fundamental problem in that it doesn't (cannot) know when the consumer of the resulting IEnumerable is going to enumerate. As a result, it is forced to buffer all the values that the observable is producing, until the consumer is kind enough to fetch them. Essentially, this produces a hidden producer/consumer model involving two threads. If the consumer is "sufficiently fast", the overhead of this may not be noticeable, but it's always there. Whenever you find yourself using Observable.ToEnumerable(), you're probably doing something wrong.

The second approach, where we build an enumerable sequence of observables and then .Concat() works (and I can't see any potential problems with it in terms of multiple subscriptions or cancellation), but has more overhead than necessary in that it produces a separate Observable for every single point in time, with each of these producing a single value. This wouldn't be necessary if we had a single observable to produce the values in order, and that's essentially what the third piece of code achieves.

The third piece of code is a tad cryptic if you don't see what overload of .Generate() it's calling. We can make this clearer by adding the parameter names:

Observable.Generate(
  initialState: getScheduleTimes().GetEnumerator(),
  condition: e => e.MoveNext(),
  iterate: e => e,
  resultSelector: e => e.Current,
  timeSelector: e => e.Current
);

The timeSelector parameter is documented rather sparsely as "the time selector function to control the speed of values being produced each iteration". Paraphrasing the actual implementation and assuming an implicit scheduler, .Generate() produces an observable that does this:

var dueTime = default(DateTimeOffset);
bool first = true;
var state = initialState();
if (hasResult) {
    observer.OnNext(result);
}
if (first) {
    first = false;
} else {
    state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
    result = resultSelector(state);
    dueTime = timeSelector(state);
    scheduler.Schedule(dueTime, Generate(...));
} else {
    observer.OnCompleted();
}

In the actual implementation, scheduling the tail-recursive call is more involved than this. If we substitute in our actual arguments:

var enumerator = getScheduleTimes().GetEnumerator();
if (hasResult) {
    observer.OnNext(result);
}
if (first) {
    first = false;
} else {
    enumerator = enumerator;
}
hasResult = enumerator.MoveNext();
if (hasResult) {
    result = enumerator.Current;
    dueTime = enumerator.Current;
    scheduler.Schedule(dueTime, generate(...));
} else {
    observer.OnCompleted();
}

So this is almost like a regular enumeration, but with the twist that each value we produce is also used as the time at which it should be produced.

There's a slight niggle in that, unlike the foreach pattern, this application of .Generate() will not call IEnumerator.Dispose() like an enumeration is supposed to. In this case, that's not a problem since we're using an iterator and those always have do-nothing Dispose() implementations, but if you were getting the times from another source, you would need to dispose them. That's exactly what Observable.Using() is for. If we put this together in a little extension method that works like Observable.Timer(), but for more than one point in time:

public static class ObservableExtensions {
  public static IObservable<DateTimeOffset> Timers(
    IEnumerable<DateTimeOffset> sequence
  ) {
    return Timers(sequence, Scheduler.Default);
  }

  public static IObservable<DateTimeOffset> Timers(
    IEnumerable<DateTimeOffset> sequence,
    IScheduler scheduler
  ) {
    return Observable.Using(
      () => sequence.GetEnumerator(),
      e => Observable.Generate(
        initialState: e,
        condition: ee => ee.MoveNext(),
        iterate: ee => ee,
        resultSelector: ee => ee.Current,
        timeSelector: ee => ee.Current,
        scheduler: scheduler
      )
    );
  }
}

And this would be my preferred way of doing it: using an IEnumerable allows us to test the result of code that produces a schedule in a simple way, while providing an IScheduler overload still allows us to test observable sequences as a whole using the TestScheduler if we are so inclined.


Your LINQ is fine.  All you're doing is simple navigation of an XDocument.  There's isn't any more you can do with LINQ there.  However, there are still some improvements that can be made.

Borrowing from janos' answer, you can create a helper method GetWords that takes XDocument xdoc and string name as parameters:

private List<string> GetWords(XDocument xdoc, string name)
{
    var words = from wordList in xdoc.Root.Elements("Word")
                select wordList.Element(name).Value;
    return words.ToList();
}

You can store the XML path as a constant at the class level:

private const string _cXmlPath = @"C:\Users\Jesse\Source\Repos\AsyncSpeechSynth\EJCTest\XMLControlLibrary\newDictionary.xml";

You can get rid of magic strings.

You can use auto properties.

Edit: You can rename the xmlDataLoad method using UpperCamelCase and to start with a verb.  Thanks @BCdotWEB and @RobH.

The new version of your class looks like this:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private const string _cXmlPath = @"C:\Users\Jesse\Source\Repos\AsyncSpeechSynth\EJCTest\XMLControlLibrary\newDictionary.xml";
    private const string _cWordName = "Word";
    private const string _cEnglishName = "English";
    private const string _cRomajiName = "Romaji";
    private const string _cJapaneseName = "Japanese";

    public MainWindow()
    {
        InitializeComponent();
    }

    private void LoadXmlData()
    {
        XDocument xdoc = XDocument.Load(_cXmlPath);

        engList.ItemsSource = GetWords(xdoc, _cEnglishName);
        romList.ItemsSource = GetWords(xdoc, _cRomajiName);
        jpnList.ItemsSource = GetWords(xdoc, _cJapaneseName);
    }

    private List<string> GetWords(XDocument xdoc, string name)
    {
        var words = from wordList in xdoc.Root.Elements(_cWordName)
                    select wordList.Element(name).Value;
        return words.ToList();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        LoadXmlData();
    }

    public class WordList
    {
        public string English { get; set; }
        public string Romaji { get; set; }
        public string Japanese { get; set; }
    }
}


Your structure seems adequate, but there are a couple of mistakes, and some new language syntax in 3.3 that will make things even clearer:

That name!

def inorder_gen(self, node):

The name does make it obvious what order you're using. And it also explains that you're writing a generator - which is putting implementation details in the public interface. Don't do that. You could go with inorder(), but even better would be to make your class iterable using the standard Python approach. See this SO answer for an example of how.
You were off to a good start ...

if node is None:
    return
if node.left != None:

... but then you tried to use != None. Use is None or is not None instead. (Like you did on the first line!)
Use Python's yield from expression to connect a nested generator to your caller. This code:

if node.left != None:
    for v in self.inorder_gen(node.left):
        yield v
yield node.val
if node.right != None:
    for v in self.inorder_gen(node.right):
        yield v

Becomes this:

yield from self.inorder_gen(node.left) if node.left is not None else ()
yield node.val
yield from self.inorder_gen(node.right) if node.right is not None else ()

And if your nodes default to truthy (which most objects do), you can replace if node.left is not None with if node.left, for more readability!

yield from self.inorder_gen(node.left) if node.left else ()
yield node.val
yield from self.inorder_gen(node.right) if node.right else ()

Bonus: If you make your TreeNode class iterable, as mentioned in #1, and you use yield from as mentioned in #3, you can make your code even smaller! Since the nodes are iterable, and since yield from will accept an iterable, you can yield from the nodes directly, like this:

# NOTE: This has to be on the node class, so if you can't change
# that, it won't work. (But maybe you could subclass the TreeNode?)

def __iter__(self):
    if self.left: yield from self.left
    yield self.val
    if self.right: yield from self.right

(In fairness, this last example came from the PEP proposing the yield from syntax: http://www.cosc.canterbury.ac.nz/greg.ewing/python/yield-from/yf_current/Examples/binary_tree.py, and see overview page here: http://www.cosc.canterbury.ac.nz/greg.ewing/python/yield-from/yield_from.html)


Don't return if there is an error, throw the error.

if(i<0 || j< 0) {
    throw new Error("Invalid Index");
}

if(i>rowLimit || j> columnLimit){
    throw new Error("Index out of bounds");
}

Don't assume an array has elements

(i.e.: let columnLimit= myArray[0].length-1; will throw a TypeError if there are no elements in the list)

Play it safe.

//get first element in list,
//if it doesn't exist set it to a default empty array
const [column = []] = myArray;
const columnLimit = column.length;

const before let and let before var

When declaring variables, always define them with const by default. You only use let when you expect that variable in question is likely to mutate. And never use var unless you have a good reason to.

Note: const arr = []; arr.push(1) mutates the array but not the variable

  am I covering all the edge cases ?

Yes, you are.

Assuming that the two dimensional array has columns of equal length

  Just wanted to know if there is a better way to solve this problem

There are only 8 elements max possible around a single element, and yet for every element you check to see if (i,j) != (x,y).

To solve this "problem", simply add all values (even with (i,j))

Then before returning subtract the element at (i,j)

for(let x = Math.max(0,i-1); x<=Math.min(i+1,rowLimit); x++){
  for(let y = Math.max(0,j-1); y<=Math.min(j+1,columnLimit); y++){
        sum+=myArray[x][y];
   }
 }

return sum - myArray[i][j]

Is this better? Well, it's 9 additional conditions VS an extra addition and subtraction.


How to optimize this majority vote method

This can be solved with a simple groupby operation, which can tell you how often each combination appears. Then you just need to compare this with your n and filter the data:
key = ["begin", "end", "case"]
n = len(systems) // 2

mask = df.groupby(key)["system"].count() > n

df.set_index(key)[mask] \
  .reset_index() \
  .drop(columns="system") \
  .drop_duplicates()

#    begin  end  case
# 0     10   14  0365

This outputs the same as your code on my machine, but not the same as the example output you gave in your question (which I think is wrong).
Note that I used integer division // instead of float division / and manually casting to int.
In general, if you find yourself using itertuples in pandas, you should think very hard if you cannot achieve your goal in another way, as that is one of the slowest ways to do something with all rows of a dataframe.


I think a singleton/enum like pattern would be beneficial. The curious part is the IMutablePriceConfiguration object seems to vary based on the situation.

Remove the IMutablePriceConfiguration as a dependency for the cost strategy objects.

Next:

public sealed class EquipmentType
{
    public static readonly Heavy = new EquipmentType(1, "Heavy", new HeavyRentalCostStrategy());
    public static readonly Specialized = new EquipmentType(2, "Specialized", new SpecializedRentalCostStrategy());
    public static readonly Regular = new EquipmentType(3, "Regular", new RegularRentalCostStrategy());

    public static readonly IEnumerable<EquipmentType> All = new EquipmentType[]
    {
        Heavy,
        Specialized,
        Regular
    };

    public static EquipmentType Find(int id)
    {
        return All.SingleOrDefault(e => e.Id == id);
    }

    public static EquipmentType Find(string name)
    {
        return All.SingleOrDefault(e => e.Name == name);
    }

    private IRentalCostStrategy CostStrategy { get; set; }
    public string Name { get; private set; }
    public int Id { get; private set; }

    private EquipmentType(int id, string name, IRentalCostStrategy costStrategy)
    {
        Id = id;
        Name = name;
        CostStrategy = costStrategy;
    }

    public double CalculateRentalCost(IMutablePriceConfiguration mutablePriceConfiguration)
    {
        return CostStrategy.CalculateRentalCost(mutablePriceConfiguration);
    }
}

The IMutablePriceConfiguration becomes an argument to the CalculateRenderCost method on the EquipmentType class
The EquipmentType class has a private constructor so you are guaranteed to only have those three instances available. No one can incorrectly (or maliciously) create equipment types and their cost strategies.
You can access each equipment type in an enum-like syntax:

EquipmentType.Regular

You can find by id or name:

EquipmentType.Find(1);
EquipmentType.Find("Specialized");

You can blindly loop over all available equipment types:

foreach (var equipmentType in EquipmentType.All)
{
    // ...
}

As long as you have an IMutablePriceConfiguration object, you can blindly call the CalculateRentalCost method and get a result back. No need for ifs or switchs peppered all over your code.


Running a simulation for all unique combinations of a range of parameters

For a full factorial experiment, you may want to avoid constructing the whole matrix just to get the factor levels for a single experiment, especially if you have a large number of factors and levels and you are using a language where loops are not very efficient. Here is how you can do it using mod.

In a single factor experiment, you run the experiment over the range of values of the first factor. This is easy to do using mod: use mod(sim_ind, nlevels_factor1), or

mod(sim_ind-1, nlevels_factor1) + 1

if you want to start at one (since MATLAB indexes arrays from 1).

To extend the experiment to a second factor, you want this new factor to have its first level value for the first nlevels_factor1 runs, then its second level value for the second nlevels_factor1 runs, etc... all the way up till the nlevels_factor1*nlevels_factor2th run.

You'll use mod again, but now you want the first argument to mod to be 1 for the first nlevels_factor1 runs, 2 for the next nlevels_factor1 runs, etc. So instead of passing the sim_index (or sim_index-1) to mod, you'll pass ceil(sim_index/nlevels_factor1), which has value 1 for the first nlevels_factor1 runs, 2 for the next nlevels_factor1 runs, etc. Your factor level for the second factor will be

mod(ceil(sim_index/nlevels_factor1) - 1, nlevels_factor2) + 1

if you want to start from 1.

You can continue this procedure to extend your experiment to any number of factors. Just make the divisor inside the ceil equal to the product of the number of levels of all of the previous factors.

Here's what it might look like for your example:

% getting sim_ind from env
AI = getenv('PBS_ARRAYID');
sim_ind = str2num(AI);

time_slots = 40000;

% parameter vectors
up_down_ratio_arr = [1];
traffic_load_arr = [ 0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10, 100, Inf ];
blocked_modes_ind_arr = [1 2 3];
traffic_model_arr = [1 2];

size_up_down_ratio = length(up_down_ratio_arr);
size_traffic_load  = length(traffic_load_arr);
size_blocked_modes = length(blocked_modes_ind_arr);
size_traffic_model = length(traffic_model_arr);

% total number of unique combinations
uniq = size_up_down_ratio*size_traffic_load*size_blocked_modes*size_traffic_model;

% repeat each value once: 1,2,3,4,5,6,7,8,9,10,1,2,3,4...
i_up_down_ratio = mod(sim_ind - 1,size_up_down_ratio) + 1;
% repeat each value size_so_far times:
% 1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3...
size_so_far = size_up_down_ratio;
i_traffic_load  = mod(ceil(sim_ind/size_so_far) - 1, size_traffic_load) + 1;
size_so_far = size_so_far*size_traffic_load;
i_blocked_modes  = mod(ceil(sim_ind/size_so_far) - 1, size_blocked_modes) + 1;
size_so_far = size_so_far*size_blocked_modes;
i_traffic_model = mod(ceil(sim_ind/size_so_far) - 1, size_traffic_model) + 1;

up_down_ratio = up_down_ratio_arr(i_up_down_ratio);
traffic_load  = traffic_load_arr(i_traffic_load);
blocked_modes_ind = blocked_modes_ind_arr(i_blocked_modes);
traffic_model = traffic_model_arr(i_traffic_model);

% call the routine
MainCode_Single_Backahul_Cell_Sch(time_slots, up_down_ratio, traffic_load, blocked_modes_ind, traffic_model, ceil(sim_ind/uniq) );


You can replace

spawn (?MODULE, pingCircle, [Name, nobody] )

with

spawn (fun() -> pingCircle(Name, nobody) end)

This action allows do not export pingCircle/2 from the module.
It is also recommended to use spawn_link instead of spawn, because it helps to avoid lost processes.


Is this the best way to reverse a string in C (not in place)?

What about this:

/*
IN: string to have characters reversed
OUT: string containing characters in reversed order
*/
char* reverStr(const char *str)
{
        int index=strlen(str);
        char* revStr = (char*)malloc(index--);
        int destIndex=0;
        while (0<=index)
            revStr[destIndex++] = str[index--];
        revStr[destIndex]=0;
        return revStr;
}


C++ delegate implementation with member functions

Fatal bugs:

A big issue is the fact that you take a copy of the object in the function in this line:

    std::function < void (Class, Params...) >  f = func;

This needs to be Class& at the very least. Otherwise, invocations of handlers would operate on copies of the intended objects. See demonstration here: Live On Coliru with debug information showing copies are being made.

Conceptual issues:

you are using a hash for equality. This is a conceptual flaw: hashes can have collisions. Hashes are used to organize large domains into a smaller set of buckets.

  this could really be considered a fatal bug, as disconnect might disconnect unrelated handlers here

you're wrapping your member-function pointers in a std::function. Twice. This is gonna be very bad for anything performance-sensitive
you are abusing std::function for generic calleables. Instead, use perfect storage on user-supplied calleables (why bother whether it's std::mem_fun_ref_t, a bind-expression, a lambda or indeed a function pointer?). This way

you don't incur the overhead of type erasure and virtual dispatch that comes with std::function, unless your situation requires it
you don't have to bother with the annoying details that you have to, now

you don't need to treat member functions differently to begin with (std::bind to the rescue)
you don't need to rely on implementation defined implementation of pointer-to-member-function

you're using implementation defined behaviour to get a hash of a pointer-to-member-function (see previous bullet)
your less-than generic solution works for pointer-to-member-function only. This you already knew. But, you may not have realized, it doesn't work for const or volatile qualified member functions.
your Delegate class tries to "guess" identity of registered handlers. In fact, the registering party should be responsible for tracking exactly which registration it manages. A cookie-based design would be most suitable here, and certainly takes all the implementation defined behaviour out of the equation (as well as immediately making it clear what happens when the same handler gets registered multiple times). See the "more drastic rewrite" below.

Style, Efficiency

Your Key class isn't the Key. It's the collection Entry (Key + Function).
Your Key defines operator==. An object that's equatable necessitates linear search to do a lookup. Instead, define a weak total ordering (using operator<) so you can use tree-like data-structures. See below for a sample that uses std::tie() to quickly implement both relational operators (the first version).
Also, need to use Key::operator== instead of just comparing m_object and m_funcHash again (encapsulation)
Your Key stores the object, but the object is also part of FunctionType implicitely, because you capture it by reference. You should probably remove the redundancy.
Your disconnect lookup is ... not very effective:

linear search? really?
no early out? (it's unclear how you really want repeatedly registered callbacks to be handled, but I'd say

 del.connect(some_handler);
 del.connect(some_handler);
 del.disconnect(some_handler); // disconnect 1 of the two
 del.disconnect(some_handler); // disconnect the other

would be the principle of least surprise)
your i-- invokes unsigned integer wraparound. Now, this is not undefined behaviour, but it's bad style IMO. You could use

for(unsigned int i = 0; i < m_functions.size(); ) {
    auto key = m_functions[i];
    if(key.m_funcHash == hash && key.m_object == &obj) {
        m_functions.erase(m_functions.begin() + i);
    } else
    {
        ++i;
    }
}

instead.
the loop crucially depends on m_functions.size() being evaluated each iteration. This is inefficient and error-prone

  Guideline: Whenever you see a loop that became... non-trivial and obscure like this, it's a sure sign you need to use an (existing) algorithm

Fixing just these elements: just use a better datastructure, like

struct Key {
    void*         m_object;
    size_t        m_funcHash;
    // no ctor: let just just be an aggregate

    bool operator==(const Key& other) const { return key() == other.key(); }
    bool operator< (const Key& other) const { return key() <  other.key(); }
  private:
    // trick to make it trivial to consistently implement relational operators:
    std::key<void* const&, size_t const&> key() const { return std::tie(m_object, m_funcHash); }
};

std::multimap<Key, FunctionType> m_functions;

The whole disconnect function becomes trivial:

template <typename Class>
void disconnect(Class& obj, void (Class::*func)(Params...)) {
    m_functions.erase(Key { &obj, getHash(func) });
}

Fixed version(s)

Here's a version that uses the multimap approach (fixing just the style/efficiency issues) Live On Coliru

A more drastic rewrite

would look like this: Live On Coliru

This version alters the design so most (if not all) the problems are sidestepped. It uses boost's stable_vector to do a cookie-based design. This moves the burden to track handler identities on the registering parties (where it belongs after all).

#include <functional>
#include <iostream>
#include <boost/container/stable_vector.hpp>

template <typename... Params>
class Delegate {
private:
    typedef std::function<void(Params...)> Handler;
    typedef boost::container::stable_vector<Handler> Vector;
    Vector m_handlers;
public:
    typedef typename Vector::const_iterator cookie;

    cookie connect(Handler&& func) {
        m_handlers.push_back(std::move(func));
        return m_handlers.begin() + m_handlers.size() - 1;
    }

    template <typename... BindArgs, typename Sfinae = typename std::enable_if<(sizeof...(BindArgs)>1), void>::type>
    cookie connect(BindArgs&&... args) {
        return connect(Handler(std::bind(std::forward<BindArgs>(args)...)));
    }

    void disconnect(cookie which) {
        m_handlers.erase(which);
    }

    template <typename ... Args> void operator()(Args...args) {
        for(auto const& handler : m_handlers)
            handler(args...);
    }
};

//////////////////////////////////
// demonstration
#define CV volatile const
struct BaseClass {
    virtual void print(const std::string& str) CV = 0;
};

struct A : BaseClass {
    A() {}
    void print(const std::string& str) CV { std::cout << " Class A : Print [" << str << "]\n"; }
};

struct B : BaseClass {
    B() {}
    void print(const std::string& str) CV { std::cout << " Class B : Print [" << str << "]\n"; }
};

using namespace std::placeholders;

int main() {
    Delegate <const std::string&> delegate;
    A CV a;
    B CV b;
    auto acookie = delegate.connect(&A::print, std::ref(a), _1);
    auto bcookie = delegate.connect(&B::print, std::ref(b), _1);

    delegate("hello");
    delegate("world");

    delegate.disconnect(acookie);
    delegate("bye world");

    delegate.disconnect(bcookie);
    delegate("nobody there.");  // should not print anything
}


Internal function that determines when to resize by width or height in a Image Resizer utility

You can replace this:

if (computeWidth)
    return sourceDimension.ResizeWidth(maxWidth);

else if (computeHeight)
    return sourceDimension.ResizeHeight(maxHeight);

else return sourceDimension;

with this:

if (computeWidth)
    return sourceDimension.ResizeWidth(maxWidth);
if (computeHeight)
    return sourceDimension.ResizeHeight(maxHeight);
return sourceDimension;

I would rename the method and input parameters, as it would add more sense to the method name and input parameters.

private Dimention2D  ReSize(Image image, int requireWidth, int requireHeight);


Finding the smallest missing positive number in an array

Bugs

The implementation incorrectly gives -1 for all these input:

[0] should return 1
[1] should return 2
[2] should return 1
[0,2,2,1,1] should return 3
[1,2,2,1,3,1,0,4,0] should return 5

Improving the algorithm

The algorithm you used is \$O(n)\$ time and \$O(n)\$ space.
If you don't mind modifying the input array,
then you could reuse it as the storage,
making the algorithm \$O(1)\$ space.

Consider this alternative algorithm:

If the array is empty, return 1
Loop over the array indexes

While input[i] - 1 is a valid array index and not in the correct position, and input[input[i] - 1] is not in the correct position, then swap the elements i and input[i] - 1.

Loop over the array indexes again, and when you find a value not in the correct position, then return i + 1.
Return the last value + 1.

The logic behind this algorithm:

Swap elements into the correct position to get a sequence of positive integers 1, 2, 3, ...
Ignore values that cannot be in this array (<= 0 or too high index)
The beginning of the array will be filled with correct sequence values, gaps will be filled with junk, and the second looping pass will short-circuit on the first incorrect value

Strange coding style

Although these type declarations compile, they are not recommended:

public static void main(String args[]) {

public static int findSmPositive(int input[]) {

The recommended writing style:

public static void main(String[] args) {

public static int findSmPositive(int[] input) {

Also,
the code formatting style is not great, at many places it's too compact.
I suggest to copy paste into an IDE like IntelliJ or Eclipse and use the auto-formatting function to reformat nicely.

Testing your improvements

The problem description seems to match this one on leetcode.
After you implement your improvements,
I suggest posting there to verify the correctness of your implementation.

https://leetcode.com/problems/first-missing-positive/


Use the params keyword

//The new Logger for the exe
static void WriteLog(string exception, int status, params string[] arguments)
{
    string logFile = string.Format("D:\\TempLogs\\Grep-{0:yyyy-MM-dd_hh-mm-ss-tt}.log", DateTime.Now);
    StreamWriter grepLog = new StreamWriter(logFile, true);
    grepLog.WriteLine("Status: " + status.ToString() + " (0 for PASS, 1 for FAIL)");
    grepLog.WriteLine("Exception: " + exception);
    // TODO: Consider logging "no arguments" if that is the case.
    for(int i=0; i<arguments.Length; i++)
    {
        grepLog.WriteLine("Argument " + i + ": " + arguments[i]);
    }
    grepLog.Close();
}

Use an enum for status

Since the status has 3 states, use an enum for it. This will help you avoid mistakes.

Why do you try-catch while logging?

If you don't see any particular possibility for the log to fail, then simply assume it and don't try-catch the logging.

If you want the logging to no matter what not break the application with exceptions, and you cannot fix those exceptions (why?), then I would suggest putting the try-catch inside the logging method.

Main - exception should catch, log, and return

I would have the exception log the error and return, instead of continuing normally.

Alternatively, I would catch, log, and re-throw: try { ... } catch (Exception e) { WriteLog(...); throw; }

Use camelCase for local variables

StreamWriter grepLog;
Using a starting underscore (_grepLog) is also common for private fields.

Follow the de-facto conventions. (See e.g. https://stackoverflow.com/questions/2976627/on-c-sharp-naming-conventions-for-member-variables )

Avoid Hungarian Notation

In string strGrepLogFileName, the part "str" brings nothing new.
If you change the variable's type (e.g. to an Uri) without changing its meaning, you should not have to rename the variable, and using Hungarian Notation you do.


Both suffer (equal amounts) from the problem that when you call them, the compiler has to go instantiate a new function from the template. The code all ends up inlined after optimization, but it does make more work for the compiler than something like

#define NELEM(x) (sizeof(x) / sizeof (x)[0])

The benefit of array_size_2 is that if you try to call it as

int *p = nullptr;
std::vector<int> v;
size_t a = array_size_2(p);  // ERROR
size_t b = array_size_2(v);  // ERROR

the compiler will reject the call as ill-formed. Whereas if you do the same thing with array_size_1 or NELEM, you'll just get for example sizeof(int*) / sizeof(int) or sizeof(vector<int>) / sizeof(int), which isn't meaningful.

So array_size_2 saves you from accidentally writing something meaningless. Especially in cases like

int foo(int a[]) {
    return array_size_1(a);  // OOPS!
}

where int a[] is just syntactic sugar for int *a and there's no actual array in existence at all.


Maintaining a single collection subdivided by a value's property

What you suggested is absolutely fine. There isn't any unnecessary copying. Although, to make things simpler, I suggest using LINQ extension methods for filtering.

using System.Linq;

public IEnumerable<Actor> ReplicatedActors
{
    get { return allActors.Where(actor => actor.Replicates); }
}

public IEnumerable<Actor> LocalActors
{
    get { return allActors.Where(actor => !actor.Replicates); }
}

You'll still have to remove actors from allActors, these two are separate read-only lists of actors derived from the list of all actors.

Edit: I also suggest changing your actor removal loop to be a foreach loop for simplicity.

foreach (var actor in actorsToRemove)
{
    allActors.Remove(actor);
}
actorsToRemove.Clear();


Python object-oriented pipe cooling simulations

Immediately you have bad names of constants. R_w, R_f, T_0? These are meaningless. If they correspond to technical terms, then make a note of that in a single comment, ideally with a link to somewhere online that they could be roughly explained. But the best response would be actual words:

class PipeSimulator:
    INNER_RADIUS = 0.2  # m
    DIFFERENTIAL_DISTANCE = 0.01  # m
    LENGTH = 25  # m

    # Coefficients (in W/mk)
    WATER_HEAT_LOSS = 0.654
    # AIR_HEAT_LOSS = 0.028
    PIPE_HEAT_LOSS = 0.042

    # Temperature C
    INITIAL_TEMPERATURE = 50
    AMBIENT_TEMPERATURE = 20

Now, you'll notice I changed the names but also the naming style to make it clearer that they're constants. It's important to use this convention. It's useful to note that these are coefficients and what unit they're in (I assume that's what W/mk is) but instead of noting it individually put a single comment header under which they all fall. For units on single constants, simply leaving the unit notation at the end is sufficient.

However, I question whether these should all be constants. Wont you have pipes of differing lengths and inner radius? I'm not familiar with the physics here, but will the coefficients change contextually? It seems like at least some of these values should be initiated as instance attributes with __init__. Indeed, some of them are set by you again later. You'd save some lines by setting up __init__.

To give a simple demo of how that would look, I'll just use inner radius and length:

class PipeSimulator:

    def __init__(self, inner_radius=0.2, length=25):
        self.inner_radius = inner_radius
        self.length = length

pipe1 = PipeSimulator(0.2, 25)
pipe2 = PipeSimulator(0.6, 40)
pipe3 = PipeSimulator()

This way, you can pass different parameters when creating PipeSimulator to get different attributes on your object. I'm also using default parameters, in case you'd want the class to fall back on a default radius on length for when none are supplied (like in pipe3). If this is completely unfamiliar to you, leave a comment and I can explain how it works.

Note that __init__ can have other lines of code too, so if some attributes need to be calculated it's perfectly fine to have them determined in there rather than calculating externally to then assign to your PipeSimulator object.

heat_balance has a complex equation to determine the result. I'd suggest putting in a docstring where you make reference to what this equation is and where it could be found. It would be more readable too if you split the long lines up, calculating only a bit at a time instead of everything thrown together in an unreadable manner. If you wanted to be really neat, heat_in and heat_out could each have their own function that just get called in heat_balance.

The same applies to simulation except that I don't think it's a formula so much as your methods and intentions are not the clearest. What are T and X for? If you gave them better names it would be much easier to follow what they mean. Add a docstring too, explain what is simulated here. Though your question title explains it, nothing in the code itself does.


Project Euler #2: Even Fibonacci numbers

I see a number of things that may help you improve your code.

Make it clear when loops end

The code currently uses while (true) but it doesn't really loop infinitely.  It's better, generally, to have the loop exit condition explicitly stated.  For example we could rewrite your main loop as:

unsigned long total = 0;
while (front <= maxNumber) {
    total += front;
    unsigned long frontPrime = front;
    front = (3 * front) + (2 * back);
    back = (2 * frontPrime) + back;
}

Analyze the mathematics

Your mathematical analysis is correct as far as it goes, but there's a bit easier way to do it.  A bit more algebra will convince you that the series looks like this:

$$a_0 = 0$$
$$a_1 = 2$$
$$a_n = 4a_{n-1} + a_{n-2}$$

Derivation of this sequence

The Fibonacci numbers are defined as:
$$F_0 = 0$$
$$F_1 = 1$$
$$F_n = F_{n-1} + F_{n-2}$$
As you've already noted, the sum of two odd number is even, and the sum of an odd and even number is odd. For the Fibonacci sequence, this means that the sequence of \$O\$ (odd) and \$E\$ (even) looks like this:

$$E, O, O, E, O, O, E, ...$$
In other words, every third term is even.  This gets us to the fact that \$a_n = F_{3n}\$. From this observation, we have this:

$$a_n = F_{3n}$$
$$a_{n-1} = F_{3(n-1)} = F_{3n-3}$$
$$a_{n-2} = F_{3(n-2)} = F_{3n-6}$$
$$a_n = F_{3n-1} + F_{3n-2}$$
Using the definition of the Fibonacci sequence, and expanding the terms on the right, this becomes:
$$a_n = F_{3n-2} + F_{3n-3} + F_{3n-3} + F_{3n-4}$$
Substituting \$a\$ terms for \$F\$ terms, we have:
$$a_n = F_{3n-2} + 2a_{n-1} + F_{3n-4}$$
Expanding the \$F\$ terms on the right again using the definition of the Fibonacci sequence yields:
$$a_n = F_{3n-3} + F_{3n-4} + 2a_{n-1} + F_{3n-5} + F_{3n-6}$$
Again, substitute \$a\$ terms for \$F\$ terms:
$$a_n = a_{n-1} + F_{3n-4} + 2a_{n-1} + F_{3n-5} + a_{n-2}$$
Doing one last substitution and rearranging terms, we get:
$$a_n = 4a_{n-1} + a_{n-2}$$

Code implementation

That means that the outer loop could instead be written like this:

unsigned long back = 0;
unsigned long front = 2;
unsigned long current=0;
unsigned long total = front;
unsigned long maxNumber;
std::cin >> maxNumber;
while (front <= maxNumber) {
    total += current;
    current = 4*front + back;
    back = front;
    front = current;
}
std::cout << total << '\n';

In this scheme \$a_{n-2}\$ is named back and \$a_{n-1}\$ is named front.  Naturally, \$a_n\$ is named current.

Don't recompute values

The sequence is the same every time, so it really doesn't make much sense to recompute values every time.  Better would be to compute them once and save them in a std::vector or std::array. Even better is to compute the values once at compile time.  Given the input range, there are less than 30 terms, which is a very modest storage requirement.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


while found_last_factor == False:

Style is subjective, but I know I'm not the only develop who considers comparisons to Boolean literals to be bad style. while not found_last_factor: is an alternative which I consider preferable.

There are various inefficiencies in this code:

    while found_last_factor == False:
        for f in range(2, int(n/2+1)):
            if n % f == 0 and is_prime(f):
                n /= f
                factors.append(f)
                if is_prime(n):
                    factors.append(n)
                    found_last_factor = True
                    break
    return sorted(factors)

If it were modified to handle repeated prime factors in an inner loop rather than in the outmost loop then

The test is_prime(f) would be unnecessary, because n % f == 0 would already imply the primality of f.
Primes would be discovered in order, removing the need to call sorted.
A lot of unnecessary iterations of f would be saved. You rebutted AJNeufeld's observation on this subject, so consider an alternative perspective: add a line print(f) at the top of the for f loop, and then call prime_factors(1024).

The call to is_prime(n) tests primality by trial division, and is called from a loop which is factoring n by trial division. That's duplication of both code and run time.

/= does floating point division. Use //= for integer division. Similarly int(n/2+1) could be n//2 + 1.


I would suggest a two lines of code solution instead of one. :)
Let me show you first the solution then the explanation.
Solution
private static readonly Lazy<IEnumerable<string>> enumValues = new Lazy<IEnumerable<string>>(() => Enum.GetValues(typeof(AttributesInMethod)).Cast<AttributesInMethod>().Select(option => option.GetDisplayNameENUM()));

private bool IsFound(IEnumerable<SomeAttribute> attributes) => attributes.Select(att => att.Value).Any(enumValues.Value.Contains);

Explanation
Two methods instead of one

You have two kinds of data

A fairly static data, which could be changed only with code change

The mapped values of the enumeration

An absolutely dynamic data, which could change by each and every method call

The IsFound input parameter

You don't need to calculate each and every time the derived data from the enumeration. It should be calculated once and stored for long term.
Usage of Lazy
"It should be calculated once and stored for long term." > That's where the Lazy<T> type comes into play.
All you have to do is to provide a factory method (how to compute the derived data) and then the calculated information should be stored in a long-living variable. Lazy<T> gives us thread-safety so there is a guarantee that it will be calculated only once.
How to derive the data
Enum.GetValues(typeof(AttributesInMethod))
  .Cast<AttributesInMethod>()
  .Select(option => option.GetDisplayNameENUM())

GetValues returns an Array so you have to call Cast<T> to be able to use Linq operator on it.
Composing functions
For each input data check the existence of it in a predefined collection.

For each input data: attributes.Select(att => att.Value)
check the existence of it: .Any(... .Contains)
in a predefined collection: enumValues.Value

All you have to do to compose them to create a new higher level function.


BasketHelper mixes the different aspects of identifying and authenticating users, calculating prices and displaying information. These aspects should be separated. Especially manipulating the view (setting label texts, choosing CSS-formatting etc.) should not be mixed with business logic. The view logic shouldn't need to calculate prices and discounts. It should only work on results calculated somewhere else.

You have a Product class. Why do you not move product related calculations to Product? For instance add a method GetProductCampaignPrice to Product. You could make it a property as well, but since it is not returning a "static" value but depends on other properties, a method seems more appropriate.

public decimal GetProductCampaignPrice()
{
    decimal currencyMultiplier = Currency.GetCurrencyValue(CurrencyCode);
    decimal listPriceTL = ListPrice * currencyMultiplier;
    return listPriceTL * (1 - DiscountRate / 100);
}

Except for the currency calculator the calculation only needs properties of the product itself (CurrencyCode, ListPrice and DiscountRate). An even better design would be to inject a currency calculator into this method in order to remove the dependency on a specific currency calculator.

public decimal GetProductCampaignPrice(ICurrencyCalculator currencyCalculator)
{
    decimal listPriceNormalized = currencyCalculator.ToStandardCurrency(ListPrice, CurrencyCode);
    return listPriceNormalized * (1 - DiscountRate / 100);
}

Also note that I have removed the leading underscore (_) from the local variable. Underscores are used for fields, i.e. "variables" at class or struct level only.

The stuff in helper classes should be kept to a strict minimum and should really on hold things that don’t fit in anywhere else.

Look at your code and try to identify things that you can move to more specific classes.

A possible class integrating product and account related calculations could be called PriceCalculator; this is a much better name than FooHelper and it leads to a better design. Naming is crucial and goes hand in hand with good designs.

Note: If you don't want to or cannot change the Product class (e.g. because it is generated automatically), you could split the class into two partial classes, one holding the data and one with additional methods. You could also create a ProductExtensions class and make the method an extension method

public static class ProductExtensions
{
    public static decimal GetProductCampaignPrice(this Product product,
                                                  ICurrencyCalculator currencyCalculator)
    {
        decimal listPriceNormalized =
            currencyCalculator.ToStandardCurrency(ListPrice, CurrencyCode);
        return listPriceNormalized * (1 - DiscountRate / 100);
    }
}

You can call this method as if it was a member of Product

decimal result = product.GetProductCampaignPrice(currencyCalculator);