Locating empty field groups for saving data

Technically, there is no such thing as if-loops. Your code is just a bunch of if-else statements (sorry, this was the language police speaking)

What your code actually needs, is actually a real loop. Use an array or a list of a record, TLoanProduct and loop through it. Your current approach allows a maximum of six products in one loan, it involves a lot of code duplication which in itself is a code smell, and it could be a bit weird if the values for Product 3 were set but not Product 1.

My Delphi skills are a bit rusty, but consider changing TLoan into an object or a class instead of a pure record. That way you could have the Save method as part of the TLoan object/class.

This is some code for how I think it should look. It's been a long while since I worked with Delphi so this might not be 100% correct code, but it should get you started in the right direction.

TLoanProduct = record
    ProductID: integer;
    ProductTitle: string[80];
    ProductAuthor: string[80];
    Returned: boolean;
end;
TLoan = record
    LoanUniqueId: integer; { of loan record }
    DateDue: TDateTime; { date when products are due to be returned }
    MemberUniqueID: integer; { from MemberDetails File }
    MemberName: string[50]; { from MemberDetails File }
    MemberSecondName: string[50]; { from MemberDetails File }
    AmountBorrowed: integer; { amount of items currently on loan }
    LoanProducts: array [0..5] of TLoanProduct;
end;

...

procedure Save;
{ procedure to locate which field groups are empty so product and loan informati
 - on can be saved }
var i: integer;
begin
  for i := 0 to High(LoanRecords.LoanProducts) do
  if LoanRecords.LoanProducts[i].ProductID = '' then
  begin
    LoanRecords.LoanProducts[i].ProductID := ProductRecords.UniqueId;
    LoanRecords.LoanProducts[i].ProductTitle := ProductRecords.ProductTitle;
    LoanRecords.LoanProducts[i].ProductAuthor := ProductRecords.ProductAuthor;
    Exit; // Exit the method so that this is only applied for one element
  end;
end;


My VB.NET is incredibly rusty but you should write a separate function:

Public Shared Sub ReplaceBracketsWithParentheses(ByRef text As String)
    text = Replace(Replace(text, "[", "("), "]", ")")
End Sub

Calling code will then simply be:

Public Sub removeBadBrackets()
    ReplaceBracketsWithParentheses(ValueCalc)
    ...
End Sub

Note that if you have to replace more than few substrings then a fluid approach may be more readable:

Public Shared Sub ReplaceBracketsWithParentheses(ByRef text As String)
    text = text.Replace("[", "(") _
               .Replace("]", ")") _
               .Replace("{", "(") _
               .Replace("}", "]")
End Sub

If you're translating some sort of mathematical expressions (but not only!) you may also consider to use a Regex.

One word about naming: I don't know the domain you're using this code but to me LLLCalc, LLCalc and so on are not descriptive names (and, anyway, acronyms should be cased PascalCase like LllCalc, the same is true for removeBadBrackets()).


Project Euler 407: Is there any more optimal way to solve this idempotent equation (modulo n ring)?

1. Introduction

The feature of Project Euler that makes it interesting is that solving the problems is rarely a matter of writing down a straightforward algorithm and then optimizing it piecewise until it runs in the available time.

Instead, the problems are deliberately designed with parameters large enough that the straightforward algorithm will take many hours or days, but if you can gain some insight into the mathematical structure of the problem, then you can find a better algorithm that radically improves the runtime.

So if you're still at the "hours or days" stage then it's no good trying to speed up the code you've got. You might be able to speed it up by a factor of five or ten by piecewise optimizations, but probably no more than that. No, I'm afraid we need to use ... math.

2. Getting started

But what if you've already applied all the math you know, and you're too impatient to read a number theory textbook? How do you figure out where to look?

First, it's worth working your way through the Project Euler problems at least approximately in order, rather than diving straight in to the latest problems. The earlier problems often introduce key concepts (for example, Euler's totient function and how to compute it simultaneously for many numbers by sieving) in straightforward contexts, so that when in later and harder problems these concepts are needed, you'll already be familiar with them.

Second, many Project Euler problems involve at their heart a sequence of numbers. You can very often get useful clues about this sequence by computing the first few numbers in the sequence and then searching for them in the On-Line Encyclopedia of Integer Sequences.

In the case of problem 407, the first few elements of the sequence are 0, 1, 1, 1, 1, 4, 1, 1, 1, 6, and this is sequence A182665, which contains a link to this answer by Robert Israel on math.stackexchange.com.

3. Computing the sequence

(This follows Robert Israel's presentation, but with the notation changed to match the Project Euler problem.)

If \$a^2 \bmod n = a\$, then \$a(a − 1) \bmod n = 0\$.

So if \$n\$ can be factored as \$p_1^{e_1} p_2^{e_2} \ldots\$ then each \$p_i^{e_i}\$ must divide either \$a\$ or \$a − 1\$ (because each \$p_i\$ can divide into at most one of \$a\$ and \$a − 1\$).

Therefore \$n = uv\$, where \$u\$ and \$v\$ are coprime and \$u\$ divides into \$a\$ and \$v\$ divides into \$a − 1\$.

Let \$a = uw\$. Since \$a < n\$ then \$w < v\$ and \$uw = 1 \pmod v\$ therefore \$w = u^{−1} \pmod v\$.

So our plan, in pseudocode, is:

Factorize all the integers up to \$10^7\$ by sieving.
For each integer \$n\$:
  if \$n\$ is a prime or prime power, then \$a = 1\$;
  otherwise \$n\$ is a product of two or more distinct primes, so:
    for each way to factorize \$n = uv\$ with \$u\$, \$v\$ coprime:
      find \$w = u^{−1} \bmod v\$.
    \$a\$ is the maximum of \$uw\$ for all such \$uv\$.

Which might just be doable in the time available.

Now at step 6 we have to find the multiplicative inverse of \$u\$ modulo \$v\$. There are a couple of algorithms for finding the modular multiplicative inverse: normally we would use the extended Euclidean algorithm, but here the method using Euler's theorem is attractive because we know that \$u\$ is coprime to \$v\$. So \$u^{−1} = u^{φ(v)−1} \pmod v\$ where \$φ\$ is Euler's totient function.

Since we are sieving for the factorizations, we can sieve for the totients at the same time.

4. Python code

This runs in about 2½ minutes on my computer under pypy, so I didn't manage to squeeze it inside Project Euler's one-minute time limit. But at this point we're within sight of the goal, so it might be possible to get there by carrying out piecewise optimizations.

from collections import defaultdict
from functools import reduce
from itertools import combinations
from operator import mul

def factorize(n):
    """Factorize the numbers up to n, returning a pair (factorization,
    totient).

    factorization is a dictionary mapping each composite i below n to
    a list of numbers p ** e where p is a prime and e is the exponent
    of p in the factorization of i.

    totient is a list whose i'th element is Euler's totient function
    applied to i (the count of numbers less than i which are coprime
    to i).

        >>> from pprint import pprint
        >>> f, t = factorize(10)
        >>> pprint((dict(f), t))
        ({4: [4], 6: [2, 3], 8: [8], 9: [9], 10: [2, 5]},
         [0, 1, 1, 2, 2, 4, 2, 6, 4, 6, 4])

    """
    n = n + 1
    f = defaultdict(list)
    t = list(range(n))
    for p in range(2, n):
        if p not in f:
            t[p] = p - 1
            for i in range(p + p, n, p):
                j, k = i, 1
                while j % p == 0:
                    j //= p
                    k *= p
                f[i].append(k)
                t[i] = t[i] * (p - 1) // p
    return f, t

def problem407(n):
    """Generate a sequence whose i'th element is the largest a < i such
    that a**2 == a (mod i), where i runs from 1 to n (inclusive).

    """
    f, t = factorize(n + 1)
    yield 0 # i = 1
    for i in range(2, n + 1):
        if i not in f or len(f[i]) < 2:
            # prime or prime power
            yield 1
            continue
        def uw():
            for j in range(1, len(f[i])):
                for c in combinations(f[i], j):
                    u = reduce(mul, c)
                    v = i // u
                    w = pow(u, t[v] - 1, v)
                    yield u * w
        yield max(uw())


A function to print a character number of times and in number of lines

Only a couple of things:

int lines,times; - one declaration per line, please!
scanf("%c%d%d", &userChar, &times, &lines) - where does one number end and the next start?. You need to include some terminating characters, such as ,

printf("please enter a character, number of times in a line, and number of lines, separated by a comma:\n");
while ((scanf("%c,%d,%d", &userChar, &times, &lines)) == 3)

An expression such as while (++y <= numberOfLines) is confusing, what value does y have at each step? It'd be better to rewrite this as a for loop

for ( y = 0; y < numberOfLines; y++ )


The first one will be slow because of all the jQuery selection.

The second one will be slow because of the two loops. It keeps looping over what was already found. BUT it is going to be faster than the first one.

I made a basic jSPerf with a basic object: http://jsperf.com/some-random-beef

I also added two more cases to show you faster ways. NOW, if the object contains more junk in it, the results may differ.

var inputs = document.forms[0];
for (var key in fd) {
    var elem = inputs[key];
    if (elem) {
        elem.value = fd[key];
    }
}

Now what version of the code would I want to read? The first one.


Suggestions on how to improve this .htaccess file for page load speed

Honestly, this looks OK, though you could clean it up a little bit.

You have two ways to make this code better:

group related mime types.
use human-readable syntax

Regarding point #2, here's part of the config I created after watching Illya Grigorik's presentation "Breaking the 1000ms Time to Glass Mobile Barrier":

<IfModule mod_deflate.c>
# these are known to be safe with MSIE 6
AddOutputFilterByType DEFLATE text/html text/plain text/xml

# everything else may cause problems with MSIE 6
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/x-javascript application/javascript application/ecmascript
AddOutputFilterByType DEFLATE application/rss+xml

ExpiresActive On
ExpiresDefault "access plus 15 minutes"

ExpiresByType text/html "access"
ExpiresByType application/json "access"

ExpiresByType text/css "access plus 1 week"
ExpiresByType image/gif "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>

You might also look into Google's mod_pagespeed for Apache.


Select the correct input when using input group after pressing a button

If the input group perhaps contains additional input elements this won't work. I think that you should bind the button to the input field by declaring a new attribute to the button which is connected to the input's id. Like so:

<button type="button" class="btn btn-default increase" data-bind="rooms"></button>

It now contains the input ID which this button is connected to. Now in your JavaScript try something like this:

$(".increase").click(function() {
  var input = $('#' + $(this).data('bind'));
  input.val(input.val++);
});

It will use the data-bind attribute to connect to the specific input element and increase this value by 1 (++).


Putting these comments into an answer...

As pointed out, it will be a tall order to beat or even approach the computation times of the native sort function, as it is compiled from C. Often with R, the trick to make your code faster consists in composing with some of these fast compiled building blocks that are native functions. In particular, we would look to substitute for loops like the one you have with vectorized functions. Unfortunately, your use of a for loop here is particular in the sense that each iteration has a side-effect to the x vector. This means that the order of the operations is important and we cannot run the loop iterations independently in parallel or via vectorized functions.

If we cannot get rid of the for loop, we are left trying to optimize the code within the body of the loop. Let's start with a profile of your code:

x <- sample(10000)
Rprof(tmp <- tempfile())
for (i in 1:10) z <- radix_sort(x)
Rprof()
summaryRprof(tmp)$by.total
#                         total.time total.pct self.time self.pct
# "radix_sort"                  8.26     99.76      0.72     8.70
# "split"                       7.34     88.65      0.06     0.72
# "split.default"               7.28     87.92      0.54     6.52
# "as.factor"                   6.74     81.40      0.08     0.97
# "factor"                      6.64     80.19      1.72    20.77
# "as.character"                4.34     52.42      4.34    52.42
# "unique"                      0.42      5.07      0.04     0.48
# "unique.default"              0.38      4.59      0.38     4.59
# "%%"                          0.14      1.69      0.14     1.69
# "get_digit"                   0.14      1.69      0.00     0.00
# "sort.list"                   0.12      1.45      0.02     0.24
# "order"                       0.08      0.97      0.06     0.72
# "unlist"                      0.06      0.72      0.06     0.72
# [...]

We see that the main culprit here is the use of split. Another surprise here is the use of order (it seems to be applied when figuring out the levels of x_digit_i) which you could consider like cheating given your objective.

So what alternative do we have to your use of split/unsplit? Essentially, you have a vector x that you want to reorder based on a vector of digits x_digit_i. One way is to use outer to create a matrix of TRUE/FALSE where each column locates a different digit (for a total of ten columns):

z <- outer(x_digit_i, 0:9, "==")

Then, you want to turn this matrix into a vector of indices, such that the first few indices will locate the zeroes, then the ones, etc (the equivalent of idx <- order(x_digit_i). You can do so by doing:

idx <- row(z)[z]

or (harder to understand but a bit faster)

idx <- 1L + (which(z) - 1L) %% length(x)

Finally, you just have to do:

x <- x[idx]

Also note that since you are dealing with integers, your code might be a little faster (and more robust by avoiding floating point errors) if you make sure to use integers everywhere possible. In particular, your get_digit function could be rewritten as follows:

get_digit <- function(x, d) (x %% as.integer(10^d)) %/% as.integer(10^(d-1))

The benchmarks below show decent progress (where my suggestions are implemented under the name sort_radix2) bridging the gap with the native sort. I hope it helps!

x <- sample(100)
microbenchmark(radix_sort(x), radix_sort2(x), sort(x))
# Unit: microseconds
#            expr     min       lq       mean   median       uq      max neval
#   radix_sort(x) 964.692 972.3675 1025.35180 984.3775 1012.178 2233.397   100
#  radix_sort2(x) 250.642 256.5720  282.58952 261.2910  282.449 1266.061   100
#         sort(x)  82.270  86.1605   92.22669  88.0230   90.943  223.249   100

x <- sample(10000)
microbenchmark(radix_sort(x), radix_sort2(x), sort(x))
# Unit: microseconds
#            expr       min         lq       mean     median         uq        max neval
#   radix_sort(x) 71939.706 76147.1715 80028.7541 78389.8140 81512.4140 144632.484   100
#  radix_sort2(x) 24218.810 27613.3190 34841.8724 29477.7115 31772.9415 143283.337   100
#         sort(x)   411.691   454.4015   563.4825   492.6165   558.0925   3412.719   100


Determine concurrent access to a function

A few observations off the top of my head

cerrMutex is unused, and should be removed if not needed.

mapMutex is used to guard a static std::map but is itself a regular class member variable. That suggests it probably isn't guarding the map against concurrent access. This is probably a bug.

This seems like a fairly heavyweight tool. The uses of maps and strings all smell bloaty. That's not of itself a killer, but it's worth being at least aware of. If there were the possibility of just using, say, object-local integers for counting (and perhaps a function scope static declaration to use the same counting variables), that would probably be lighter.

On the other hand, in a general use case, concurrency causes problems whenever two threads are interacting with the same resource, not only when executing the same function. For example this tool would be significantly more useful if it could detect different threads concurrently running two methods of a single object.
At the same time, it would be more helpful if it actually did not interfere with two threads each holding their own object of a given class and each running methods on their own object. This is perhaps more of a documentation enhancement suggestion: your rough approach could work by changing what ID you pass, but it would benefit from examples. (And don't go changing it to make it lightweight if it means losing the ability to do this!)

A final thing that is worth thinking about is whether this causes any inadvertant synchronisation that actually masks the very problems you're trying to detect. This is hard to predict, because schedulers can be such a dark art in general, but you could run into a problem like this.

Suppose that you have two threads running a function that does something lightweight, perhaps just increment a shared integer. Without this tool in place, you'd expect them to keep stomping on each other.

Because you're syncing up on mapMutex (which I'm going to assume as above is meant to be static) then each call to the function has to do a lot of extra work in the constructor and destructor of your tool, and that is all under exclusion. If thread 2 starts while thread 1 is still in the constructor, it will fail to take mapMutex and the scheduler will probably send it to sleep for a bit. The window for it to wake up in which thread 1 is in the function and does not have the mutex is actually quite small. What you could get, then, is the function seems to behave fine (albeit slowly) while this object is trying to help with debugging and then goes back into data races for release code when the debug object is removed. Suffice to say, that's unhelpful!

I don't have any suggestions about how to fix this problem, just that it's the sort of thing that is worth being aware of.


From a once over;

Unless YFeX is also a constructor, it should be yFex
lowerCamelCase is good for you: account_modal -> accountModal
I would store YFeX.cache.account_modal into a var cachedAccountModal so that you do not have to repeat YFeX.cache.account_modal all the time
Your code is very optimistic, you should also deal with fail
Consider using the shorthand $.get()

Other than that, the code looks fine to me.


To start out with all of the

require './lib/numeral_adders/<lib>

should be moved to a separate file like/lib/number_interpreter

Moving on, looking at repetitive parts of your code. The add_numerals method has a lot of lines like this:

@numeral << <type>_adder.add_numerals.split('')

and you have methods like this:

def <type>_adder
  <type>Adder.new(@num_interpreter.<unit>)
end

You can make this DRY by enumerating over a list defined elsewhere. For example:

# in the lib/number_interpreter.rb file
class NumberInterpreter
  Adders = {
    MAdder => :thousands,
    CMAdder => :hundreds
    # ...
  }
end

# in the main file (numeral_adder.rb)

def add_numerals
  NumberInterpreter::Adders.each do |klass, unit|
    @numeral << adder(klass, unit).add_numerals.split('')
  end
  flatten_numeral
end

def adder(klass, unit)
  klass.new(@num_interpreter.send(unit))
end

Important concepts here include setting a class as a hash key then initializing it using new later on. It also uses send for programmatic method invocation. You're writing a generic adder class to make all that repetition unnecessary - its arguments are a class to initialize and a unit to convert the results with.

By the way your flatten_numeral is so simple that it'd be better to not make it a separate method. The flatten would probably be unnecessary if you use concat instead of << (shovel):

@numeral.concat adder(klass, unit).add_numerals.split('')


Throw away your current code. Instead write this:

for dir in *; do
  (cd "./$dir" && echo "In $(exec pwd) now.")
done

As a general rule, always put variables into quotes.

Rationale: Your current code can handle a few cases properly, but some other special characters will still be interpreted specially by the shell and lead to unexpected behavior. Therefore the proper way to work around this problem is to write cd ' into the terminal, then to paste the path and then to finish the command by typing '. This will work for all characters except single quotes.

Alternatively, you could invent a command cdclip that changes to the path in the clipboard. Cygwin has /dev/clipboard, and on native Linux there is probably some similar way to read the clipboard contents.


Nice code overall, pretty readable, though there is space for improvements.

1) You don't have to return from ruby methods.

2) Good use of Enumerable methods will make code cleaner.

3) Use loop instead of while true

4) Also consider keyword arguments, as calling roll(2, 4) looks kind of cryptic.

Will all that in mind, we can turn your code into something like:

def roll(amount = 0, sides = 0)
  # rand(1..0) will return nil btw
  amount.to_i.times.sum { |t| rand(1..sides.to_i) }
end

loop do
  input = gets.chomp.to_s

  abort("May your rolls be ever natural.") if input == "exit"

  amount, sides, mod = input.tr("^0-9", " ").split
  fin = roll(amount, sides) + mod.to_i # nil converts to 0

  puts fin
end


You could try something like this:

private function applyFiltering($query, $request)
{

    $query->when($request->has('active_group'), function($query) use($request) {
        $query->whereNotIn('status_id', [1, 6, 4]);
        $query->whereHas('userStatus', function ($query) use ($request) {
            $query->where('user_id', $request->user()->id)->whereNotIn('status_id', [1, 6, 4]);
        });
    })->when($request->has('waiting_group'), function($query) use ($request) {
        $query->whereNotIn('status_id', [1, 6]);
        $query->whereHas('userStatus', function ($query) use ($request) {
              $query->where('user_id', $request->user()->id)->whereNotIn('status_id', [1, 6])->where('status_id',4);
         });
    })
    ........
    ........
    ........
}
```


From a micro-optimization perspective I have found that C# and the JIT tend to like things from left to right (post).
Ex: (((size - 1) & size) != 0) and data.Length*size*2

With a macro and readability (verification) perspective I would be curious to see the performance difference between this method and just using List<T>.Add.

When it comes to performance you need to just measure it. On different machines if you can.


Multi-replacement in a string, independently and prioritized

Do it recursively. Split the string by the first "from" value, recurse with the rest of the changes for each resulting part, then join them back together with the "to" value.

def multireplace(text, changes):
    if not changes:
        return text

    from_, to = changes[0]
    parts = text.split(from_)
    return to.join((multireplace(part, changes[1:]) for part in parts))

Advantage: Short and clean code
Disadvantage: Uses linear stack with respect to the number of changes. Might lead to stack overflow in case of lots of replacement pairs.

(Note: this answer is based on an earlier answer that somehow got deleted)


I think in general it's okay, if you need to define all of those yourself (in particular length and element-of-set? that is. trim looks a bit complicated for what it does: If you want to skip single element lists (why?), write it like that, no need for the accumulator and the length call.

The input set should be cleaned up once before the subset generation though, then you won't have to filter the result for duplicates.

conS, helper and trim are bad names. The first one is a compatibility issue since you'll find Lisps that are case-insensitive, which will then overwrite the regular cons. Both conS and helper don't say anything at all about what they do. trim essentially the same, a little better maybe. In general, stick with scheme-names-with-dashes-in-between, descriptive names and no camel case.
You sometimes skip the space between )_( and add spaces where they don't belong, like _) which looks messy. Indentation is sometimes a bit off, e.g. the if in subsets has the first case on the same line as the if.


The SQL Server query analyzer is smart enough to understand that these queries are identical (given that item_ID is unique in EMR.tblFavourites for a certain doctorID/favType pair).

They should yield exactly the same execution plan, and thus they are equal in terms of performance. I would prefer second variant though...


Engineering a minimalist image interface without templates

A few notes about things and stuff (I know, my introductions are always original):

About that comment:

//doesn't STL have a std::prod() ?!?!

The standard library does have a function to compute the accumulated product of a range. It's called std::accumulate. You can use it like this:

int n = std::accumulate(
    std::begin(dimsizes), std::end(dimsizes),
    1, std::multiplies<int>{}
);

Agreed, it's a bit verbose. But the function is quite generic since it may work with any well-formed binary operation. Note that if you are using C++14, you can use std::multiplies<> instead of std::multiplies<int> and let the type be deduced.
Also, you mentioned std::array. If you know for sure that you will only store 4 values and not more, then please, by all means, use an std::array<short, 4> instead of an std::vector<short>.
Your case isn't really consistent. For local variables, the generally accepted practice is to use snake_case everywhere and to drop every capital letter.
Ok, I hate to say this, but void AImg::plusone(std::string cast) without templates really hurts me. I know that you plan to change that later, but the current version still hurts me ç___ç Also, since you're not altering the std::string, it would be better to take a const std::string& parameter instead.
Instead of that:

int AImg::operator()(unsigned int idx);

Array subcript tends to use the... well, the array subcript operator[] instead of the parenthesis. Unless you have to feed it several parameters, in which case operator() is sometimes preferred, but that's not your case.

int AImg::operator[](unsigned int idx);

I don't think that the method setdata really needs a cast from void* to void*:

void AImg::setdata(void* input) { data = input; }


How to use inversion of control within a strategy when using the strategy pattern

For me the question is how the strategy is created. Is it possible to inject the file name during construction of the strategy? That would be the way I would do it.

Else you can create callbacks that are created and injected. When you need the file call this callback and let this decide (eg asking the user).


Retrieving all the email addresses on a web page

First, your code isn't exactly substantial, so it's hard to write a good review.

Up first, file_get_contents() works, but curl is faster.

It's a little longer, but try this:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

Moving on to your regex:

/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/

Instead of A-Za-z, you can end with a /i, and make your search case insensitive:

/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}/i

Depending on how complex you'll allow emails to be, you can add (or remove), some valid characters.

Next, you perform a array_values(array_unique($matches[0])) twice.

var_dump(array_values(array_unique($matches[0])));

$neaterArray = array_values(array_unique($matches[0]));

Into:

$neaterArray = (array_values(array_unique($matches[0])));
var_dump($neaterArray);

Your variable naming follows a camelCase standard all-throughout, so that's alright.

Your comments are generally good, but //store above in array for upcoming bit is incorrect as I pointed out above.

  Is this a good way to go about solving the problem? Are there parts that could be optimised with more suitable functions?

Swapping file_get_contents() with curl will improve the speed of page download.

  Is initialising the array imperative for this program? I tried it without the original declaration (in the preg_match_all line) and it still functioned.

You don't need to initialise the variable first, you really only would if it where in a for loop, in this case you can just output to a new variable.

  Is there a part/are there parts of the code that comes across as poorly written?

Not really, variable naming could be expressed better by replacing $string with $input and $neaterArray with $duplicateRemovedArray, but other than that, the code is good.


Decoding custom packets with Python using Twisted

It is hard to review something when you can't test whether your reviewed code actually works, so with that disclaimer lets see what we can do with your code.

Regarding style issues, your variable names are not good, and doesn't convey any useful informations. But leave that as it is...

Here are some elements I've incorporated in the refactoring below:

Your code sets j=internal_rounds - 1 which in effect sets j=1, so that the while loop never executes more than once. In other words it can be removed
You calculate i*2 and i*2 +1 twice for each loop, which could be simplified to some addition if we add a few more variables. That is i is expanded into i2 and i2_1, in the hope that 3 additions on those is cheaper than 3 additions and 4 multiplications. :)
Several of your steps change a variable temporary before using the result to change the dl variable, so I've compressed those a little
Remove the calculation of the loop limit for every loop

Is my refactored code faster than yours? You've got to test, as I can't. The same applies for the correctness, but I think it should be the same.

def decode(packet_data):
    i = 0
    i2 = 0
    i2_1 = 1
    packet_length = len(packet_data) - 4

    seqX = bytearray.fromhex('HEXSTRINGREMOVED')
    seqY = bytearray.fromhex('HEXSTRINGREMOVED')
    result = []

    cl = 0x6e

    while i < packet_length:
        dl = ord(packet_data[i])
        bl = seqX[i2_1]
        al = seqX[i2]
        bl2 = seqY[i2_1]
        dl2 = seqY[i2]

        dl += -bl if bl <= dl else (~bl & 0xFF + 1)
        dl ^= bl2

        dl = -al if al <= dl else (~al & 0xFF + 1)
        dl ^= dl2 ^ cl

        result.append(dl)
        cl ^= dl

        i += 1
        i2 += 2
        i2_1 += 2

    return "".join(map(chr, result))

Another micro-change you could try out, is to change the handling of result to:

result = ''
...
result += chr(dl)
...
return result

It could be faster (or slower), as it skips the array handling and the join/map operations, but it uses a string concatenation instead...


ASP.net service that sends email whenever an entity is updated

The very first problem is to move some responsibilities out of the controller. IMHO controllers should do as little as possible because their responsibility should be to glue the HTTP request to the domain model.

In your case the controller should not create and configure the service also because it makes impossible (OK...just hard) to test both in isolation. Please pick a better name but the very first thing to do is to receive an IEmailService service exactly the same way you receive the others.

This MIGHT not be always possible without some major refactoring then I'd start introducing a factory:

public ProjectController(IProjectService service, IEmailServiceFactory factory) {
   _service = service;
   _emailService = factory.GetService();
}

That hypothetical factory method is simply:

public GetService() {
    var emailService = new EmailService(_service, emailRepos);
    var settings = Settings.Load(connection);
    emailService.SmtpServer = settings["SmtpServer"];

    // ...
    emailService.TemplateASubjectFormat = settings["TemplateASubjectFormat"];
    // ...

    return emailService;
}

This is easy because you're just moving your code from one class to another and you introduced another service.

Now controllers came back to a reasonable level of responsibilities (and complexity) and they're also testable because you can mock the IEmailServiceFactory service (no need to send tons of e-mails when running your tests on the controller...)

As soon as you're ready (or simply as a second step on your refactoring) you should receive the IEmaiLService service directly - instead of going trough a factory.

There are also few things to say about the other code. Those initialization lines are tedious, if you're OK to tie your EmailService to its DB representation then you can decorate its properties:

[ConfigurationColumName("SmptServer")]
public string SmtpServer {get;set;}

You can then use a touch of Reflection to enumerate its properties:

foreach (var property in typeof(EMailService).GetProperties()) {
    var attribute = property.GetCustomAttribute<ConfigurationColumNameAttribute>();
    if (attribute == null) {
        continue;
    }

    property.SetValue(obj, settings[attribute.Name]);
}

Of course you need to define a ConfigurationColumNameAttribute class and add proper error handling.

We then arrive to the second error-prone (and not scalable) part of your code. You hard-coded the number of templates. What if you will ever need 3? Or 4? Or just one? You may simply use a dictionary (if not an array):

public Dictionary<string, TemplateDefinition> Templates { get; } = new ...;

Where TemplateDefinition has Subject and Content properties. Code should now be simple enough that you may even avoid Reflection.

SendEmailWithTemplateA() and SendEmailWithTemplateB() are almost exact duplicates, if you use a dictionary then there should not be any repeated code.

Mechanism you're using for templating is fragile. It's hard to write long strings using {0} and {1} as placeholders. Do yourself a BIG favor and switch to a small, fast and well-tested templating engine like Mustache. You'll be able to write your template as Hello {{username}}, we write to you to inform you about the new {{product}}.... It'll be much easier to configure and edit your templates and you'll minimize the chances to mix-up things when changing something in your code. Do not forget that this has to be tested too.

Do not catch Exception, is OutOfMemoryException or AccessViolationException something you want to handle that way?


Well, there's nothing wrong as far as I can see here. The only thing I would check is that there is a suitable index on the Id field in database, so the delete query can be performed relatively quick.

Another thing to consider is the size of your table. If you have lots of records in there, it can take considerable time to remove and re-add records again (due to indexing and re-indexing upon each delete/insert). In such case, I would simply add a flag to the database, marking those old dates as deleted and simply add new ones at the end of the table.

Yet another thing that comes to my mind now is that you can gain even more performance-wise if you grouped those single inserts like so:

$vals = array();
foreach ($dates as $date) {
    $date = explode("/",$date);
    $d    = $date[0];
    $m    = $date[1];
    $y    = $date[2];
    $vals[] = "('$id', '$d', '$m', '$y')";
}
mysql_query("INSERT INTO wp_opening_date (Id, D, M, Y) VALUES ".implode(',', $vals));

At last, please do not use mysql_* functions, they are now deprecated. See the PHP manual for mysql_query for more info.


In my opinion, the easiest way would be to embrace exceptions. DirectoryNotFoundException and FileNotFoundException are there for a reason, and actually even calling .Exists might not save you from them - the file might be moved/removed between the Exists and the action you're taking next.

You can do:

public static void ProcessPath(string path)
{
    var extension = Path.GetExtension(path);

    if(string.IsNullOrEmpty(extension))
    {
        Program.ScanDirectory(path);
    }
    else
    {
        if(extension != ".cs")
            throw new NotSupportedException("Only .cs files are supported");

        Program.ScanFile(path);
    }
}

And either catch those exceptions higher up and write them to console or (considering you're doing Environment.Exit in your example), just let them propagate and crash the application.


Fully Generic C++ Stack Implementation Without Lists, Arrays, or Vectors

The best thing to do if the caller tries to Pop when the stack is empty is to throw an exception. You're right, there's no return value that makes sense.

You have a bug in void Stack<T>::Push(T& data). If the stack is initially empty, the m_top and m_bottom pointers are nullptr, but if an item is pushed onto an empty stack, the m_bottom pointer is never set.

There's no reason for Stack<T>::Clear() to decrement m_size within the loop. Just set it to 0 at any time. (Though, the compiler may be smart enough to notice this)


I see some things that may help you improve your program.

Separate I/O from calculations

The program has three basic phases.  First, it gets input, then it manipulates that input, and then it produces output.  I would recommend putting the rotation code into a separate function.

Consider signed vs. unsigned

Does it make sense to have a negative array size?  Does it make sense to have a negative shift value?  I'd answer "no" to the first and "yes" to the second question.  For that reason, I'd recommend making n a size_t or unsigned type and also adding code to handle negative rotations.

Rethink your algorithm

The code currently creates a temporary array, but all that's really needed is a single temporary int.  Here's one way to do it:

unsigned gcd(unsigned a, unsigned b) {
    return b == 0 ? a : gcd(b, a % b);
}
void rotate(unsigned n, int shift, int *list)
{
    if (shift < 0) {
        shift = n -(-shift % n);
    } else {
        shift %= n;
    }
    if (shift == 0) {
        return;
    }
    for (unsigned cycles = gcd(n, shift); cycles; --cycles) {
        unsigned i = 0;
        unsigned nexti = n-shift;
        for (int temp=list[nexti+cycles-1]; nexti; i = nexti) {
            nexti = i+shift;
            if (nexti >= n) {
                nexti -= n;
            }
            std::swap(temp, list[i+cycles-1]);
        }
    }
}

Worked example

This is probably easier to understand with an example.  Let's start with a simple array or length 7 = { 0, 1, 2, 3, 4, 5, 6} and a requested shift amount of 4.  When the for loop starts we have this:


Getting an array from one property of an associative array best practice

I think array_map is what you are looking for:

php > $aa = array (array ("id" => 1, "name" => 'what'), array('id' => 2));
php > function id($i) { return $i['id'];};
php > print_r(array_map ('id', $aa));
Array
(
    [0] => 1
    [1] => 2
)


It's faster to just trim a value than it is to try and figure out if it needs trimming in the first place.

However, that's not where your performance bottleneck is.

My personal #1 rule of fast spreadsheet manipulations:

Thou shalt not directly manipulate data in worksheets

By this I mean, doing anything in a worksheet has huge computational overhead. In the VBA object heirarchy, worksheets are only 2 steps removed from the application object itself. There are layers upon layers of abstractions, events, handlers, objects (not to mention several Billion range objects) buried in a worksheet object, and any time you do something in it, it will trigger a cascade of operations to make sure that nothing in your worksheet gets messed up.

Your sub might run fine for a couple of hundred cells in a small worksheet, but a few thousand cells in a larger spreadsheet might suddenly become unbearably slow.

For this reason, you should interact with worksheets as infrequently as possible. If there is data in your worksheet that you need to analyse: access the worksheet once to read the data into an Array, then do all your computations on the Array, then access the worksheet once to read the data back.

Your sub then looks like this:

Public Sub TrimWorksheetCellValues(Optional ByRef targetSheet As Worksheet)

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    On Error GoTo errorHandler

    If targetSheet Is Nothing Then Set targetSheet = ActiveSheet '/ If no sheet is provided, assume the active sheet

    Dim firstRow As Long, lastRow As Long
    firstRow = 1
    lastRow = targetSheet.Cells.Find(What:="*", _
                         SearchOrder:=xlByRows, _
                         SearchDirection:=xlPrevious).row

    Dim firstColumn As Long, lastColumn As Long
    firstColumn = 1
    lastColumn = targetSheet.Cells(lastRow, Columns.Count).End(xlToLeft).column

    Dim sheetRange As Range
    Set sheetRange = targetSheet.Range(Cells(firstRow, firstColumn), Cells(lastRow, lastColumn))

    Dim sheetArray As Variant
    sheetArray = Array()
    sheetArray = sheetRange

    Dim ix As Long, iy As Long
    Dim elementValue As Variant, trimmedValue As Variant

    For ix = firstRow To lastRow
        For iy = firstColumn To lastColumn
            elementValue = sheetArray(ix, iy)
            trimmedValue = Trim(elementValue)
            sheetArray(ix, iy) = trimmedValue
        Next iy
    Next ix

    sheetRange = sheetArray

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

    Exit Sub

errorHandler:
    MsgBox "Error has occurred.", _
      vbCritical, "Error!"

End Sub

A few other things I modified while I was there:

Function names should be written in PascalCase with the leading word capitalised

Things should be explicitly scoped. Your sub was implicitly targeting the active sheet everywhere but nowhere was that explicitly declared or confirmed as the desired functionality. The sub now explicitly targets a particular sheet or explicitly targets the active sheet if no target is provided.

The firstRow and firstColumn are now explicitly declared and assigned, rather than magically appearing halfway through your code.

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

These are the standard application settings to turn off if you want your macros to run faster. You should make sure any error handling resets them to their previous values in case your procedure terminates unexpectedly.

Don't catch errors if you're not going to handle them properly. This:

errorHandler:
    MsgBox "Error has occurred.", _
      vbCritical, "Error!"

Is just an error message, but with the useful information (error#, warning etc.) taken out. Do something useful with it (like resetting the application settings) or remove it.


Total array size can be equal to INT_MAX and k can be as small as 2

Why not 1?

    @Override
    public int compare(Long firstNumber , Long secondNumber) {
        return (int) (secondNumber - firstNumber);
    }

I found myself several time staring at such a line and being sure, there can be NPE there! But it can and I'd suggest to add explicit checks (throwing is correct, my point is to do it explicitly).

The Comparator is seriously broken:

casting from long to int can overflow
subtraction can overflow, too

Use Long.compare.

PriorityQueue<Long> heap = new PriorityQueue<>(k, new DecreasingComparator());

That makes it simple, but boxing is not free. While a few small values get cached in a cache in java.lang.Long, for others an object must be created. This takes 16 bytes and the heap contains a reference to it (4 or 8 bytes). So you need 20 or 24 bytes per long in addition to the 8 it takes in the input array.

This may make a few megabytes if you want the millionth element. There's also an allocation, but with current smart GCs it's usually no big deal.

There's no need for a decreasing comparator, as you could find the input.length+1-kth smallest element instead.

Or you could use both and select the one giving you a smaller queue.

    for(int i=0; i<k;i++) {
        heap.add(input[i]);
    }
    for(int i=k; i<input.length;i++) {
        if(heap.peek() > input[i]) {
            heap.poll();
            heap.add(input[i]);
        }
    }

This is smart and avoids most of the boxing (for small k). It could use some comments and a lot of tests.


Creating an iPad-style video frame with CSS and without images

Your code is perfectly valid, according to the HTML and CSS validators at W3C:

  HTML Validator
  CSS Validator

However, there are a couple things you could improve.

HTML:

I assume you already know to always specify the doctype and character encoding in your HTML files.  The character encoding is not required by the validator, but it is good to always include it:

<!DOCTYPE HTML>
<head>
    <meta charset="utf-8">
    <title>Page Title</title>
</head>

Your CSS is difficult to read because of your indentation and your use of braces.  All of your indentation should match, not have some blocks at the nested indentation level, and some at their proper level.  Also, most CSS files use braces like this:

.vid {
    max-width:800px;
    width:80%;
    margin:0 auto;
}

Not like this:

.vid{
    max-width:800px;
    width:80%;
    margin:0 auto}

Edit

After clarification in the comments, this is a valid CSS style, but I still prefer the above style.

End Edit

The CSS validator does not require that you have a semi-colon ; after the very last item, but you should to keep things all the same style.

Overall, your code is good and the UI is beautiful.  These are just a few things you could improve on and a few tips that just because they are so important, they deserve to be here.


Since you know that the double quotes will always be matched, you might try this instead of your first two replaces:

r.replace(/"([^"]*)"/g, "“$1”")

I think that's a little stronger.  The unmatched single quotes are harder, and I think what you have is reasonable.  I might try this tack though if JavaScript has the \w for word letters.  (If not, use [a-zA-Z].)

.replace(/(\w)'(\w)/g, "$1’$2")
.replace(/'([^']*)'/g, "‘$1’")


Shortest possible way of printing a specific board

Bugs

You say:

  I am trying to print a board exactly like this with the multidimensional array.

But, in reality, you are not... you only print the first item from the 2D array, and the rest of the board is printed from the constant string values. See this article describing C++ array initialization

char score[10][10] = {' '};

The above code only initializes the first position of the score 2D array, and the remaining cells in the array are left as null-characters.

When those null-characters are printed in the j loop:

    for (int j = 0; j < 10; j++) {
       cout << score[i][j];
    }

The all do nothing (except the very first cell at score[0][0]) because they become zero-length strings.

Thus, only the first line, and the first value get printed. To compensate for this, you are printing an constant-string value to complete the line, but, the first line is one character longer (because you printed score[0][0]) than the others, so the first line has to have a single-char shorter constant to complete it, and you need the if(i == 0){... condition.

I have made this obvious by initializing the array with an x (char score[10][10] = {'x'};) in this ideone which produces:

   a b c d e f g h i j
  +-------------------+
 0|x                  |
 1|                   |
 2|                   |
 3|                   |
 4|                   |
 5|                   |
 6|                   |
 7|                   |
 8|                   |
 9|                   |
  +-------------------+

You need to correctly initialize the array....

char score[10][10] = {};
for (int i = 0; i < 10; i ++) {
    for (int j = 0; j < 10; j++) {
        score[i][j] = ' ';
    }
}

Other

you are using the grid-size 10 as a magic number in a lot of places. You should probably make it a constant.....

Alternative.

C++ is not my primary language, and this is hardly a good example of a C++ program, but I have re-written your program as.... available on ideone as well ... This is the code that you should really be reviewed on ....

#include <iostream>
using namespace std;
#include <vector>
#include <string.h>

int main(){

    char score[10][10] = {};
    for (int i = 0; i < 10; i ++) {
        for (int j = 0; j < 10; j++) {
            score[i][j] = 'x';
        }
    }

    cout<< "   a b c d e f g h i j"<< endl;
    cout <<"  +-------------------+"<< endl;

    for (int i = 0; i < 10; i++) {
        // print the first character as part of the opener.
        cout << " " << i << "|" << score[i][0];
        for (int j = 1; j < 10; j++) {
           // only add spaces for subsequent characters.
           cout << " " << score[i][j];
        }
        cout << "|" << endl;
    }
    cout <<"  +-------------------+"<< endl;

}

because the above code initializes the 2D array with x, it prints the following grid:

   a b c d e f g h i j
  +-------------------+
 0|x x x x x x x x x x|
 1|x x x x x x x x x x|
 2|x x x x x x x x x x|
 3|x x x x x x x x x x|
 4|x x x x x x x x x x|
 5|x x x x x x x x x x|
 6|x x x x x x x x x x|
 7|x x x x x x x x x x|
 8|x x x x x x x x x x|
 9|x x x x x x x x x x|
  +-------------------+


Macro for inserting a mini table between heading styles

Optimization:

You've done a good job of making sure you're not processing more than you have to, but there are a couple of things you can do here to improve performance. Instead of looping through all of the MiniTOCs you've just inserted, updating each one individually. Just update all of the fields in the entire document at once.

Replace This:

' Update all TOC fields in document
For Each currentTOC In ActiveDocument.TablesOfContents
     currentTOC.Range.Select
     currentTOC.Update
Next currentTOC

With This:

ActiveDocument.Fields.Update

It also turns out that there's no reason to  to check every paragraph's style. We can find them all. Below is the uber simplified logic that you would need to implement. Also note that subs/functions should have a verb-noun type name. I changed it in my example.

Private Sub test()
    InsertMiniTOCFields wdStyleHeading1, 3
End Sub

Public Sub InsertMiniTOCFields(headingStyle As WdBuiltinStyle, TOClevel As Long)
    Dim bookmarkRange As Range
    Dim bookmarkNumber As Long
    Dim currentRange As Range
    Dim insertRange As Range
    Dim doc As Document

    Set doc = ActiveDocument
    Set currentRange = doc.Range 'start with the whole doc as the current range

    With currentRange.Find
        .Forward = True         'move forward only
        .Style = headingStyle   'the style given as an argument
        .Execute                'update currentRange to next found instance

        Do While .Found

            ' code to insert bookmarks

            ' Add the TOC field
            Set insertRange = currentRange 'I changed this assignment from currentParagraph to currentRange
            insertRange.Collapse direction:=wdCollapseEnd
            ' Add the new TOC field
            doc.Fields.Add _
                Range:=insertRange, _
                Type:=wdFieldEmpty, _
                Text:=" TOC \h \o """ & HeadingNumber & "-" & TOClevel & """ \b TOCHeading" & HeadingNumber & "_" & (bookmarkNumber + 1)
                bookmarkNumber = bookmarkNumber + 1

            ' update currentRange to next found instance
            .Execute
        Loop
    End With

    'update all newly inserted MiniTOCs
    doc.Fields.Update

End Sub

You can also turn screen updating off to pick up some more performance. You will need to introduce some error handling into your code if you decide to do that though. You'll want to make sure that screen updating is always turned back on when your sub exits; even if it errors. Truthfully, I imagine that this routine should really have an error handler anyway. Here is a pretty good error handling pattern to follow.

Other Notes:

You really shouldn't access the document with ActiveDocument each time. It's much better to store the reference in a variable. This way, you know for a fact that the document you started working on is the one you'll continue to work on.

Dim doc as Document
Set doc = ActiveDocument

Watch your line indentation. Ends should be at the same indentation
level as the If they belong to.
Instead of declaring HeadingNumber as a long in your sub
declaration, you should consider using WdBuiltInStyle.

So instead of this:

Sub MiniTOCFields(HeadingNumber As Long, TOCLevel As Long)
    '......
    ' Check for occurrences of Heading X
     If currentParagraph.Style = "Heading " & HeadingNumber Then

You would have this:

Sub MiniTOCFields(headingStyle As WdBuiltInStyle, TOCLevel As Long)
    '......
    ' Check for occurrences of Heading X
     If currentParagraph.Style = headingStyle Then

You write pretty clean code. I like your variable names. Very concise and easily understandable. You use line continuations judiciously, but it can be a slippery slope. Be careful with that.


I just want to know if the code I wrote would be appropriate in a interview setting or would I expect to write code like the solution in the book.

As we cannot see the solution form the book, this is hard for us to answer.

Your solution seems to work which is ok for learning purposes, the biggest I can think of with your current code is List comprehension.

for col in the_array:
    transposed.append(col[i])
transposed.reverse()

Could be

transposed = [col[i] for col in the_array][::-1]

Note how instead of .reverse() I use the slice annotation to reverse the list [::-1]

We could even make the first for loop another list comprehension (essentially creating a double list comprehension)

def transpose2(the_array):
    return [
        [col[i] for col in the_array][::-1]
        for i in range(len(the_array))
    ]

I should note though that is is a rather elaborate way of writing

def transpose3(arr):
    return zip(*arr[::-1])

Where the zip rotates the reversed list with argument unpacking


I would do the definition inline with the declaration:

$newArray = array(
    '2014-13-03' => array(
        'SMD' => array(
            'IMPR' => 10,
            'CLICK' => 10
        )
    )
);

If you wanted to lean towards the more compact side, you could achieve almost the same clarity with something like:

$newArray = array('2014-13-03' => array('SMD' => array(
    'IMPR' => 10,
    'CLICK' => 10
)));

In addition to a bit more clarity (at least in my opinion), this has the advantage of it being more difficult to accidentally mess up the data. Since the parents keys aren't repeated, the keys are either right for both leaves or wrong for both leaves. That should help prevent a rather odd potential bug.

By the way, that's a rather odd data structure unless this is just an example. Three levels deep for such a sparse data set is kind of excessive.

From an optimization standpoint, it's not going to matter how you do it. You're in the realm of microseconds at most. Really it's just the parser that's going to differ on it anyway since I would imagine the parser will change any reasonable incantation of this to the same instructions (I have not confirmed that though).

By the way, $newArray is a terrible variable name in anything but example code. If your real code is using that, change it to a descriptive name.


4: use std::{env, error, fs::read_to_string, io, path::PathBuf, process};

Just a personal taste, but I would do

use std::{env, error, io, process};
use std::fs::read_to_string;
use std::path::PathBuf;

Yes, nested includes are nice and easy, but hard to extend. It's up to you.

35: let file_contents: Vec<&str> = file_contents.split('\n').collect();

I would suggest using lines instead.

Also, you can omit &str or change the line completly.

Either

let file_contents: Vec<_> = file_contents.lines().collect();

or

let file_contents = file_contents.lines().collect::<Vec<_>>();

46/48: line.len() > 0 / line.len() == 0

Replace that by !line.is_empty() and line.is_empty().

60: resolved_path = PathBuf::from(env::current_dir()?);

Remove PathBuf::from completly, because current_dir is already a PathBuf


You can transpose the given list of lists using a single line:
zip(*table_data)

That's it. Now, to find the longest word in each column, it would be another 1-liner:
map(len, [max(_, key=len) for _ in table_data])

You are calculating len(table_data) a lot of times. Better to store it as a variable? Although, another comprehension could be:
for row in zip(*table_data):
    for index, cell in enumerate(row):
        print(cell.rjust(col_width[index]), end=" ")

You whole function now becomes:
from typing import List
def print_table(table_data: List):
    col_width = list(map(len, [max(_, key=len) for _ in table_data]))
    for row in zip(*table_data):
        for index, cell in enumerate(row):
            print(cell.rjust(col_width[index]), end=" ")
        print()


Decode Argon2 parameters and handling decode errors

Because you use named parameters, the error checking can indeed be simplified.

While you critique the use of if err != nil, I enjoy the consistent error handling, and prefer it to the concepts used in many other languages.

Returning errors

Rather than explicitly returning values, such as

return nil, nil, nil, errors.New("...")

You can instead set the named return value err:

if len(fields) != 6 {
    err = errors.New("incorrect hash format")
    return
}

This does not set the other values to nil, and that shouldn't matter. In terms of consuming this API, it would be bad practice to use any other return values if err is not nil. It would be the equivalent in C of using the return value of strtoul() without checking errno.

Having the comment // error check each time is too verbose.

Misspelling

The variable fileds is misspelled, it should be fields.

Helper function

Using named return values in your helper function is superfluous. You can easily return those variables directly.

func decodeBase64WithLength(encStr string) ([]byte, uint32, error) {
    s, err := base64.RawStdEncoding.DecodeString(encStr)
    return s, uint32(len(s)), err
}

But now that the function has been cleaned up, it's easy to see that it really isn't needed. If this is the only place you use the function, then doing something small twice doesn't justify a helper function in my opinion.

Params

You reference Argon2Params as Params, and both are exported types, but you refer to its members as unexported types. I'll assume it's exported, and capitalize the member variables.

Conclusion

Here is the code I ended up with:

package main

import (
    "encoding/base64"
    "errors"
    "fmt"
    "strings"

    "golang.org/x/crypto/argon2"
)

// Argon2Params are ...
type Argon2Params struct {
    Memory     uint32
    Time       uint32
    Threads    uint8
    SaltLength uint32
    KeyLength  uint32
}

func decodeHash(encodedHash string) (p *Argon2Params, salt, hash []byte, err error) {
    fields := strings.Split(encodedHash, "$")

    if len(fields) != 6 {
        err = errors.New("incorrect hash format")
        return
    }

    var version int

    if _, err = fmt.Sscanf(fields[2], "v=%d", &version); err != nil {
        return
    }

    if version != argon2.Version {
        err = errors.New("argon2 version mismatch")
        return
    }

    p = &Argon2Params{}

    if _, err = fmt.Sscanf(fields[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time,
        &p.Threads); err != nil {
        return
    }

    salt, err = base64.RawStdEncoding.DecodeString(fields[4])
    p.SaltLength = uint32(len(salt))

    if err != nil {
        return
    }

    hash, err = base64.RawStdEncoding.DecodeString(fields[5])
    p.KeyLength = uint32(len(hash))

    return
}

func main() {
    decodeHash("$argon2id$v=19$m=65536,t=3,p=4$ruDgwQK24h0wGXI87+lVWAbHmgNidUNPVSTdSloOlfM$py20HR7L4K6LllGsZNDbkrbh89x2tIF8JCIG0DAaoi8")
}

Hope this helps!


Instead of attaching multiple click handlers for the same element, you should just combine them into one function:

$(document).ready(function () {
    $(".menu").click(function () {
        $('#menu').animate({
            'left': '0px'
        });
        $('#container').animate({
            'left': '100px'
        });
    });
    $("#close").click(function () {
        $('#menu').animate({
            'left': '-100px'
        });
        $('#container').animate({
            'left': '0px'
        });
    });
});

Other than that, i don't see anything to optimize.


Make loading icon appear only after 2 seconds

The ajaxStart() handler is only called if there are no other ajax requests currently in progress, so if there is already something in progress, the handler will never be fired.

Th ajaxStop() handler will only be called when a request completed and there are no other outstanding requests. So, theoretically, if you have ajax requests being fired every second, the loading icon could remain on your screen in perpetuity.  If you are looking at building a heavily ajax-driven UI, it might not be too wise to rely on the global ajax functionality for this reason, as you have to then concern yourself with interaction of different ajax requests and how they may impact the user experience.

From a UX standpoint, I would find it odd that you only want to display the loading icon until after 2 seconds have passed.  This seems like a really long time to wait to give the user some feedback that something is happening in response to some action they have taken.

There is no reason to have your global loadingIconOn variable at all. It would be preferable instead to work with jQuery queue functionality to give explicit control over how the animations are sequenced.

For example:

$(document).on({
    ajaxStart: function () {
        $('body').delay(2000, 'loadingIcon').queue('loadingIcon', function() {
            $(this).addClass('loading').dequeue();
        });
    },
    ajaxStop: function () {
        $('body').clearQueue('loadingIcon').removeClass('loading');
    }
});

This also gives the advantage of having the function to delay then add the class specifically "scoped" to only be relevant to the body element as well as the opportunity to set up a specific queue (loadingIcon in this example), which deals only with this specific functionality.

Note that you don't need to use a custom queue like loadingicon. You could simplify this down by using the default fx queue, which would look like:

$(document).on({
    ajaxStart: function () {
        $('body').delay(2000).queue(function() {
            $(this).addClass('loading').dequeue();
        });
    },
    ajaxStop: function () {
        $('body').clearQueue().removeClass('loading');
    }
});

But, I find it best practice to keep animations related to a certain set of functionality within their own queues so as to minimize potential conflicts with effects you might add in the future. Like say you added some functionality in the future to change some of other property/class on <body>, if the effects were in their own queue, they could be applied to the element simultaneously with the icon loading effect without causing undesirable interactions (obviously other than if they impact the same CSS properties in the loading class).


intersecton(List(1, 2, 4), List(4, 5, 6)) incorrectly returns None.

You've asked several questions recently, and I keep seeing similar issues:

Using list.last: You have been advised to avoid traversing to the end of the list, for efficiency.  Lists should be manipulated at the head.
Functional thinking: These solutions involve too many tedious cases, and the code could be simplified by defining helper functions, or even restated entirely in terms of other functions.
Spelling: What's an "intersecton"?  (You previously misspelled "palindrome", twice.)
Inadequate testing: The counterexample cited above just happened to be the first test I tried, and it failed.  This isn't the first time I've seen an obviously wrong result.  Your first question was closed due to broken code, and it still hasn't been fixed.

You are welcome to use Code Review as a learning resource, but it would be a good idea to show some improvement between questions.


Several problems I see:

accList_allocate

accList_allocate doesn't do what you probably think. It creates a new accList, yes, but this new one will not be visible to the caller (and thus, will be lost as memory leakage). If you want to initialize the pointer passed to it, use a pointer-to-pointer:

void accList_allocate(struct accList **outList)    //allocate and initialize to NULL values
{
   struct accList* theList = Malloc(sizeof(struct accList));
   theList->head = NULL;
   theList->tail = NULL;
   theList->size = 0;
   *outList = theList;
}

Also, you should really check the return value of Malloc. Especially on embedded systems, there's a real possibility of running out of memory. Let the caller handle the error, but tell him that something's wrong.

appendToEnd

Same as with accList_allocate, check Malloc's return value and return some kind of error code if it's NULL. What you're writing there is library code that should always handle errors gracefully and let the caller decide whether to crash and burn or recover and try again.

removeData

Please refer to my answer in your other thread.


When misused, private access can frequently result in reduced opportinutues for code reuse, such as in this case. Self-contained static methods in particular should almost never be private, but rather should be moved into a separate utilities class and marked public.

At the same time, you should add javadoc to the method, to further facilitate code reuse:

/**
 * Tests whether a number is prime or not.
 * @param num The number to test.
 * @returns {@code true} if {@code num} is prime, {@code false} otherwise.
 * @throws IllegalArgumentException if {@code num} is zero or negative.
 */

As for readability, I think that (num & 1) == 0 is perfectly clear, however the previous statement, if (num <= 3) return num > 1;, is a little bit unclear. You should replace it with a simple check for one, if (num == 1) return false; and another if (num <= 3) return true; after it.

Note that if you start the loop at 5, you missclassify 9, 15, and 21, which you can see in this ideone sketch: https://ideone.com/Jnn6QU. They are missed because they are less than 25 but not divisible by two. You should start the loop at 3 in order to catch those numbers.

You may wish to consider using BigInteger.isProbablePrime instead of this method, however, as it is much faster for large values. While a true return from that method does not guarantee that the number is prime, you can tune its certainty to your needs.


Zip-like construction of objects from parameter collections

I see one error:

assert(std::all_of(sizes.begin(), sizes.end(), [&](size_t s){return s=sizes[0];}));
                                                                     ^

This is an assignment, not a test. You probably meant s == sizes[0].
You can help this by passing s as a const value:

assert(std::all_of(sizes.begin(), sizes.end(), [&](size_t const s){return s == sizes[0];}));

Additionally, you may not mind destroying your old vectors (via move). So it may be worth looking at using move construction on the result vector:

std::vector<T> zipConstruct(std::vector<Arg>&... argVec)
{                                //        ^^^  pass by reference as you may modify them

      result.emplace_back(std::move(argVec[i])...);
                      //  ^^^^^^^^^^   Add standard move to get move semantics.


Printing a list as "a, b, c." using Python

TL;DR:

Despite this being the currently accepted & highest voted answer, these methods from this answer and variations (1, 2) of it:

print(", ".join(flavours) + ".")         # Peilonrayz
print(", ".join(flavours), end=".\n")    # Maarten Fabré
print(f'{", ".join(flavors)}.')          # Andy

are all faster than the solution originally proposed in this answer:

print(*flavours, sep=', ', end='.\n')

Original Answer, Plus Explanation & Timing Analysis:

Consider also:

flavours = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']
print(*flavours, sep=', ', end='.\n')

This does not perform any unnecessary string concatenation, nor does it require a loop variable to test for the final index.

How does this work?

The print function takes a variable number of arguments, and so would be defined something like:

def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
    # ...

except it is a built-in function.

The *args parameter consumes all of the unnamed arguments into one list for processing by the function, allowing the function to take a variable number of arguments.

In the statement,

print(*flavours, sep=', ', end='.\n')

The "splat operator" (*) takes the iterable flavours and expands it into a list of arguments for the function, allowing the caller to pass a variable number of arguments to a function, taken from the contents of a container (list, tuple, etc).

The Python interpreter could match the *flavours splat operator with the *args variable argument list of the print function, and simply pass the flavours list into the args.

But does it?  I got worried.  Perhaps, because a list is given, and the variable argument list (in CPython) is passed as a tuple, the list actually must be copied.  How much time does it take.

After creating a class Null output stream, to speed up the printing, I began passing variable sized lists to the various answers, and profiling the results.  While my solution is one of the least amounts of code, it turns out that @Peilonrayz's solution of ", ".join(flavours) seems to be the fastest.

Using tuples or lists doesn't seem to affect the performance much, so any thought that splatting a tuple instead of a list, to be collected into a *args variable argument tuple may be optimized to a no-op, seems to have been squashed.

Since print will automatically convert objects to strings for printing, the above will work for all object types in a list.  The ", ".join(flavours) will only work for strings; it would have to be modified to convert non-strings to strings to be truly equivalent:

print(", ".join(map(str, flavours)) + ".")


I solved it by drawing the borders 1px outside of the squares bounds. This way I was able to simplify my method enormously:

private func drawBorder() {
        var borders: [Border] = [Border(edges: .all)]
        if self.tackleBoard.isCornerStone(atLocation: location) {
            borders.append(Border(edges: .all, color: Theme.shared.alternateStoneBorderColor))
        }
        if location.row == tackleBoard.boardSize - 1 || location.row == 1 {
            borders.append(Border(edges: .top, color: Theme.shared.alternateStoneBorderColor))
        }
        if location.column == tackleBoard.boardSize - 1 || location.column == 1 {
            borders.append(Border(edges: .left, color: Theme.shared.alternateStoneBorderColor))
        }

        self.addBorder(borders)
    }

This produces the same result as my first code snippet but is way more readable I guess. I am happy with the result now. However if someone has a better solution for me I'd love to improve the code :)


string.punctuation == string.punctuation.lower().
You don't need string_clean to be a function as you only use it once.
Don't use _ as a variable, and definitely don't in a loop, as most use it as a 'garbage' variable.
You can use f[:-1] to get the same as u = f[:];u.pop()
Your algorithm is ok, but can be a bit odd to read.

To improve your code I'd add collections.defaultdict.
This will allow you to remove the innermost if/else.
This is as if the value isn't in the dictionary it'll default it to something for you.

>>> from collections import defaultdict
>>> next_word_keeper = defaultdict(int)
>>> next_word_keeper['test'] += 1
>>> next_word_keeper
defaultdict(<type 'int'>, {'test': 1})
>>> next_word_keeper['test'] += 1
>>> next_word_keeper
defaultdict(<type 'int'>, {'test': 2})
>>> next_word_keeper['test2'] += 1
>>> next_word_keeper
defaultdict(<type 'int'>, {'test': 2, 'test2': 1})

Using the above should get you:

def word_counts(f):
    f = f.lower().split()
    unique_f = list(set(f[:-1]))
    result = {}
    for word in unique_f:
        next_word_keeper = defaultdict(int)
        for i in range(len(f)-1):
            if word == f[i]:
                next_word_keeper[f[i + 1]] += 1
        result[word] = next_word_keeper
    return result

But this code is not the best when it comes to readability and performance!

Instead of going through the list multiple times, you can go though it once.
Using enumerate we get the current index, and then we can use it to get the next word.
And then using two defaultdicts we can simplify the function to six lines:

def word_counts(line):
    line = line.lower().split()
    results = defaultdict(lambda:defaultdict(int))
    for i, value in enumerate(line[:-1]):
        results[value][line[i + 1]] += 1
    return results

You can also go onto use the itertools pairwise recipe to further simplify the code.


My observations thus far:

You are not actually using mouseenter in your code, you should as that would be the better approach
The function inside a loop with the double var assignment is awkward, if you want to go functional just use .forEach()
The way you have // handle this if needed, the reader is not sure if that can happen. If it can happen, then the code will create 2 times labelElement since you did not call labelElement.destroy(); in that else branch. If it cannot happen, remove the code. Also if it cannot happen, place labelElement.destroy(); after the if statement
labelElement seems to be a global, I hope it is created with a var statement elsewhere in your code
From a naming perspective (not sure this is your naming), I have no idea what scrollGroup would return, and even less of an idea now that I see that that object has a method called translateY. You might want to re-consider carefully some of the naming.


Your current approach would benefit from sorted inputs.

But an even simpler approach would be to ignore the irrelevant verbs and rephrase the problem like this:

  A noun phrase is a pair of nouns. We are given two input sets of noun phrases, and must compute set intersection, using a problem specific notion of "phrase equality".

This implies a linear O(n) input pre-processing pass, where you populate a HashSet with each input phrase, X+" "+Y.

With that in hand, your task is trivial. Scan the other collection of phrases, and for each phrase make two set membership queries: is X+" "+Y or Y+" "+X present in the set?

BTW, your identifier storeAsserions seems to be a typo for storeAssertions. And please include a space after keywords like if & for.


You're pretty new to OCaml? You're using OCaml 3.12 features and probably did a lot of functional programming before. Let's see if I can show what idioms I've seen before. I'm not an OCaml expert though, far from it.

Empty trie Consider using something like Empty to denote the empty trie. type trie = Empty | Node of int * trie CharMap.t This is better than your empty hack, and will allow you to take advantage of OCaml's pattern matching.

string_of_char is a nice OCaml name, but this is not really string_of_char, but string_of_char_option. Since it's not important, I'd tend to make it look smaller in the code.

let string_of_char_option = function None -> "" | Some ch -> String.make 1 ch

Auxiliary function name You don't need to use the name helper: traverse is fine. It's not ambiguous since traverse is not recursive. This applies to all functions with auxiliary functions.

Indentation I'm not sure I understand how you choose to put your ins. Also, fromChildren has a wrong indentation.


Printing the sums of numbers from 1 to 10 with only 1 loop

Yes, it is possible.

public static void printSums() {
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
        sum += i;
        System.out.println(sum);
    }
}

The key is simply to calculate the sum of the first \$N\$ digits. It is easy if you already have the sum of the first \$N-1\$ digits : you simply add \$N\$.


A pattern I use for this is individual validators:

function validateName(value) {
  if (value.length > 0) {
    if (!inputValue.match(/^[a-zA-Z]+$/)) {
      return 'Letters only'
    }
  }
  return ''
}

Obviously this can be heavy for simple forms, but it's a very reusable pattern, and it keeps your components lighter:

handleValidation(e) {
  const name = e.target.name
  const value = e.target.value
  this.setState({ [name]: value }, () => {
    if (name === 'firstName') {
      this.setState({ errors[name]: validateName(value) })
    }
  })
}

This allows you to do:

{this.state.errors['firstName'] &&
{this.state.errors['firstName']}
}

One benefit I find to this pattern is that it scales well - as your forms grow, you'll refactor to have your inputs as their own components and managing their own state, and this pattern will scale better and better as you refactor, as opposed to doing all the checking within a single function.


Wrapper for complicated Range manipulation

Using your method, I would opt for a Select Case when determining which way to go.

Sub expand(ByVal rangeToExpand As Range, ByVal whatDirection As String)
    Dim lastRow As Long
    Dim lastColumn As Long

    Select Case whatDirection

        whatDirection = "toTheRight"
            lastRow = rangeToExpand.CurrentRegion.Row
            lastColumn = Cells(rangeToExpand.Row, rangeToExpand.CurrentRegion.Column.Count).End(xlToRight).Column
            Set rangeToExpand = Range(rangeToExpand, Cells(lastRow, lastColumn))

        whatDirection = "fromTheRight"
            lastRow = rangeToExpand.CurrentRegion.Row
            lastColumn = Cells(rangeToExpand.Row, rangeToExpand.CurrentRegion.Column.Count).End(xlToLeft).Column
            Set rangeToExpand = Range(rangeToExpand, Cells(lastRow, lastColumn))

        whatDirection = "downwards"
            lastColumn = rangeToExpand.CurrentRegion.Column
            lastRow = Cells(rangeToExpand.CurrentRegion.Rows.Count, rangeToExpand.Column).End(xlUp).Row
            Set rangeToExpand = Range(rangeToExpand, Cells(lastRow, lastColumn))

        whatDirection = "fromSheetBase"
            lastColumn = rangeToExpand.CurrentRegion.Column
            lastRow = Cells(rangeToExpand.CurrentRegion.Rows.Count, rangeToExpand.Column).End(xlDown).Row
            Set rangeToExpand = Range(rangeToExpand, Cells(lastRow, lastColumn))
    End Select

    rangeToExpand.ClearContents
End Sub

That way you don't have to check every if every time. If my method is off for the directions, I probably misunderstood the goal of each string, but I don't see them in the original.

Then all you need to do is pass a range and a string to expand and it does all the work. Or make expand a function and pass the range back to the caller.

Also, as I mentioned in the comments, I'm not sure .CurrentRegion is the way to go. If working with A1 in here - these are the CurrentRegions -

You can double check it, I'm on 2007 and just used

Sub testing()
    Dim rng As Range
    Set rng = Range("A1")
    rng.CurrentRegion.Select
End Sub

So anything that's a connection to the cell you've chosen, will be part of the CurrentRegion - even if it's all snakey like that.

So your first picture the CurrentRegion = D5:G40 and the second picture CurrentRegion = D4:L40 assuming the red cell(s) is the selection.

As to how to fix this - I'm not sure. Maybe ask for the input to be the "header" row, but that only works if you want to clear all the way down. It defeats the whole purpose of this. I didn't mean to point out a problem and not provide a solution - sorry.


As far as I can tell, this should be properly tail-call optimized (see this post), but I haven't actually checked.

Consider using AsyncSeq, it could make dealing with asynchronous collections easier.


You should separate concerns whenever possible. Since BLE & HTTP requests are quite different, you could write the following protocols:

protocol Request {
    associatedtype Provider
    var provider: Provider { get }

    func execute()
}

protocol BLERequest: Request {
    typealias Provider = BLEProvider

    var code: UInt { get }
    var characteristic: CBCharacteristic { get }
    var service: CBService { get }
}

protocol HTTPRequest: Request {
    typealias Provider = NetworkProvider

    var data: Data { get }
    var accessToken: String { get }
    var method: HTTPMethod { get }
    var params: [String:Any]? { get }
}

Then comes the magic; you can write generic extensions on your Request protocol, for each specific Request type.

extension Request where Self: BLERequest {
    func execute() {
        // provider is available since it is a get-able requirement,
        // and we know it is a BLEProvider instance
        // same goes for all the other get-able vars
        provider.writeValue(data: code, characteristic: characteristic, service: service)
    }
}

extension Request where Self: HTTPRequest {
    func execute() {
        // Again, same thing, we have all vars we need
        provider.performRequest(data: data, token: accessToken, method: method, params: params)
    }
}

Then, when you are implementing a new Request, all you need to do is implement the requirements for your chosen protocol, and everything else will be handled for you :)

Example:

enum MyBLERequest: BLERequest {
    case getStatus
    case download

    // MARK: BLE Request conformance
    var provider: Provider {
        return BLEProvider(... whatever init is needed)
    }

    var code: UInt {
        switch self {
        case .getStatus: return 0x01
        case .download: return 0x02
        // Any further new case will require you to implement the code here, so you have compile-time safety :)
        }
    }

    var characteristic: CBCharacteristic {
        return CBCharacteristic(.. init)
    }

    var service: CBService {
        return CBService(... more init)
    }
}

Then you can simply do MyBLERequest.getStatus.execute(), and it's all done through the protocol extension code.

And since Swift Enums allow associated values, you can always pass in additional parameters, whenever needed (you could have another case case getAuthToken(byUserID: String), which are then available to you in your implementation)

Now, since you have this all neatly separated, I would go further and pass your Request instances to each specific Provider directly. In effect, you are not the one executing a request, a provider is. That means your requests are agnostic to whatever Provider executes them, which will allow you to set up unit testing easier (because then you can write Mock Providers, and still pass them your requests like usual).

So you should probably extend each provider like such:

extend BLEProvider {
    func execute(request: BLERequest) {
        writeValue(code: request.code,
                   characteristic: request.characteristic,
                   service: request.service)
    }
}


The name ReverseDoublyLinkedList is not so good.  Just stick to DoublyLinkedList.

It would make more sense if the reverse method returned a new instance of the list.  Actually, I would have defined a static method that takes a list and return a reversed list.


This will be shorter, it takes less selects, and may runs at SQL server side

return rep.FindWhere(i => i.ID == itemID)
          .SelectMany(i => i.Batch.Items)
          .Where(i => i.StatusID == (short) ItemStatus.Pending)
          .MaxBy(i => i.NumInBatch).ID;


Capitalize a sequence of lines entered via console input and print/return

Is this pythonic ?

The answer to this question is often found by doing import this:

  Beautiful is better than ugly.
  Explicit is better than implicit.
  Simple is better than complex.
  Complex is better than complicated.
  Flat is better than nested.
  Sparse is better than dense.
  Readability counts.
  Special cases aren't special enough to break the rules.
  Although practicality beats purity.
  Errors should never pass silently.
  Unless explicitly silenced.
  In the face of ambiguity, refuse the temptation to guess.
  There should be one-- and preferably only one --obvious way to do it.
  Although that way may not be obvious at first unless you're Dutch.
  Now is better than never.
  Although never is often better than right now.
  If the implementation is hard to explain, it's a bad idea.
  If the implementation is easy to explain, it may be a good idea.
  Namespaces are one honking great idea -- let's do more of those!

Why is this line not pythonic ? Because it is not readable enough.

  Readability counts.

string = "\n".join([string, inp]) if string and inp else "".join([string, inp])

Why is this line not pythonic ? Because it contains more than one instruction by line

  Sparse is better than dense.

string = ('\n' if string and inp else '').join([string, inp])

Why is this line not pythonic ? Still not the prettiest way of writing that.

  Beautiful is better than ugly.

delimiter = '\n' if string and inp else ''
string = delimiter.join([string, inp])

I will say later in this post why this is still ugly and how to improve this code.

Is a recursive function pythonic ?

No, yes, it's complicated. First, the call stack hell. Every time you call a function, python has to "store" the addresses of the caller into a call stack, the depth of the call stack is 1000, which is not much. So...

while and for are often better than recursive in terms of readability (not always true)
while and for are often better than recursive in terms of performance (not always true)
Everything that can be done in a loop can be done recursively (with python not always true)
Everything that can be done recursively can be done with a while or for loop. (always true)
The stack is the limit. 1000 calls comes quick, for example there are more than 1000 words in this post, it wouldn't be a good idea to use recursion to parse it, it would raise a RecursionError: maximum recursion depth exceeded.

Is my implementation of a recursive function good ?

No, because you pass the accumulator as an argument (classic beginner mistake). You think in terms of loops, even when using recursion. Let's take a look at a simple function.

def sum(l):                  #  No hidden mystery accumulator
    if len(l)==1:            #  The first line is usually the stop condition
        return l[0]          #  Return the last element
    return l[0] + sum(l[1:]) #  Return the first + the sum of the rest

sum(range(42))  # 861

Let's take a closer look at how it calculates this:

def sum(l):
    if len(l)==1:
        return l[0]
    return f"({l[0]}+{sum(l[1:])})"

sum(range(10))  # '(0+(1+(2+(3+(4+(5+(6+(7+(8+9)))))))))'

Impressive !

Now look at your function:

def capitalize_line(string=""):     # Hidden mystery accumulator
    inp = input("enter: ").upper()  # Move this outside of your function
    # This line is already debunked
    string = "\n".join([string, inp]) if string and inp else "".join([string, inp])
    if not inp:
        print(string)    # Move this outside of your function
        return string    # You don't use this but you should
    return capitalize_line(string=string) # not using return as intended
                         # (carrying processed data down the call stack)

  Explicit is better than implicit.

Using stdin and stdout inside a function whose purpose is to capitalize letters is not a good thing. It makes the code impossible to divide because everything is linked. The capitalize function should capitalize and return a string and nothing else.

How should I write it ?

You think I will give you the solution like that... I'm sorry Dave, I'm afraid I can't do that !

Just kidding, but promise me you will try before looking at it:

  def capitalize(l):
    if not l:
        return ''
    return l[0].upper() + '\n' + capitalize(l[1:])

def capitalize(l): # alternative way
    if len(l)==1:
        return l[0]
    return l[0].upper() + '\n' + capitalize(l[1:])

def main(): # Python 3.8 only
    inputs = []
    while s:=input('enter: '): inputs.append(s)
    print(capitalize(inputs))

def main():
    inputs = []
    while True:
        s = input('enter: ')
        if not s:
            break
        inputs.append(s)
    print(capitalize(inputs))

if __name__ == '__main__':
    main()   # In case someone imports your module to use your functions
 But You want to do like the pros don't you ? Use generators
def capitalize(iterable):
    try:
        s = next(iterable)
    except StopIteration:
        return ''
    return s.upper() + '\n' + capitalize(iterable)

def inputs():
    while True:
        s = input('enter: ')
        if not s:
            break
        yield s

Even better (or worse), a recursive generator:
def inputs():
     s = input('enter: ')
     if not s: return
     yield s
     yield from inputs()

def main():
    print(capitalize(inputs()))

Wow, you're still there, it means you had the time to read my entire post, and since you've time on your hands, I recommend you Socratica, more specifically the video about recursion.

And remember, recursion isn't often the best solution.


Receive an array input and output a string

A few stylistic nitpicks: the function body should be indented and there should be a space following the - signs.

getString should be changed to take an array of boolean values, instead of a sparse array of "Y" strings. You can write a separate function to convert your original format to a bool array.

function optionsToBoolArray(array){
    var converted = [];
    for(var i = 0; i < array.length; i++){
        converted[i] = array[i] === "Y";
    }
    return converted;
}

getString is also a undescriptive name for your function. You should change it to something along the lines of optionsToReadableString.

fundMap doesn't need to be an object. Since you are currently using like an array, explicitly make it an array for clarity.

fundString = fundArray + " option"; should be fundString = fundArray[0] + " option"; to avoid implicit conversions for readability.

The code for multiple options can also be simplified by using array methods:

else {
    fundString = fundArray.slice(0,fundArray.length - 1).join(", ") + " and " + fundArray[fundArray.length - 1] + " options";
}

This also lets you eliminate the else if branch.

You should also extract the console.log out of the function to separate the logic. After doing this, you can eliminate fundString completely by just returning the value from each branch of the if/else.

You should also look into learning ES6 features such as using let instead of var.


You said in one of the comments that instead of modifying an existing tree, you would rather create a new tree. In this case, having separate classes for the nodes is acceptable (I wouldn't do it, though). But then, to effectively communicate that you are not going to modify the nodes, all their fields must be final.

I don't understand why you need the NullNode. To me it looks like a waste of memory.

The empty default constructor of LeafNode is unnecessary. In the NullNode class you didn't write it out explicitly, which is better.

At the end of your program you have these lines:

tree = new NonLeafNode(
  new NonLeafNode(new LeafNode(), new NullNode()), new NullNode());

As it is written right now, as a reader I have to carefully count parenteses to see which nodes belong together. This is because the text Node(), new appears almost 3 times. I prefer the following form:

tree = new NonLeafNode(
  new NonLeafNode(new LeafNode(), new NullNode()),
  new NullNode());

Or, if the structure gets even more complicated:

tree = new NonLeafNode(
  new NonLeafNode(
    new LeafNode(),
    new NullNode()),
  new NullNode());

The indentation now corresponds exactly to the depth of the node in the tree. Well, except for the root node, but that should be easy to figure out.

All in all it is a very nice piece of code. You chose really good names for the classes and variables, which is one of the most important things in programming. I also liked that you wrote the expected output in comments. For code that you show to others, this is good so that they don't have to run the code. When you do serious programming, you should replace those comments with proper unit tests.


You are using the Map more like a list...

EDIT: this is NOT working:

You could create an object to hold one translation ({X => {"cake","egg"}) then instead of all the Maps you could use a List (of those translations) and always remove and use the first element and pass the shorter list to the next call of your method.

EDIT: this IS working:

You could use a List with the translation and add an index parameter in you method to know which element from the list use. Then you increment the index once before making the recursive calls...

Here is some code (without constructors getters etc...):

public class Translations {
    final String key;
    final Set<String> translations;
}

public static void addAllReplacements_2 (String source,List<Translations> translationsList, final int index, Set<String> targets) {
    if (index == (translationsList.size())) {
        // no more replacements:
        targets.add(source);
    } else {
        // pick an entry
        Translations translations = translationsList.get(index);
        String text = translations.getKey();
        Set<String> translationValues = translations.getTranslations();

        final int nextIndex = index+1;

        for (String translationValue: translationValues) {
            addAllReplacements_2(
                    source.replace(text, translationValue),
                    translationsList,nextIndex,
                    targets);
        }

    }
}


Validate and Add Service Provider/Location in C#

There are five lines that are repeated three times:

bll.LocationID = ddlLocations.SelectedValue;
bll.IsApproved = "y";
bll.ServiceProviderLocationAdd();
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();

Those should be moved to a separate method to start with. I also don't like that it does two things: update bll and then use bll to update gvServiceProviders; this looks like a mix of UI and business logic.

temp is a really bad name.

At this point we're basically here, if you apply some techniques to reduce the indentation:

protected void btnAddServiceProvider_Click(object sender, EventArgs e)
{
    bll.Name = txtServiceProvider.Text;
    DataTable temp = bll.ServiceProviderCheckExisting();

    if (temp.Rows.Count == 0)
    {
        bll.IsDeleted = "n";
        bll.ServiceProviderAdd();
        temp = bll.ServiceProviderCheckExisting();
        bll.ServiceProviderID = temp.Rows[0][0].ToString();
        Update();
        return;
    }

    bll.ServiceProviderID = temp.Rows[0][0].ToString();
    temp = bll.GetServiceProviderLocationUsingServiceProviderID();

    if (temp.Rows.Count == 0)
    {
        Update();
        return;
    }

    for (int x = 0; x < temp.Rows.Count; x++)
    {
        if (ddlLocations.SelectedValue == temp.Rows[x][1].ToString())
        {
            lblServiceProviderError.Text = "This service provider already exists for that location.";
        }
        else
        {
            Update();
        }
    }
}

(Update() is the method that contains the five lines I mentioned at the beginning. Not a  great method name either.)

Which I find to be an odd flow, to say the least. Which is partly due to not knowing what bll actually is.

To me it feels like some of the code should be re-thought. For instance this:

bll.LocationID = ddlLocations.SelectedValue;
bll.IsApproved = "y";
bll.ServiceProviderLocationAdd();

Why isn't this one single method on bll that takes the value of ddlLocations.SelectedValue as a parameter?

I'm also not fond of ServiceProviderCheckExisting() returning a DataTable, I'd expect it to be more like GetExisting().


First missing positive with only primitives

Stupid edge-cases!
While doing some testing for coming up with a better version for the First missing positive question, I added a bunch of more test cases and compared several different methods with each other. Then I found the following problems:
Input [-5] returned 2147483647 but expected 1
Input [-5, -4, -3] returned 2147483647 but expected 1
Input [0, 0, 0, 0] returned 2147483647 but expected 1
Input [] returned 2147483647 but expected 1

To correct these problems, I added some edge-case checking; to check for array where there are no positive integers. As these really are edge-cases, I haven't decided how to handle these. As there technically isn't a clear "first missing positive number". If I would have handled 7 8 9 as return 1 then I would have returned 1 for these edge cases also, but I feel that wouldn't be expected behavior from this algorithm so therefore I decided to throw an exception.
The new code is:
public int simonNew(int[] array) {
    boolean[] foundIntegers = new boolean[array.length];
    int smallestPositive = Integer.MAX_VALUE;

    for (int i : array) {
        if (i > 0 && i < smallestPositive)
            smallestPositive = i;
    }
    if (smallestPositive == Integer.MAX_VALUE)
        throw new IllegalArgumentException("Array must not be null and must contain at least one positive integer");

    for (int i : array) {
        if (i < smallestPositive)
            continue;

        int index = i - smallestPositive;
        if (index < foundIntegers.length)
            foundIntegers[index] = true;
    }

    for (int i = 0; i < foundIntegers.length; i++) {
        if (!foundIntegers[i])
            return i + smallestPositive;
    }
    return foundIntegers.length + smallestPositive;
}