My custom implementation of MATLAB's imdilate

I have a few different comments.

Firstly, for 2D arrays like in your example, you can simply do conv2(binaryImage,structuringElement,'same'), it's equivalent to imdilate (and about 4 times faster). That might not be acceptable for your case if you are supposed to write the code yourself though.

Next, and importantly, your code has a logic error. If your binary image has a white pixel along any edge, the results are incorrect or you get an error (if it's in the top row). This is due to your indexing into dilatedImage where i+k-2 can be less than 1, or can be larger than the number of rows in dilatedImage.

You have a lot of comments, which is better than none, but I think it's excessive here. It is very clear what this line of code does [imageRows, imageColumns] = size(binaryImage);, for example, even for people who don't know Matlab. Some of your comments make the lines very long as well.

A minor issue, I'd move the imdilate command somewhere else, that part of the code is where you are re-creating imdilate, I think it's nicer to separate the verification part.

Another minor issue is in using i and j as loop indices. Since i and j can be used for complex numbers in Matlab, by convention they are avoided as loop indices (although I do not usually worry about this).

I would put the code that does the work into its own function that takes binaryImage and structuringElement as inputs and returns dilatedImage.

The big thing here is you 6 nested for/if statements, which is hard to read and hard to code. Historically, such nested loops would have been very slow in Matlab, but nowadays it's not such a concern. One thing you should do is swap the order of the first two for loops. Matlab stores arrays in a column major format, so loop over the columns first, then the rows. This gives roughly a 20-25% speedup in my tests. Additionally, checking to remove the out-of-bounds error is also a speedup, since we only set pixels to one if they are inside the image, irregardless of the value of the structuring array. Check out this version of your loop:

for j = 1:imageColumns
    for i = 1:imageRows
        if binaryImage(i, j) == 1
            % Loop through the entries of the structuring element
            for l = 1:structuringColumns
                for k = 1:structuringRows
                    % make sure the new pixel is inside the image
                    if  i+k-2>0 && j+l-2>0 && i+k-2<=imageRows && j+l-2<=imageColumns
                        % make a white pixel if necessary
                        if structuringElement(k, l)==1
                            dilatedImage(i + k - 2, j + l - 2) = 1;
                        end
                    end
                end
            end
        end
    end
end

Of course it would be nice to avoid writing all these loops, and that can be done. This next method is only slightly faster, but to me is cleaner. The idea is to first find the white pixels, and just loop over them, for each one working out which surrounding pixels should be changed.

[rowIdx,colIdx] = find(binaryImage); % the indices of white pixels in the image
[maskRowIdx,maskColIdx] = find(structuringElement); % indices of structuring elements

% now get indices of structuring elements relative to the centre of the array
maskRowIdx = maskRowIdx - floor(structuringRows/2) - 1;
maskColIdx = maskColIdx - floor(structuringColumns/2) - 1;

dilatedImage = zeros(imageRows, imageColumns);

% loop over each white pixel in the image
for i = 1:numel(rowIdx)
    % these are just the indices of the pixel
    rI = rowIdx(i);
    cI = colIdx(i);

    % now loop over each non-zero element of the structuring array
    for j = 1:numel(maskRowIdx)
        % the position of the pixel to change is (r,c)
        r = rI+maskRowIdx(j);
        c = cI+maskColIdx(j);

        % if the pixel is inside the image, we make it a 1
        if r>0 && c>0 && r<=imageRows && c<=imageColumns
            dilatedImage(r,c) = 1;
        end
    end
end


Yes, you can make it less verbose.

I assume you are using AutoFixture in you call to Create()?

If so, this will create random values out of the box. No need to specify the content and assign each property. Create the source object for mapping, map it, compare the mapped values with the properties on the source object:

    [Test]
    public void Map_Always_SetsSimpleProperties()
    {
        var doc = fixture.Create<Notification223>(); // Autofixture will fill properties with random data.
        var sut = CreateSut();

        var actual = sut.Map(doc);

        Assert.That(actual.AuctionPlace, Is.EqualTo(doc.AuctionPlace));
        Assert.That(actual.SubmissionCloseDateTime, Is.EqualTo(doc.SubmissionCloseDateTime));
        Assert.That(actual.QuotationForm, Is.EqualTo(doc.QuotationForm));
        Assert.That(actual.QuotationExaminationDateTime, Is.EqualTo(doc.QuotationExaminationDateTime));
        Assert.That(actual.EnvelopeOpeningTime, Is.EqualTo(doc.EnvelopeOpeningTime));
        Assert.That(actual.EnvelopeOpeningPlace, Is.EqualTo(doc.EnvelopeOpeningPlace));
        Assert.That(actual.AuctionDateTime, Is.EqualTo(doc.AuctionDateTime));
        Assert.That(actual.ApplExamPeriodDateTime, Is.EqualTo(doc.ApplExamPeriodDateTime));
        Assert.That(actual.ConsiderationSecondPartDate, Is.EqualTo(doc.ConsiderationSecondPartDate));
    }


class Card {
    readonly Ranks rank;
    readonly Suits suit;
    // ...
}

In this type definition, there is a grammatical mismatch: Ranks rank has a plural type name but a singular variable name.
The types Ranks and Suits should be renamed to Rank and Suit, to make the code more consistent.


Validity of macro for printf() call in a corporate environment

Although the C standard can allow void main() under certain implementations, it's best to use int main() whenever possible.  See this for more info on the return type of main().
A loop is not a good use of a macro:

#define printS for(i=0;s[i];i++){printf("%c",s[i]);}

It should instead be a function:

void printS()
{
    for (i = 0; s[i]; i++)
    {
        printf("%c",s[i]);
    }
}

#define is a pre-processor directive (or a macro) that will replace the designated piece of code with something else.  While you can use this with loops, it's still discouraged as there are cleaner alternatives in C, such as functions.
Your two variables above main() are in global scope, which is almost always discouraged.  Anything in global that's not a constant can be modified anywhere in the program, which can introduce bugs and hurt maintenance.  You should keep variables as close in scope as possible, such as in functions.  You can then pass them to other functions as needed.

Assuming this is pre-C99, i should be declared right before the loop.  Otherwise, it should be initialized within the loop statement.
Functions in C that take no arguments should have a void parameter:

void main(void)

Consider adding more whitespace between operators for more readability.

Using your single-line loop as an example:

for(i=0;s[i];i++){printf("%c",s[i]);}

You could have something like this:

for (i = 0; s[i]; i++) { printf("%c", s[i]); }

Implementation with changes applied:

#include <stdio.h>

void printS(char s[])
{
    int i;
    for (i = 0; s[i]; i++)
    {
        printf("%c", s[i]);
    }
}

int main(void)
{
    char s[] = "Hello World!\n";
    printS(s);
}


Integer-to-ASCII algorithm (x86 assembly)

There are all sorts of things that LOOK like they should perform better, but I can only get a tiny bit of improvement.  And that may disappear (or worsen) on other hardware:

    mov ebx, 0xCCCCCCCD
    xor rdi, rdi

.loop:
    mov ecx, eax                    ; save original number

    mul ebx                         ; divide by 10 using agner fog's 'magic number'
    shr edx, 3                      ;

    mov eax, edx                    ; store quotient for next loop

    lea edx, [edx*4 + edx]          ; multiply by 10
    shl rdi, 8                      ; make room for byte
    lea edx, [edx*2 - '0']          ; finish *10 and convert to ascii
    sub ecx, edx                    ; subtract from original number to get remainder

    lea rdi, [rdi + rcx]            ; store next byte

    test eax, eax
    jnz .loop

The 2 changes are:

Move shl rdi to a 'better' place
Use lea instead of or to set rdi


Project Euler 78: Coin Partitions in Python

1. Debugging

The first version of your code was broken because you used the expression

(-1)**(k-1)

where k is sometimes negative. The documentation says:

  For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered.

(my emphasis) so when k was negative, this expression evaluated to a float, either 1.0 or -1.0, and then the usual rules of arithmetic conversion caused all the other intermediate results to become floats too. Floats have limited precision, so eventually these were approximate rather than exact.

How did I discover this? Well, I ran the program under the Python debugger:

$ python -m pdb cr93311.py
> cr93311.py(1)<module>()
-> partitions = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42]

I wanted to see what values actually showed up in the partitions list, so I set a breakpoint on line 17 (just after the partitions.append):

(Pdb) break 17
Breakpoint 1 at cr93311.py:17

And then I continued to the breakpoint and printed the partitions array:

(Pdb) continue
> cr93311.py(17)<module>()
-> n += 1
(Pdb) p partitions
[1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56.0]

The 56.0 stands out immediately as an error: it should be 56. (Possibly this was not obvious to you: in which case you might appreciate David Goldberg's article "What Every Computer Scientist Should Know About Floating-Point Arithmetic" or the beginner's version thereof.)

How did this floating-point number get there? Let's find out by restarting the program and setting a breakpoint on line 14, just after the computation of pentagonal and temp:

(Pdb) run
Restarting cr93311.py with arguments:
        cr93311.py
> cr93311.py(1)<module>()
-> partitions = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42]
(Pdb) break 14
Breakpoint 2 at cr93311.py:14
(Pdb) continue
> cr93311.py(14)<module>()
-> if k > 0: k *= -1
(Pdb) p pentagonal, temp
(1, 42)

Nothing wrong there; let's try the next iteration of the loop:

(Pdb) continue
> cr93311.py(14)<module>()
-> if k > 0: k *= -1
(Pdb) p pentagonal, temp
(2, 30.0)

So it's the computation of temp that wrongly converted to float. Let's check the sub-expressions of that computation:

(Pdb) p k, (-1)**(k - 1), pentagonal, partitions[n - pentagonal]
(-1, 1.0, 2, 30)

So it's the (-1)**(k - 1) that's the culprit.

2. Review

It is easier to test and measure code if it is organized into functions. Functions can be tested and timed independently of each other, making it possible to isolate an error or a performance problem.
Functions should be given docstrings describing what they do, so that it's possible to check the implementation against the documentation.
When a function produces a sequence of results it's usually convenient in Python to generate those results using the yield statement. That way, we don't have to commit in advance as to how many results we are going to compute (as we would if the function returned a list), and we don't have to store all the results in memory at once.
It is easier to test functions if they have adjustable parameters (instead of fixed constants like 1000000) so that we can run and check them on small inputs.

So I would break up the code into functions, like this:

def pentagonal():
    """Generate the generalized pentagonal numbers."""

def partitions_modulo(m):
    """Generate the partition numbers modulo m."""

def problem78(m=10**6):
    """Return the least value of n for which the partition number p(n) is
    divisible by m."""

This makes the code easy to test on small instances:

>>> from itertools import islice
>>> list(islice(pentagonal(), 16))
[1, 2, 5, 7, 12, 15, 22, 26, 35, 40, 51, 57, 70, 77, 92, 100]
>>> list(islice(partitions_modulo(100), 16))
[1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 1, 35, 76]
>>> problem78(23)
32

and easy to measure:

>>> from timeit import timeit
>>> timeit(problem78, number=1)
9.393578507006168

3. Performance

Your best bet is to use PyPy — this kind of simple numerical code is where PyPy really shines. I get more than ten times speedup simply from running the code in the post under PyPy.

If you're determined to stick with CPython, then here are some techniques I found that were helpful:

Only generating as many generalized pentagonal numbers as necessary: it turns out that we only need the first 200 or so, not the first 2000.
The generalized pentagonal numbers are $$ 0, 1, 2, 5, 7, 12, 15, 22, 26, 35, 40, 51, 57, 70, \dotsc $$ If we take the differences between consective elements, we get the sequence $$ 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, \dotsc $$ whose \$n\$th item is \$n\$ if \$n\$ is odd, or \$n\over 2\$ if \$n\$ is even. This means that the generalized pentagonal numbers can be generated using itertools.count and itertools.accumulate, like this:

accumulate(k if k % 2 else k // 2 for k in count(1))

The signs repeat in the cycle $$ 1, 1, -1, -1, 1, 1, -1, -1, \dotsc $$ and so they can be generated using itertools.cycle, like this:

cycle((1, 1, -1, -1))

Using sum instead of explicit accumulation.

But the revised code is only about twice as fast as the original:

from itertools import accumulate, count, cycle, islice

def pentagonal():
    """Generate the generalized pentagonal numbers starting at 1.

    >>> list(islice(pentagonal(), 16)) # http://oeis.org/A001318
    [1, 2, 5, 7, 12, 15, 22, 26, 35, 40, 51, 57, 70, 77, 92, 100]

    """
    return accumulate(k if k % 2 else k // 2 for k in count(1))

def partitions_modulo(m):
    """Generate the partition numbers modulo m.

    >>> list(islice(partitions_modulo(1000), 16)) # http://oeis.org/A000041
    [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176]

    """
    signs = 1, 1, -1, -1
    partitions = [1]          # Partition numbers up to p(n)
    pentagonals = []          # Generalized pentagonal numbers <= n
    pentagonal_it = pentagonal() # Iterator over generalized pentagonal numbers
    next_pentagonal = next(pentagonal_it)

    yield 1
    for n in count(1):
        if next_pentagonal <= n:
            pentagonals.append(next_pentagonal)
            next_pentagonal = next(pentagonal_it)
        p = sum(sign * partitions[-pent]
                for sign, pent in zip(cycle(signs), pentagonals)) % m
        partitions.append(p)
        yield p

def problem78(m=10**6):
    """Return the least value of n for which the partition number p(n) is
    divisible by m.

    >>> problem78(23)
    32

    """
    return next(i for i, p in enumerate(partitions_modulo(m)) if p % m == 0)


Categorizing gene sequences read from a CSV file

Yeah, the problem is the switch: you have the same set of  if-elif-else conditions duplicated in two places. Chances are that as your program grows, you will add more replicas of these chains. The problem with these chains is that if later you need to add one more case in the middle, you will need to modify all replicas accordingly. This is error prone, as you might not remember all the places where you replicated the chains.

How can we deal with that better? Can we replace these chains with something else, in a way that if we add a new case in the Gene constructor, we can be free from worrying about the rest of the program?

At least in this example, there is a workable solution. Consider these 3 lists:

refseqs = []
ensembl_genes = []
ensembl_transcripts = []

These lists are an important part of the problem. They mirror the currently supported 3 types, and when you put items in these lists, you need to refer to these lists by these names exactly.

Instead of these lists, you could use a dictionary of lists, where the keys are the gene types, and the values are lists. Something like this:

genes = dict()

with open(csv_gene_list, 'r', newline='') as csv_input:

    reader = csv.reader(csv_input, delimiter=',')
    next(reader)
    for row in reader:
        row_gene_symbol = row[0]
        row_gene_id = row[1]

        row_gene = Gene(row_gene_symbol, row_gene_id)

        if row_gene.row_gene_id not in genes:
            genes[row_gene.row_gene_id] = []

        genes[row_gene.row_gene_id].append(row_gene)
        # ...

In this form the chain is gone, and the second part of your question is naturally gone too.

As @jaime pointed out in a comment, this can be greatly simplified:

if row_gene.row_gene_id not in genes:
    genes[row_gene.row_gene_id] = []

genes[row_gene.row_gene_id].append(row_gene)

Using setdefault like this:

genes.setdefault(row_gene.row_gene_id, []).append(row_gene)


My critique is mostly on the crypto.

Never invent your own crypto. It's difficult to do correctly, and there are already good libraries for this sort of thing. See sinatra-authentication or bcrypt-ruby.
rand() is not a cryptographically secure random number generator, so it's a poor choice for use in crypto. Also see point #1.
Your password salting is incorrect. The salt must be mixed with the password before hashing, not after. Also see point #1.
Why append the length_of_salt_and_hash? That seems pointless.
Why append salt + hashed_pass? These are usually stored as separate fields in a database record.
Avoid magic numbers like 61 in your code. What does Roger Maris have to do with this? It's unclear and redundant that this 61 refers to the length of the string on the next line.
You ask for "better or more verbose." Those are often opposite goals. More verbose code means more code to read and more code to maintain. (That does not mean you should prefer cryptic one-liners.)


There are a couple of constructs in there that can be improved.

string.Join("", charArray), repeated a lot. string has a constructor that takes a char[], which is a lot faster. They are both linear time, which your question seems to focus on, but in terms of actual efficiency the difference is nearly two orders of magnitude in some tests (actual impact of course varies).
new Stack(), so.. the old stack, from the .NET 1.1 days? Don't use that one, use Stack<T>. Especially if the things you're putting in them are value types, which would have to be boxed in the old non-generic Stack.

For ReverseString_ForEachConcat, I don't agree that the time complexity is O(n). At every step, the old string is copied over into the new string, with something concatenated in front of it. So in the second iteration there is 1 copied character, in the third iteration there are 2 copied characters etc. That's a classic O(n²) pattern.

I think we could also argue about whether or not it takes constant space. The many old versions of the string can disappear quickly, but while the concatenation is happening, both the old string and the result of the concatenation need to exist. In the last iteration, that means that while the final result is being made (the size of which doesn't count), there is an other string in play of nearly the same size, so O(n) worth of auxiliary space.


//elements that don 't change should be declared in a scope that doesn't
 //get executed all the time to avoid redundant opearation
var content = $(".content", $page);

function renderSourceItems(items) {

  //JS normally pulls up variable declarations, even when declared
  //anywhere. To avoid readability issues, it's best you declare
  //them up here
  var column, list;

  //the "return early" or "blacklist" method returns if any anomalies
  //are found earlier in the code. That way, you don't use nested ifs
  if (!items) {
    content.html('<p> No Data Found </p>');
    return;
  }

  //down here, it's assumed that items does exist and has content

  column = _.keys(items[0])[0];
  content.empty();

  //depending on the browser, DOM strings vs jQuery DOM vary in
  //performance. Since it varies, I'd rather improve readability
  //by using one of them that's more readable, where in my case
  //it's jQuery DOM building
  list = $('<ul/>', {
    "data-role": "listview",
    "data-filter": "true",
    "data-theme": "c"
  });

  //our recursive function using setTimeout to avoid freezing UI
  (function looper(i) {

    var value, item;

    if (!(i % 100)) {
      value = items[i][column];

      //each item gets built using our readable method
      //here we make a list item and append to it a link with
      //the given data
      item = $('<li/>').appendTo(list);
      $('<a/>', {
        'href': '#apage ',
        'data - column ': column,
        'data - value ': value
      }).text(value || ' [No Value]').appendTo(item);

    }

    setTimeout(function () {
      if (++i < items.length) {
        //when not yet the last item, repeat
        looper(i);
      } else {
        //else we end

        //now you notice that we only append the list to the DOM down here
        //why not append it beforehand? The issue is DOM access - it's slow!
        //we take advantage of jQuery using DOM fragments, DOM elements that
        //are not in the DOM and just operate off-DOM. We only append
        //to the DOM after everything is completed, thus minimizing
        //DOM access from items.length times to just 1
        list.appendTo(content).listview("refresh");
      }
    }, 200);

    //start with index 0
  }(0));

}


Find the smallest number in the first array that is not in the second one

Why do you make your arrays only 10 elements large when the task explicitly says 20?

Even worse, you don't protect the program from writing outside the array. The C programming language doesn't protect against this wrong behavior, therefore you as the programmer must do this.

Before every write to an array you must check that the array index is valid. For example:

assert(0 <= idx && idx < arr_len);
arr[idx] = value;

Only if you can prove mathematically that the assert condition is always true, can you leave out the assert. Follow this advice, and your programs will be better than 80% of the existing C programs.

To reduce the complexity of the main function, you should define a function like this:

bool intarray_contains(const int *arr, size_t arr_len, int value) {
    ...
}

Then you don't need to write this code in main.

After that, to ensure that your program works correctly (it currently doesn't), you should extract the calculation into a separate function:

int min_not_present_in(const int *arr1, size_t arr1_len, const int *arr2, size_t arr2_len) {
    ...
}

This function definition allows you to do the calculation without entering the values every time. Like this:

int positive[] = { 1, 2, 3 };
int odd[] = { 1, 3, -1 };
int even[] = { -2, 0, 2 };

assert(min_not_present_in(positive, 3, odd, 3) == 2);
assert(min_not_present_in(positive, 3, even, 3) == 1);

To make all this work, you need the following lines at the top of your file:

#include <assert.h>
#include <stdbool.h>


jQuery hover and click events for a five-star rating

I couldn't see the Unicode stars in 200_success's answer on Chrome, so I made a version of their snippet with SVG stars from an old meta.SO post of mine:

$('.modal-review__rating-order-wrap > span').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
    $(this).parent().attr('data-rating-value', $(this).data('rating-value'));
});
/* Initial state */
div.modal-review__rating-order-wrap > span {
    display: block; float: left;
    height: 30px; width: 40px;
    background-image: url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='80'%20height='30'%3E%3Cpath%20d='M17.5,12.5h-8.5l6.8,5-2.6,8.1,6.8-5,6.8,5-2.6-8.1,6.8-5h-8.5l-2.6-8.1z'%20fill='%23c0c0c0'%20stroke='%23c0c0c0'/%3E%3Cpath%20d='M57.5,12.5h-8.5l6.8,5-2.6,8.1,6.8-5,6.8,5-2.6-8.1,6.8-5h-8.5l-2.6-8.1z'%20fill='%23ffd83d'%20stroke='%23eac328'/%3E%3C/svg%3E");
    background-position: 0px 0px;    /* gray star */
}

/* Persistent state */
div.modal-review__rating-order-wrap[data-rating-value] > span {
    background-position: -40px 0px;  /* gold star */
}
div.modal-review__rating-order-wrap > span.active ~ span {
    background-position: 0px 0px;    /* gray star */
}

/* Hover state */
div.modal-review__rating-order-wrap[class]:hover > span {
    background-position: -40px 0px;  /* gold star */
}
div.modal-review__rating-order-wrap[class] > span:hover ~ span {
    background-position: 0px 0px;    /* gray star */
}

Note that I had to add [class] as a specificity hack to the last two CSS selectors, since otherwise the third selector (with .active) would override them.  (In 200_success's version, the :after pseudo-classes effectively serve the same function, but my version doesn't use them.)

I also made the inner spans into floating blocks to eliminate any whitespace gaps between them, since those cause annoying "blinking" effects when moving the mouse over the gap.  Flex layout on the outer div could be used to achieve the same effect.

Note that I've marked this "answer" as Community Wiki, since it's basically just an addendum to another answer.  I'd have posted it as a comment, but you can't include snippets in comments.  I didn't feel presumptuous enough to edit this into their answer directly, but if 200_success wants to do so, I'm happy to delete this "meta-answer".


Well, you already identified the main issue with your code, and I concur: the imperative style. Also, note that this code should have two loops and you are doing it all in one, that's why you have to use flags all over the place. Since you asked for a functional solution, no while nor loop,  use recursion:

def guess_number(number_to_guess)
  guess = gets.to_i
  if guess == number_to_guess
    puts("You found the correct number: #{number_to_guess}")
  else
    puts(guess > number_to_guess ? "Too high" : "Too low")
    guess_number(number_to_guess)
  end
end

def game
  puts('Find the magic number between O and 9')
  guess_number(rand(10))
  print('Another try? (Y/N): ')
  if gets.strip.downcase == "y"
    game
  end
end

game

If you want to validate the input, create a method def get(validation_regexp) and use it: get(/^\d+$/) and get(/^[yYnN]$/).


Any problems in using hibernate's session.connection() to run native sql

Since Hibernate session provides APIs to run native SQL queries, I would avoid extracting the connection from the session and leave the life cycle management of the Statement, ResultSet used for running native queries, to Hibernate Session itself. There must be some reason why they discourage the use of connection like this, directly and so it is being deprecated.


Insert new row to a QTableView by double-clicking the last row

Your answer is a good one, but it has that non-editable last row hanging around. If you want to make the extra row editable, you can do as shown here. The idiom of hitting a return in the current last row that produces an empty row, is a standard one.

I don't believe there is a built-in mechanism in Qt.

A variation of the approach found in the above link

In my app, I use a slightly different approach, and thought I would share it here. For convenience, I summarize both approaches here.

In the answer at the above link, both MyTableModel and MyBlankRowModel are derived from QAbstractTableModel, and the former is set as a sourceModel in the latter. This idiom implies that all QAbstractTableModel methods overridden in MyTableModel must be re-implemented in MyBlankRowModel, mostly forwarding to the MyTableModel methods, with exceptions as noted in that answer. This approach can be cumbersome if a large number of QAbstractTableModel methods are overridden in MyTableModel as is the case in my app.

Therefore I derive MyBlankRowModel from MyTableModel, only override a few methods: rowCount() returning MyTableModel::rowCount() + 1; data(...) and setData(...) to handle the row buffer. This offers the flexibility that MyTableModel can be designed to handle a complex model, and nothing in MyBlankRowModel has to change! It also simplifies the view interaction since I simply do qTableView->setModel(myBlankRowModel).


Creating range of numeric values based on array of strings

If a method returns an IEnumerable<T> we expect an deffered execution using the yield keyword.

To make this happen and have a valid parameter validation we need another method which calls the method which is yielding.

So let us add one

public static IEnumerable<string> GetRangeSegments(string[] segments, string rangeIndicator)
{
    if (segments==null) { throw new ArgumentNullException(nameof(segments)); }
    if (rangeIndicator == null) { throw new ArgumentNullException(nameof(rangeIndicator)); }
    if (string.IsNullOrWhiteSpace(rangeIndicator)) { throw new ArgumentException("May not be empty.", nameof(rangeIndicator)); }

    return GetSegments(segments, rangeIndicator);
}

All the if statements will be executed and if the code comes to return it will immediately return because it knows about the yieldings in the GetSegments() method.

Using yield makes the empty string[] rangeSegments superflous because we just yield break. If you call ToArray() on the result of these yield break you get an empty array.

Because you can access the chars of a string by using its index you don't need ToCharArray().

If there isn't by some mistake either rangeStart[diffIndex] or rangeEnd[diffIndex] a digit the code blows up at the call to int.Parse(). A better way would be to use int.TryParse() and if this doesn't succeed you could yield break.

But if we e.g do int start = rangeStart[diffIndex] + 1; then the ascii value of that char will be casted to an int which we then can check if 47 < start < 58 and if not we yield break here.

The return statmenet in your method is just unreadable, hence hard to maintain as well. To "replace" a single char inside a string we can just use a StringBuilder.

Summing all up lead to

public static IEnumerable<string> GetRangeSegments(string[] segments, string rangeIndicator)
{
    if (segments == null) { throw new ArgumentNullException(nameof(segments)); }
    if (rangeIndicator == null) { throw new ArgumentNullException(nameof(rangeIndicator)); }
    if (string.IsNullOrWhiteSpace(rangeIndicator)) { throw new ArgumentException("May not be empty.", nameof(rangeIndicator)); }
    return GetSegments(segments, rangeIndicator);
}

private const int ascii0 = 48;
private const int ascii9 = 57;
private static IEnumerable<string> GetSegments(string[] segments, string rangeIndicator)
{
    var rangeIndicatorIndex = Array.IndexOf(segments, rangeIndicator);

    if (rangeIndicatorIndex < 0 || rangeIndicatorIndex == segments.Length - 1)
    {
        yield break;
    }

    var rangeStart = segments[rangeIndicatorIndex - 1];
    var rangeEnd = segments[rangeIndicatorIndex + 1];

    if (rangeStart.Length != rangeEnd.Length)
    {
        yield break;
    }

    var diffIndex = GetFirstDifferentCharPosition(rangeStart, rangeEnd);
    if (diffIndex == -1)
    {
        yield break;
    }

    var start = rangeStart[diffIndex] + 1;
    if (start < ascii0 || start > ascii9) { yield break; }

    var end = rangeEnd[diffIndex];
    if (end < ascii0 || end > ascii9) { yield break; }

    if (end < start) { yield break; }

    StringBuilder sb = new StringBuilder(rangeStart);
    for (int i = start; i < end; i++)
    {
        sb[diffIndex] = (char)i;
        yield return sb.ToString();
    }

}
private static int GetFirstDifferentCharPosition(string first, string second)
{
    var diffIndex = -1;

    for (var i = 0; i < first.Length; i++)
    {
        if (first[i] != second[i])
        {
            diffIndex = i;
            break;
        }
    }
    return diffIndex;
}


Q: How can the algorithm of the function be improved?

A: I'm not sure what you mean by algorithm. There are several things relating to functionality that you should improve on, however:

Make an enum to represent what modes are accepted by your function, and use that instead of taking a char. This will greatly reduce the potential for bugs and makes you less reliant on magic "numbers" (or characters, if you will).
You might want to remove the biggest drawback your function has compared to scanf and friends, which is lack of flexibility. The great strength of scanf is that its format string is extremely variable and can be used to extract data from a vast variety of formats. You approach currently limits you to a single char worth of format specifier, and is thus much more rigid and less adaptable. Depending on what you want from your function, this might be acceptable or even desired, but if you really want to contest with scanf, you should come up with a good idea of two on how to improve flexibility.
Remove the hard limit on length. Why do you arbitrarily only read 20 chars? This is just barely sufficient for 64bit integers, but will quickly prove as too little as soon as you start reading different types of data (especially strings).
Add some error reporting facility to your function. What if you tried to read an int when there was none? You might want to tell your users about this (actually, you absolutely must tell your users about this, or your user interface is quickly going to take a turn into an unpleasant direction).
You state in you question that gets_s is useless for streams different from stdin, but that criticism also applies to your function. Consider taking a stream handle as your first argument and reading from that instead. You can still provide another function which has stdin implied, for convenience's sake.

Q: Don't I need to free() in every case?

A: Yes, you absolutely do. Every buffer that allocated via malloc and friends should be freed at some point, otherwise you've got yourself a memory leak. Actually, you might not even want to allocate things on the heap at all. If all I want to do is read a single integer, I usually don't want to incur the cost of calling out to the OS to reserve some memory for me, when I could just read the value into a local variable. How do you do this? Easy enough, instead of taking care of allocation yourself, hand that task over to the user and just accept a pointer instead, i.e.

void scano(char mode, void* buffer);

This has the added benefit of opening up the return value slot, so now you can actually use that to indicate whether an error occured:

int scano(char mode, void* buffer);

or even better

err_code scano(char mode, void* buffer);

where err_code is an enum containing all the possible error values. This pattern of returning an error indicator is really common throughout the standard library and most C applications in general.

Q: Is it fully safe? If not, how can it be made safe?

A: That depends on your definition of "fully safe". If you mean "has no undefined behavior", then the answer is no, sadly. atoi causes such undefined behavior in the case that the integer it is trying to parse is out of range for the int type. The same is true for atof, so you would need to brace against those cases (by not using those two functions, usually). Another problem is that you don't check for malloc failure - if allocation fails, you get a null pointer and subsequently try to write the result of atoi or atof to it, which also causes undefined behavior. Another point of insecurity is your call to fgets: If reading fails completely, your array remains uninitialized. The subsequent call to strlen is then undefined behavior.

Other things that aren't quite right

You don't need to cast the return value of malloc, or any other function returning void*. In fact, this can lead to subtle bugs when making changes to your code later on.
Don't rely on magic numbers. Instead of typing fgets(sData, 20, stdin), pull that 20 out to its own constant, or, at the very least, do something like fgets(sData, sizeof buf, stdin). That way, you're way less prone to buffer overflow bugs arising from you forgetting to change one of the two 20s when you go back and edit your code.
*(sData + strlen(sData) - 1) = '\0'; //get rid of the '\n' before the '\0' ...and now you've overwritten part of your data! There might not actually be an '\n' there, if the line you are reading from has still 19 or more characters left. Check for those kinds of things before writing into your string!


A couple of format rules like:

Is a good practice declare first and then use it. Is not a big deal, but is a good practice.
Try to use, Pascal Case for constructors, and camelCase for methods.
You can replace some repeated function with inheritance javascript

Also, try to don´t abuse of the this. In javascript is a little tricky and can be changed depending of the context.
For default values use

var something = original Value || default Value;

also, last thing most important for your calculator, take a look to the javascript floating points troubles maybe you can get wrong results.


Minimalistic, self-contained class for reading a sectionless INI file

Include (only) what you use

This class uses nothing from <iostream>, so it's a waste of the compiler's time to include it.

Control the public interface

Is trim() really a facility that should be a part of SectionlessINIReader?  I don't think it belongs in the public interface, and more likely belongs in a private or protected section.

Make it easier to use

The getLong() member function has an awkward interface, requiring the user to pass an lvalue (worse, a pointer).  Consider returning a std::optional<long> instead, to convey the result in a single value.

Pass strings by const reference

There's no need to make a copy of the key argument to the accessors - that should be declared as const std::string& key instead.

Accessors should be const

get() and getLong() both modify dict (they create a new empty mapping for any requested key that doesn't yet exist).  We don't want to do that, as it's wasteful.  We would have spotted this bug if we'd declared those members const (so that they could be used by code with only a const reference to the reader - that will be important if we later add writing functions).

We could write:

std::optional<std::string> get(std::string key) const
{
    auto const it = dict.find(key);
    if (it == dict.end())
        return {};

    return it->second;
}

And getLong() could use it:

std::optional<long> getLong(std::string key) const
{
    auto const value = get(key);
    if (!value.has_value())
        return {};

    return std::stol(value.value());
}

Open the code to extension

At present, the only way to add more types that can be read is to edit this class or to subclass it.  And it's not designed for subclassing (it has a non-virtual destructor), so it's closed to end-users.

One way to make it open for extension is to separate the string-to-value conversion from the string lookup, and allow users to specialize that part; our code could then use the appropriate specialization, or fail to compile if no conversion has been defined.

This would be the starting position:

namespace convert {

    // This function must be specialized for any extension types to
    // convert from string to value.
    template<typename T>
    std::optional<T> fromString(const std::string&);
}

It's used in our get<>() function quite simply:

template<typename T>
std::optional<T> get(const std::string& key) const
{
    auto const value = get(key);
    if (!value.has_value())
        return {};

    return convert::fromString<T>(value.value());
}

We could provide some common conversions:

template<>
std::optional<std::string> convert::fromString(const std::string& s)
{ return s; }

template<>
std::optional<long> convert::fromString(const std::string& s)
{ return std::stol(s); }

template<>
std::optional<double> convert::fromString(const std::string& s)
{ return std::stod(s); }

Users can add their own conversions in similar manner.

Variation

Instead of creating a free function to specialize, we could make fromString() be a private static member function of SectionlessINIReader.  The choice may well depend on whether you might want to use fromString() from anywhere else.

Think about exceptions

std::stol() will throw an exception if the value can't be parsed as a long.  Do we want to pass this straight to our callers, or do we want to treat malformed values the same as missing values, and simply return an empty std::optional?  (There's no right or wrong answer here; I just want to be sure that we've made a conscious choice.)

Avoid narrowing conversions

    int idxEq;
    ...
        if (((idxEq = line.find("=")) != std::string::npos)) {

Here, we assign the result of find() (a size type) to idxEq (a signed integer) and then compare idxEq to std::string::npos (a size type again).  That's a potentially narrowing conversion which could change the sign, and a comparison between types of different signedness.  I know we don't expect keys to be long enough to overflow int, but it would be nice to silence the compiler warning here, and it's very easy to make it consistent:

    std::string::size_type idxEq;

Check the result of filesystem operations

In the constructor, we call file.close(), but never check the result.  If we want to be sure that we read the complete file, we need to ensure that close() has succeeded.

If we really don't care about whether we missed some data, then we could simply omit the close() and let the file's destructor do that for us - but I don't advise ignoring a failed close.

Inefficient use of search

There's no need to search all the way through a string just to see what its first character is:

if (line.find_first_not_of(";#") == 0)

It's clearer to examine the first character directly (after checking that the line has at least one character, of course).

Check for duplicate keys

When reading, we simply overwrite any key that appears more than once.  Consider emitting a warning, or throwing an exception.

Remove dead code

There's a remnant of some old code still hanging around, which should be deleted:

// bool getDouble(...)

Modified code

#include <fstream>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>

class SectionlessINIReader
{

private:
    std::map<std::string, std::string> dict = {};

public:
    SectionlessINIReader(const std::string& filename)
    {
        auto file = std::ifstream {filename};
        readStream(file);
    }

    SectionlessINIReader(std::istream& in)
    {
        readStream(in);
    }

    std::optional<std::string> get(const std::string& key) const
    {
        auto const it = dict.find(key);
        if (it == dict.end())
            return {};

        return it->second;
    }

    template<typename T>
    std::optional<T> get(const std::string& key) const
    {
        auto const value = get(key);
        if (!value.has_value())
            return {};

        return fromString<T>(value.value());
    }

private:

    // https://stackoverflow.com/a/1798170/3516684
    static std::string trim(const std::string& str,
                            const std::string& whitespace = " \t")
    {
        const auto strBegin = str.find_first_not_of(whitespace);
        if (strBegin == std::string::npos)
            return {}; // no content

        const auto strEnd = str.find_last_not_of(whitespace);
        const auto strRange = strEnd - strBegin + 1;

        return str.substr(strBegin, strRange);
    }

    template<typename T>
    static std::optional<T> fromString(const std::string&);

private:

    void readStream(std::istream& in)
    {
        std::string line;
        while (std::getline(in, line)) {
            if (line.empty() or line[0] == ';' or line[0] == '#') {
                continue;
            }
            auto const idxEq = line.find('=');
            if (idxEq == line.npos) {
                // consider reporting an error here
                continue;
            }

            auto const key = trim(line.substr(0,idxEq));
            auto const value = trim(line.substr(idxEq+1));
            if (!dict.emplace(key, value).second) {
                throw std::runtime_error("Duplicate key in INI file");
            }
        }
        if (!in.eof()) {
            throw std::runtime_error("Failed to read INI file");
        }
    }
};

// String converters
template<>
std::optional<std::string> SectionlessINIReader::fromString(const std::string& s)
{ return s; }

template<>
std::optional<long> SectionlessINIReader::fromString(const std::string& s)
{ return std::stol(s); }

template<>
std::optional<double> SectionlessINIReader::fromString(const std::string& s)
{ return std::stod(s); }

// we can add more specializations here, and user may also add
// specializations.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream contents("age = 30\n"
                                "favourite_drink = tea\n"
                                "name = Bob\n");

    const SectionlessINIReader ini(contents);
    auto age = ini.get<long>("age");
    if (age.has_value())
        std::cout << "Name: " << ini.get<std::string>("name").value_or("")
                  << "; age: " << age.value()
                  << std::endl;
}


Normalizing an apartment rental database

I have added some comments to your code since, as comments have stated, the relational design is really hard to comment on since we don't know all the business requirements.

There is no need to have an order by with an insert statement since when querying,
the order isn't deterministic unless you specify an ORDER BY. Thus, attempting to insert
data in an order isn't really necessary

insert into bldg_table (bldg)
Select distinct bldg from apartmentmaster order by bldg;

----------------------------------------------------------

insert into id_rec (id, firstName, lastName)
Select id, tenantfirstname, tenantlastname
from apartmentmaster where apt not in (603, 602);

----------------------------------------------------------

In the first two queries you didn't fully qualify your column names as there was no reason to. In this segment, and the following ones, you used a full qualifier of table.column. Since you are selecting from a single table, this is unnecessary. If you do want to fully qualify it, I would use table aliases. See below for the change.

insert into apt_bldg_table(aptNumber, baseRent, bldg)
select aptmstr.apt, aptmstr.baseRent, aptmstr.bldg
from apartmentmaster as aptmstr;

---------------------------------------------------------

Instead of repeating this for Feburary, March, etc as you stated below,
you could create a dates table variable and use CROSS JOIN to eliminate the need to run this five times. See this link for a quick demo. Also, if you want to hard code the date as you have done, and want to use double quotes
you need to SET QUOTED_IDENTIFIER OFF.

insert into tenant_apt_table (id, aptbldg, begdate, baseRent)
select apartmentmaster.id, aptbldg_table.rec_no, "2015-01-01", aptbldg_table.baseRent
from apartmentmaster
join apt_table
on apartmentmaster.apt = aptbldg_table.aptNumber and
apartmentmaster.bldg = aptbldg_table.bldg;

----------------------------------------------------------

insert into rent_rec (tenant_apt_id, paid_date, paid_amt)
select
    tenant_apt_table.rec_no, apartmentmaster.janPaid, apartmentmaster.janRent
from apartmentmaster
join apt_bldg_table
on apartmentmaster.Apt = apt_bldg_table.aptNumber and apartmentmaster.Bldg = apt_bldg_table.bldg
join
    tenant_apt_table
on tenant_apt_table.aptBldg = apt_bldg_table.rec_no

/*and we repeat this query five more times for February, March, etc.*
----------------------------------------------------------


From what I see, you could use two different methods: Ternaries and switches:

From a switch point of view, you could use the following to proceed:

function mytemplate_init() {
    switch(request_path()) {
       case "widgets_json":
           drupal_json_output(_get_widgets());
       break;
       case "people_json":
           drupal_json_output(_get_people());
       break;
    }
}

Or, one can replace that with a ternary to shorten it:

if (request_path() == "widgets_json") {
    drupal_json_output(_get_widgets());
    exit;
}
if (request_path() == "people_json") {
    drupal_json_output(_get_people());
    exit;
}

into:

request_path() == "widgets_json" ? drupal_json_output(_get_widgets()) : (request_path() == "people_json" ? drupal_json_output(_get_people()) : "" )
exit;

The shortside to ternaries is that you sacrifice readability for effectiveness.

However, if you can move past that, ternaries are an effective part of a Programmer's Toolbelt(TM)

Or, as I've since come to understand, we can use objects!

$functions = [
       "widgets_json" => _get_widgets,
       "people_json"  => _get_people
     ];
$functions[request_path()]();

Unfortunately, with such a small amount of code supplied, very little can be reviewed.


Passing a selectlist to the view based on database models from viewmodel is a MVC anti-pattern

I think there are a few things that can be fixed here, but overall I don't think this is automatically an anti-pattern. It could just be executed a little better.

Caveat: I don't practice what I preach nearly as often as I should.

What I tend to do in my own projects, and the standard where I work, is for the view model to expose an IEnumerable<SelectListItem> (actually, when we're lazy, we put this enumerable in the ViewBag like you have but we're trying to get away from that.) Rather than giving the context to your view model, just give the items to the view model when it's constructed and have it generate the SelectListItems from them. AFAIK, that's the controller's job.

public class SomeViewModel
{
    public IEnumerable<SelectListItem> ListItems { get; private set; }

    public SomeViewModel(IEnumerable<SomeModel> items)
    {
        ListItems = items
            .Select(i => new SelectListItem()
                {
                    Text = i.Name,
                    Value = i.Id,
                    Selected = i.IsSelected // or whatever
                })
            .ToList();
    }
}

public class SomeController
{
    public ActionResult Index()
    {
        var viewModel = new SomeViewModel(_context.SomeModels);

        return View(viewModel);
    }
}

Again, I can't promise this is the more "correct" way to do it, but I've done it and seen it done on at least four different projects, and it's worked well for us so far.

P.S. Your ViewModel probably shouldn't inherit from your Model. I've never actually seen that done before, but some cursory Googling shows that it's not really recommended. You should have the exact properties you need in the view copied into your view model (I hear there are tools for his), and use a tool like AutoMapper to copy values back and forth when necessary.


Calculating the change of a vending machine

I see a number of things that may help you improve your code.  Because it makes a lot of things simpler, I'm going to assume that you and your compiler are able to handle C++11.

Post complete code

Here on Code Review, we prefer longer and more complete questions and code which is different from many of the other sister sites.  For that reason, when posting a question here for review, it's often best to include a short driver code showing the context of how your code is intended to be used.  It helps reviewers quickly understand your code and give you a better review.

Use const where practical

The std::vector p gets created and destroyed every time the function is invoked.  That's not very efficient and not at all necessary.  Instead, we can make it static so it's created once and const because it shouldn't change.  We can do that with this single line:

static const std::vector<double> p{ 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01 };

Don't use floating point for money

There is a problem using floating point (that is, float or double types) fto represent money values.  For example, when I tried to use your code to return €0.03 I only got €0.02.  This is a fundamental problem with using double (or any floating-point representation) for money values.  An alternative is to keep a number of cents as an integer value internally.  For more depth about floating point issues, I'd recommend the excellent article "What every computer scientist should know about floating-point arithmetic" by David Goldberg.

Simplify expressions

The code currently has these lines:

if (numeric_change != 0) return false;
return true;

We can simplify this to:

return !numeric_change;

However this is something of a problem with floating point values.  Either change the variable to use and integer type or compare to a real value smaller than your minimum change amount.  For example, you might use 0.005.  Much better would be to use integers.

Think carefully about the problem

If the vending machines contains €0.07 and I put in €50.00 for something that costs €10.00 what I would want to have happen is that I would get my €50.00 back and not the €10.00 item.  What the program seems to actually do, however, is return €0.07.  That is, I would expect that the function would return the value false (which it does), and then have possible_change identical to the paid object.  The specification you quote is not very clear on this issue, but it seems like the right behavior to me.

Putting it all together

Using these suggestions, here is what the routine becomes:

bool i_have_change (colleccio& machine, const colleccio& paid,
                colleccio& possible_change, double numeric_change) {
    static const std::vector<unsigned> p{ 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1 };

    //Add paid to machine
    for (size_t i = 0; i < paid.size(); ++i)
        machine[i] += paid[i];

    unsigned change = numeric_change * 100;
    //I start with change (> 0) and I keep on substracting all $$$
    //as I can (they are always <= change)
    for (size_t i = 0; i < machine.size() and change > 0; ++i) {
        while (p[i] <= change and machine[i] >= 1) {
            change -= p[i];
            ++possible_change[i];
            --machine[i];
        }
    }

    if (change) {
        // can't make change so return money
        for (size_t i = 0; i < paid.size(); ++i) {
            possible_change[i] = paid[i];
        }
    }
    //If I still have change, I have not physical change!
    return !change;
}

Test code

Since the code for colleccio objects was not given, I created my own to test the code.

#include <vector>
#include <initializer_list>
#include <iostream>
#include <numeric>

class colleccio : public std::vector<int>
{
public:
    colleccio(std::initializer_list<int> w) :
        std::vector<int>{w}
    {}
    colleccio() : std::vector<int>(12) {}
    double value() const { return std::inner_product(v.begin(), v.end(), begin(), 0)/100.0; }
    friend std::ostream& operator<<(std::ostream& out, const colleccio& col) {
        out << "{ ";
        for (const auto n : col)
            out << n << ", ";
        return out << "} = " << col.value();
    }
private:
    static const std::vector<unsigned> v;
};

const std::vector<unsigned> colleccio::v{ 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1 };

Now here is a convenience macro and test code in main.

#define SHOW(X) std::cout << # X " = " << (X) << std::endl

int main()
{
    colleccio machine{0, 0, 0, 0,
                      0, 0, 0, 0,
                      0, 0, 0, 7};
    colleccio paid   {1, 0, 0, 0,
                      0, 0, 0, 0,
                      0, 0, 0, 0};
    colleccio change;
    double chg_amount{40.0};

    std::cout << std::boolalpha;
    SHOW(machine);
    SHOW(paid);
    SHOW(change);
    SHOW(chg_amount);
    SHOW(i_have_change(machine, paid, change, chg_amount));
    SHOW(machine);
    SHOW(paid);
    SHOW(change);
    SHOW(chg_amount);
}

Sample output

machine = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, } = 0.07
paid = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } = 50
change = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } = 0
chg_amount = 40
i_have_change(machine, paid, change, chg_amount) = false
machine = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } = 50
paid = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } = 50
change = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } = 50
chg_amount = 40


Fetching the website version number from the database

The try-catch-throw with no error handling is completely pointless. I would just remove it and let the exception bubble up the call stack.
There is no need to call connection.Dispose() since the using () { ... } block will do that automatically
A StringBuilder object is like hitting a thumbtack with a sledge hammer in this case. You can prefix a string literal with the @ symbol to allow newline characters for better readibility:

string sql = @"SELECT TOP 1
               [WebsiteVersion]
               FROM [WebsiteDefaults]";

Or since this is such a simple SQL statement, a one-liner is appropriate as well:

string sql = "SELECT TOP 1 [WebsiteVersion] FROM [WebsiteDefaults]";


How to rewrite recursion in a more ruby way

It looks pretty good to me. Some notes:

I'd avoid return on the last expression
I'd avoid the "-=" (not very functional)
I'd avoid inline returns (write a full-fledged conditional instead)
I have my doubts about this more_friends.users <<, is this a side-effect you are doing behind the caller's back?

As a general note, Ruby is an OOP language, you can strive for functional style (I do whenever possible), but still, use also an OOP structure or you'll end up with weird undiomatic code.


Python script searching for string in textfile and inserting another textfile before match

The problem is a general one in data processing, one that programmers have to think about all the time! When changing a file \$F\$ from \$A\$ to \$B\$ it's tempting to implement it like this:

Read \$A\$ from \$F\$.
Compute \$B\$ from \$A\$.
Delete \$F\$.
Write \$B\$ to \$F\$.

But we need to consider the possibility that something will go wrong. Maybe the user will type control-C on the keyboard and interrupt the program? Maybe there will be a power cut? Maybe the disk will not have enough room for \$B\$? If any of these things happened after step 3 and before step 4, then you would be left in a situation where \$F\$ contains neither \$A\$ nor \$B\$. So you have lost your data and can't get it back.

This is why we try to design systems so that operations are atomic — either they succeed completely or they fail completely. In this case we would use the following procedure:

Read \$A\$ from \$F\$.
Compute \$B\$ from \$A\$.
Write \$B\$ to a temporary location \$G\$.
Replace \$F\$ with \$G\$.

This works because operating systems (usually!) give us an atomic implementation of step 4. In Python we can use os.rename, where you can see that the documentation says:

  If successful, the renaming will be an atomic operation

In this design, if something goes wrong before step 4, the file \$F\$ still contains \$A\$, and so we haven't lost our data, and so we have a chance to fix the problem and try again.

So in this case, I'd write something like this (but this is not tested, so don't use it blindly!):

import os
import shutil
import sys
import tempfile

# usage:
# $ python thisfile.py text.txt searchstring insert.txt
text_file, searchstring, insert_file = sys.argv[1:]

with tempfile.NamedTemporaryFile('w', delete=False) as temp:
    with open(text_file) as f1:
        inserted = False # Have we inserted insert_file yet?
        for f1_line in f1:
            if not inserted and f1_line.startswith(searchstring):
                with open(insert_file) as f2:
                    for f2_line in f2:
                        temp.write(f2_line)
                inserted = True
            temp.write(f1_line)

os.rename(temp.name, text_file)

Here I've used the library function tempfile.NamedTemporaryFile to choose somewhere to put the temporary file.

 Update

So here's another reason why it's a good idea to make operations atomic — you might have made a programming error! The code I wrote above works correctly on my operating system (macOS) but as it says in the os.rename documentation:

  The operation may fail on some Unix flavors if src and dst are on different filesystems

So I'm guessing that you're on some kind of Linux system. On these systems you've got to ensure that the temporary file \$G\$ is on the same filesystem as \$F\$, and the only reliable way to do that is to put it in the same directory as \$F\$:

import os
import shutil
import sys
import tempfile

# usage:
# $ python thisfile.py text.txt searchstring insert.txt
text_file, searchstring, insert_file = sys.argv[1:]

# Directory and name of text_file.
dirname, basename = os.path.split(text_file)

# Create temporary file in same directory as text_file.
with tempfile.NamedTemporaryFile('w', dir=dirname, prefix=basename,
                                 delete=False) as temp:
    with open(text_file) as f1:
        inserted = False # Have we inserted insert_file yet?
        for f1_line in f1:
            if not inserted and f1_line.startswith(searchstring):
                with open(insert_file) as f2:
                    for f2_line in f2:
                        temp.write(f2_line)
                inserted = True
            temp.write(f1_line)

os.rename(temp.name, text_file)

Writing reliable code that works on different platforms is not easy!


Date composition from day, month and year input

As Ekkhard.Homer said, none of you delete lines do anything, because startDate and endDate are strings at that point: They don't have any day, month or year properties.

Anyway, since you need to do the same thing twice, I'd suggest you make a function for it. I've spruced this one up a bit by mapping properties, but that's not really necessary.

$scope.addWeek = function(week) {

  function formatDate(obj) {
    return ['day', 'month', 'year'].map(function (prop) {
      return String(obj[prop]);
    }).join('-');
  }

  week.startDate = formatDate(week.startDate);
  week.endDate = formatDate(week.endDate);
}


I would like to know if there is anything else I can do to check even fewer numbers for an even more efficient algorithm.

The general recommendation is to use a

   sieve for this.  The one that comes to mind is the Sieve of Eratosthenes.

That said, there are some other comments that I can make on the code as it stands.

    int checkIfPrime = 6;       // multiples of 6

Often, your code will read more naturally if you give variables noun names.  This tells what you should do with the variable.  I'd prefer a name like primeCandidate which describes what it is.  Or should be, since 6 isn't actually a number that you want to check.

    int primeCandidate = 7;

It can save calculations if you start with 7 rather than 6.  Rather than saying primeCandidate-1 and primeCandidate+1, you can just say primeCandidate-2 and primeCandidate.  Note that you need the larger number slightly more often.

    bool lessOnePrime = true;
    bool plusOnePrime = true;

Since you don't use these outside the while loop nor across iterations, you should define these inside the loop instead.  Of course, as we'll discuss later, these aren't actually necessary.

    vector<int> primeVector;

This is called Hungarian notation, where you put the type in the name.  This can cause difficulty in changing code later.  For example, what if you wanted to change from std::vector to a type called List?  Should you rename this variable as well?  A better name might be primes which works regardless of type.

    while (countPrimes < 10001)                 // checks until the 10001st prime has been found

You don't have to track a counter manually.  You can just say

    while (primes.size() < 10001)

The type already maintains a count for you.  You might as well use it rather than duplicate it manually.

        for (int i = 0; primeVector[i] <= sqrt(checkIfPrime + 1); i++)      //checks only prime factors up to the square root

You don't need to start at 0 each time.  By starting with 5 and 7 and always incrementing by 6, you ensure that it will never be divisible by 2 or 3.  So you can skip the first two elements in the vector.

        for (int i = 2, n = sqrt(primeCandidate); primes[i] <= n; i++)

You don't need to calculate the square root on each iteration.  You can do it once at the beginning of the loop.

You don't need to comment saying that you are only checking to the square root.  The code says this.  You might want to comment on why it is safe to only check up to the square root.

        {
            if ((checkIfPrime - 1) % primeVector[i] == 0)
            {
                lessOnePrime = false;
            }
            if ((checkIfPrime + 1) % primeVector[i] == 0)
            {
                plusOnePrime = false;
            }

            if (lessOnePrime == false && plusOnePrime == false)
            {
                break;
            }
        }

        if (lessOnePrime)
        {
            primeVector.push_back(checkIfPrime - 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime - 1 << endl;
        }
        if (plusOnePrime)
        {
            primeVector.push_back(checkIfPrime + 1);
            countPrimes++;
            // cout << "#" << primeVector.size() << " prime number:\t" << checkIfPrime + 1 << endl;
        }
        lessOnePrime = true;
        plusOnePrime = true;

This is more complicated than it needs to be.  It would be much simpler to use two function calls instead of this for loop.

        if (isPrime(primeCandidate - 2, primes))
        {
            primes.push_back(primeCandidate - 2);
        }

        if (isPrime(primeCandidate, primes))
        {
            primes.push_back(primeCandidate);
        }

Yes, this repeats the for loop, but it saves you the internal scaffolding.  It also means that if one is a prime and the other isn't, it doesn't keep trying to divide the non-prime one by each potential factor.  That loop can exit early.  You'd have to profile to be sure, but I'd expect this to be faster.

The function would look something like

bool isPrime(const int candidate, const std::vector<int>& primes)
{
    for (int i = 2, n = sqrt(candidate); primes[i] <= n; i++)
    {
        if (candidate % primes[i] == 0)
        {
            return false;
        }
    }

    return true;
}

I haven't tried to compile it though.

Note that it might be more efficient to use an iterator rather than an index variable.  The notation would be more complicated in this case though.

I'll leave writing the actual function to you.  Note that even with the overhead of writing the function, you'll still likely shorten the code a bit.  You do a lot of effort just to make the single for loop work.

        checkIfPrime += 6;
    }

The only change I'd make to this is the variable name.  Although if you wanted to simplify the code in the loop at the cost of making this more complicated, you could change this to

         primeCandidate += increment;
         increment = 6 - increment;
     }

Where increment would be initialized as

     int increment = 2;

And you'd start primeCandidate at 5.  You'd also only do one isPrime check per iteration of the while loop.


When you see that you're basically copy-pasting the code and changing a few values, you can usually encapsulate all the common stuff inside a function. Here:

var registerStuff = function(category, active, prod, select) {
    $(category).click(function(){
        var CategoryID = $(this).data('category');
        $(category).removeClass(active);
        $(this).addClass(active);

        $(prod).each(function(){
            if(($(this).hasClass(CategoryID)) == false){
               $(this).css({'display':'none'});
            };
        });
        $('.'+CategoryID).fadeIn();
    });

    $(select).change(function(){
        var CategoryID = $(this).find('option:selected').data('category');
        $(prod).each(function(){
            if(($(this).hasClass(CategoryID)) == false){
                $(this).css({'display':'none'});
            };
        });
        $('.'+CategoryID).fadeIn();
    });
};

registerStuff(".category-menu  ul li", 'cat-active',  '.prod-cnt',  '.category-menu  select');
registerStuff(".category-menu2 ul li", 'cat-active2', '.prod-cnt2', '.category-menu2 select');

We can now clean up the inside of that function further. For example, some things could be cached, and the second $(category) is uneccessary. The == false is a code smell, rather use a negation. The jQuery hide() method is better than spelling out the css(). Blending out the prods of the wrong category is common code, and can be factored out as well.

var registerStuff = function(category, active, prod, select) {
    var displayOnlyWantedCategory = function($prods, categoryId) {
        $prods.each(function() {
            var $this = $(this);
            if (! $this.hasClass(categoryId)) {
                $this.hide();
            }
        });
        $('.' + categoryId).fadeIn();
    };

    var $category = $(category);
    $category.click(function() {
        var $this = $(this);
        $category.removeClass(active);
        $this.addClass(active);

        displayOnlyWantedCategory($(prod), $this.data('category'));
    });

    $(select).change(function() {
        displayOnlyWantedCategory($(prod), $(this).find('option:selected').data('category'));
    });
};

The next thing to consider is your usage of classes. Your category-menu and category-menu2 are visually and functionally identical, they're only two instances of the same idea. What happens when you want to have fifteen category-menus on the same page? I wouldn't want to see the CSS for that:

 .category-menu,
 .category-menu2,
 .category-menu3,
   ...
 .category-menu14,
 .category-menu15 {
   ...
 }

Your solution does not scale.  Instead, let's think about a product-collection element, which contains a few buttons to select a category, and a few items which can be displayed. We want to limit the effect of selecting a category to the current collection only.

The resulting HTML might look like:

All

Category 1

Category 2

Item 1 [cat 1]

Item 2 [cat 2]

Item 3 [cat 1]

The jQuery initialization must take care to install the handlers only in the elements of the current collection:

$(function() {
    $('.product-collection').each(function() {
        var $collection = $(this);
        var $selectors = $collection.find('.product-collection__selector');
        var $items     = $collection.find('.product-collection__item');

        $selectors.click(function() {
            var $selector = $(this);
            var cat = $selector.data('product-collection__category');

            $selectors.removeClass('product-collection__selector--active');
            $selector.addClass('product-collection__selector--active');

            if (cat) {
                $items.each(function() {
                    var $item = $(this);
                    if ($item.data('product-collection__category') == cat)
                        $item.fadeIn();
                    else
                        $item.hide();
                });
            }
            else {
                $items.fadeIn();
            }
        });
    });
});

See it in action here: http://jsfiddle.net/Qv6QE/3/

My class names may seem excessively verbose, but they avoid namespace conflicts by following the Block-Element-Modifier naming scheme.


Macro to remove rows with data not meeting certain requirements

An interesting learning experience.

Well done for doing the deletion in a backwards loop. Also, well done for declaring all variables.

As you have implied, there is room for some improvement. What I suggest below may not increase speed, but should at least help with maintainability and readability.

Three different ways of accessing a sheet

You are using three different ways of accessing a sheet: index, ActiveSheet and name. Each has their uses and are valid, but mixing methods in a single routine makes it a little more confusing to read.

You haven't identified how the routine is called, and this makes a difference on the applicability of ActiveSheet. How can you guarantee that the active sheet is the one that you want to clean up?

You also reference your FirstRow and LastRow from a fixed sheet, not your ActiveSheet - how can you be sure that they are correct?

Speed up routine

You set your calculation mode and attempted to turn off screen updating. But you don't turn them back again at the end of the routine.

Also consider setting .EnableEvents = False so that you do not fire events every time you delete a row.

Tweaks

Consider using a Select Case to identify a valid row. I have an example in the code below.

Consider creating a Union for each row that you find and want to delete. Then use this union to delete all the rows at once, instead of one at a time.

Put your date value into a variable, rather than accessing the cell each time in the loop. This will save some time and accessing the Excel cells/ranges is relatively expensive.

Perhaps this code?

Sub Remove_FutureRenewals()
    Dim Firstrow As Long
    Dim LastRow As Long
    Dim Lrow As Long
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim SelectedSheet as Worksheet
    Dim BaseDate as String

    Set SelectedSheet = ActiveSheet ' addresses any change to ActiveSheet while routine is running.
    BaseDate = Format(ThisWorkbook.Worksheets("Date Calc").Cells(5, "A").Value, "YYYYMMDD")

    Firstrow = SelectedSheet.UsedRange.Cells(1).Row
    LastRow = SelectedSheet.Cells(ThisWorkbook.Worksheets(2).Rows.Count, "A").End(xlUp).Row

    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    With SelectedSheet
        For Lrow = LastRow To Firstrow Step -1
            Select Case .Cells(Lrow, "E").Value ' always be explicit.
                Case "120", "90", "60" 'etc
                    'If Format(.Cells(Lrow, "E").Offset(0, -1).Value, "YYYYMMDD") <> BaseDate Then
                    If Format(.Cells(Lrow, "D").Value, "YYYYMMDD") <> BaseDate Then
                        .EntireRow.Delete
                    End If ' Better practice to use a full If-The-Endif block rather than a single line
            End Select
        Next Lrow
    End With
    With Application
        .Calculation = CalcMode
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub

This code still has a lot of "magic numbers" in it, but should give you some ideas on where to go next.


Return a sorted ordering of courses such that we can finish all courses

Objects are passed by "copy of a reference".

Notice that the coursesObj after the function call has empty values ( see snippet below )

const isEveryCourseCovered = courses => courses.every(c => !Boolean(c));
const getCourseOrder = courses => {
  const courseSubjects = Object.keys(courses);
  const courseRequirements = Object.values(courses);
  const courseOrder = [];

  do {
    courseSubjects.map((subject, i) => {
      if (subject) {
        courseRequirements[i].map((requirement, idx) => {
          if (courseOrder.includes(requirement)) {
            courseRequirements[i].splice(idx, 1);
          }
        });
        if (!courseRequirements[i].length) {
          courseOrder.push(subject);
          delete courseSubjects[i];
        }
      }
    });
  } while (!isEveryCourseCovered(courseSubjects));

  return courseOrder;
};

const coursesObj = {
  'CSC300': ['CSC100', 'CSC200'],
  'CSC200': ['CSC100'],
  'CSC100': []
};
console.log("result ", getCourseOrder(coursesObj));

console.log("Courses Object : ", coursesObj);

You should create a copy of the passed object, a quick way ( one of many ways ) of doing that is JSON.parse(JSON.stringify(c));
( see snippet below ):

const getCourseOrder = c => {
  // make a copy of the input object
  const courses = JSON.parse(JSON.stringify(c));

const isEveryCourseCovered = courses => courses.every(c => !Boolean(c));
const getCourseOrder = c => {
  // make a copy of the input object
  const courses = JSON.parse(JSON.stringify(c));

  const courseSubjects = Object.keys(courses);
  const courseRequirements = Object.values(courses);
  const courseOrder = [];

  do {
    courseSubjects.map((subject, i) => {
      if (subject) {
        courseRequirements[i].map((requirement, idx) => {
          if (courseOrder.includes(requirement)) {
            courseRequirements[i].splice(idx, 1);
          }
        });
        if (!courseRequirements[i].length) {
          courseOrder.push(subject);
          delete courseSubjects[i];
        }
      }
    });
  } while (!isEveryCourseCovered(courseSubjects));

  return courseOrder;
};

const coursesObj = {
  'CSC300': ['CSC100', 'CSC200'],
  'CSC200': ['CSC100'],
  'CSC100': []
};
console.log("result ", getCourseOrder(coursesObj));

console.log("Courses Object : ", coursesObj);

I didn't test the performance but i would guess it wouldn't be that efficient since it has 5 nested loops (do while, .map, .map, .includes) and .every that's called on every iteration of the while loop and 3 ifs

Reading the requirement :

  Return a sorted ordering of courses

Array.sort() was the first thing to come to my mind, my suggested approach would be simply sorting the Object.keys of the coursesObj based on the length of the value ( array of required courses) corresponding to that key, like so :

const coursesObj = {
  'CSC300': ['CSC100', 'CSC200'],
  'CSC400': ['CSC100', 'CSC200', 'CSC300'],
  'CSC200': ['CSC100'],
  'CSC100': []
};

const result = Object.keys(coursesObj).sort((a, b) =>
  coursesObj[a].length - coursesObj[b].length
);

console.log(result)

PS : i added the CSC400 key in the middle just for the demo.

EDIT :

If you have an Object like :

const coursesObj =
    {
      c1: ['c2', 'c3', 'c4'],
      c5: ['c1'],
      c4: [],
      c2: [],
      c3: ['c4']
    }

you can transform it to add the prerequisites of the courses in its prerequisites
 array so it becomes :

const detailed =
   {
     c1: [ 'c2', 'c3', 'c4' ],
     c5: [ 'c1', 'c2', 'c3', 'c4' ], // c5 now has c1 and the prerequisites of c1
     c4: [],
     c2: [],
     c3: [ 'c4' ]
   }

then apply the same sort function above :

const coursesObj = { c1: ["c2", "c3", "c4"], c5: ["c1"], c4: [], c2: [], c3: ["c4"] };

const detailedObj = Object.entries(coursesObj).reduce((accumulator, [courseId, requirements]) => {
  accumulator[courseId] = requirements.slice(0); // original courses required.

  requirements.forEach(course => {
    accumulator[courseId].push(...coursesObj[course]); // add the required courses for each required course .
  });

  // remove the duplicates
  accumulator[courseId] = [...new Set(accumulator[courseId])];

  return accumulator;
}, {});

// sort by the number of prerequisites
const result = Object.keys(detailedObj).sort((a, b) =>
  detailedObj[a].length - detailedObj[b].length
);

console.log(result);


Looks good. Few notes:

There is no reason to #include <stdlib.h> in both linkedlist.h and linkedlist.c. Pick one (I recommend linkedlist.c).
Allocation of a struct llnode instance definitely belongs to ll_node_init, and its signature should be

static struct ll_node * ll_node_init(char * data);

Notice static: there is no reason to expose struct ll_node to the client.
Maintain your invariants. It is clear that if (ll_head != NULL) then ll_tail != NULL, and vice versa. For example, push_head should have

    if (ll->head != NULL) {
        assert(ll->tail != NULL);
        ll->head->prev = node;
    } else {
        assert(ll->tail == NULL);
        ll->tail = node;
    }

The code doesn't really care what kind of data it queues. You may consider making the structure more generic with void * data.


Looks okay to me,

I would not expose function names mentioning node, but rather familyMember or member.
You expose only name through addNode, but you have name, mother, father, children in the constructor of Node.
Your var statement is not well indented, making the code harder to understand
I am curious as to treeList, what use case do you have in mind for that?


I was looking into the MemoryStream and I found this

  Except for a MemoryStream constructed with a byte[] parameter, write operations at the end of a MemoryStream expand the MemoryStream.

on MemoryStream.Write Method

I would look around a little bit on the MSDN sites that I am going to list and see if you want to change around the code that you have so that you can maybe use the Byte[] Parameter.

MemoryStream Class

although it looks like most of those Constructors create non-resizable instances, whereas the a Memory Stream Created with out any Parameters ...

  Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero.

so to me it looks like the BlockCopy or 2 streams methods are the only way to go.


Bug

The bug you mentioned about not handled files larger than 4K is here:

        s += s.substr(max(0, i - window_size) + pos.to_ulong(), length);

Here, i is the amount of compressed file you have read so far.  But you want to use the size of the decompressed file instead.  So that line should be changed to:

        s += s.substr(max(0, (int) s.size() - window_size) +
                pos.to_ulong(), length);

I tested this change against a large file and it fixed the problem.

Substrings are costly

In the main loop of lz_compress(), you set call s.substr() for every byte of the input file, and the substring can be as large as your window size (4KB).  Each time you do that, you are making a copy of a portion of the original string.  So for a 1 MB file, you end up copying 4 GB of data during the course of your compression loop.  You could do a lot better if you just passed the original string into your longest_prefix() function along with the start index and length of the substring you would have created.  That way you wouldn't need to make unneeded copies of your input string.

Simplification of bit packing/unpacking

It looks like you did something really complicated here with bitsets in the compress function:

        bitset<4> length(match.second);
        bitset<12> pos(match.first);
        bitset<16> concat(length.to_string() + pos.to_string()); // change a 4-bit and a 12-bit number into two 8-bits numbers
        bitset<8> bit1(concat.to_string().substr(0,8));
        bitset<8> bit2(concat.to_string().substr(8,8));

        i += match.second;

This could be simplified to:

        int pos    = match.first;
        int length = match.second;
        compressed += (char) ((length << 4) | (pos >> 8));
        compressed += (char) (pos & 0xff);

        i += length;

Similarly, the decompress function:

for(int i = 0; i < compressed.size(); i += 2)
{
    bitset<8> bit1(compressed[i]);
    bitset<8> bit2(compressed[i+1]);
    bitset<16> concat(bit1.to_string() + bit2.to_string());
    bitset<4> length_b(concat.to_string().substr(0,4));
    int length = length_b.to_ulong();

    if(length == 0)
    {
        bitset<8> c(concat.to_string().substr(8, 8));
        s += (char)c.to_ulong();
    }
    else
    {
        bitset<12> pos(concat.to_string().substr(4, 12));

        s += s.substr(max(0, (int) s.size() - window_size) +
                pos.to_ulong(), length);
    }
 }

could be simplified to:

for(int i = 0; i < compressed.size(); i += 2)
{
    unsigned char byte1 = compressed[i];
    unsigned char byte2 = compressed[i+1];
    int length = (byte1 >> 4);

    if(length == 0)
    {
        s += byte2;
    }
    else
    {
        int pos = ((byte1 & 0xf) << 8) | byte2;

        s += s.substr(max(0, (int) s.size() - window_size) + pos, length);
    }

}

Speed of compression

One of the slowest parts of your program is the longest_prefix() function.  This function searches a 4KB window for the longest match to a 16 byte pattern.  Your brute force search takes \$O(n*m)\$ time, where \$n\$ = 4KB and \$m\$ = 16.  To achieve faster compression speeds, you will need to use a faster search algorithm.  Some alternatives are: Knuth-Morris-Pratt searching or hash tables.  I found this webpage that discusses some of the various alternatives with sample implementations, if you are interested in improving your search algorithm.


You could allow to initialize the stack locally.
Just by separating the bigger part of stack_create to separate function.

void stack_init(STACK* stack, char* mem, size_t size)
{
    stack->mem = mem;
    stack->size = size;
    stack->top = -1;
}

char stack_mem[STACK_SIZE];
STACK stack;
stack_init(&stack, stack_mem, STACK_SIZE);

As for error handling, stack usualy does not handle it. You should instead offer the "is empty?" and "is full?" functions. Consumers of the stack are then responsible for making sure stack is not empty before they peek or pop, and that it is not full before they push. Check for emptiness is often integral part of algorithms using the stack anyway. Check for fullness not so much, it Is mostly limitation of a fixed size stack. But the consumer must check it nevertheless or they must be sure that bigger stack is never needed.

In stack_create you should check if malloc returns null then dont assign to properties and return null as well. Consumers are again responsible for checking this situation.

One last point, the stack_create could be complemented with stack_destroy.


Upon coming face to face with the mighty cross-origin request block, and needing to get a JSON file from an external source, I decided to use the Yahoo Query Language in order to achieve this.

Using YQL just to get a JSON and parse it sounds like a dirty workaround.
I don't know the right answer about that part.
You might be better off asking on stackoverflow.com instead,
to overcome your original problem without resorting to such workaround.

About the code posted, these are only minor nitpicks:

Where does key come from? Perhaps it should be a method parameter
User lowercase for variable names (site (or url) instead of Site)
You look up the 'Steam64ID' element twice. It would be better to do it once and store in a variable to reuse, for example:

var steam64ID = document.getElementById("Steam64ID").value += "" + app.id64;
getFriendList(steam64ID);

The function is called getID64 which sounds like a getter, so it should return something, but it actually doesn't.


Quicksort implementation with pivotal calculated as middle element

What do you think about my implementation?

To tell you the truth, I don't think much of your implementation.  Instead of in-place swaps you're creating a bunch of temporary lists and combining them after.  It probably more closely resembles a merge sort than a quick sort.

Creating all those lists and merging them together requires many more iterations than the usual quick sort.

Altogether, it seems to me, that both the time and space complexity is worse than the usual quick sort.


I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.

rexes = ('[A-Z]', '[a-z]', '[0-9]')
# ...
if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
    print('Strong password')


Reading a config file outside of the publicly visible root directory

I am assuming that you have a directory structure something like this, which can be common in shared hosting environments:

/path/to/your/directory => your customer directory on the host
/path/to/your/directory/public => the web server document root

Or, if you had full control over your environment it might look like:

/some/nonpublic/directory => non-public directory (possibly in include path)
/var/www => web server document root

So ideally, your application should be able to seamlessly handle both without custom code that changes based on where you deploy the application.

Typically, this is done by configuring constants for file paths in a config file, not by relying on values derived from $_SERVER['DOCUMENT_ROOT'] as this has absolutely no connection to where on a server you may have the ability to place your non-public application code. You may be able to count on this behavior for some specific shared host environment, but this gives you no guarantee that this same behavior would exist in another environment.

So an approach of defining path constants may look like:

define('WEB_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('INCLUDE_DIR', {path to one of non-public directories shown above});
define('CONFIG_DIR', INCLUDE_DIR . '/config');

Then if you wanted to check if your config is set for JCDB, it might look more like:

if(!isset($GLOBALS['config'])){
    $GLOBALS['config'] = parse_ini_file(CONFIG_DIR . '/JCDBconfig.ini');
}

This reduces your problem to only having to figure out how to populate the value into INCLUDE_DIR, not trying to determine this directory when you are at the point of trying to conditionally load configurations for various components in the application.

This could be hard-coded (not ideal) which is quick and dirty, but you might consider an approach that allows you to conditionally determine the include path.

For example, if you control the environment, you could modify your Apache config to inject an environmental variable holding the include path or, if missing, perhaps looks into a file that you specifically deploy onto your shared host to determine how to get to that include path for the host you are on.

So perhaps something like this near the beginning of your application bootstrap process.

define('WEB_ROOT', $_SERVER['DOCUMENT_ROOT']);
if(!empty($_SERVER['APP_INCLUDE_PATH']) {
    define('INCLUDE_DIR', $_SERVER['APP_INCLUDE_PATH']);
} else {
    define('INCLUDE_DIR', require WEB_ROOT . '/appIncludeConfig.php');
}

Where in Apache you have

 SetEnv APP_INCLUDE_PATH /some/nonpublic/directory

Or for shared host,  appIncludeConfig.php has a single line of code like:

<?php
return '/path/to/your/directory';

I question why you would want to put a critical dependency like a config setting into a mutable variable in global scope vs. something immutable (like a constant).  So perhaps something like this is more appropriate:

if(!defined('JCDB_CONFIG')){
    define('JCDB_CONFIG', parse_ini_file(CONFIG_DIR . '/JCDBconfig.ini'));
}

Note I also changed the naming of the config setting to be something less generic than just config such that it is clear that this value is specific only to this particular configuration value.


This is roughly what BDD should look like.  You're definitely on the right track in that you have a specific set of postconditions and expected results for every "public" method.  However, the tests for these postconditions are incomplete in some respects that I think will probably come up as edge conditions and/or browser quirks (assuming your system is going to run in a browser).  In addition, you're testing behaviors in this suite that are shared between your subclasses - even if they don't actually share a prototype, they do have a common interface and common expectations.

For incompleteness, I'm referring to 'should return false when value provided is null or undefined' when the corresponding test only tests null.  This should be two tests, one for null and another for undefined.  In addition, you should define and test the function's behavior for other values that are commonly mistaken for null and undefined, like 0, false, and ''.  The empty string is of particular importance because it's unclear from your tests whether an empty string is acceptable as long as it's specified - the source of your data might determine whether that's applicable.  I would go with two or three tests per native type: one that is acceptable, one that is not (if both are applicable), and one that is falsy (if the falsy value for the type is not already covered).  If you really want to go all out, define behavior for the parameters '0', 'false', 'undefined', and NaN.

This sounds like a pain to do - especially when you see that you need to define said behavior for all of the other functions whose preconditions are the same.  The root of the problem here is that your preconditions are not very DRY.  Each function has two test cases: null and 'asd' as inputs to test.  Since null and 'asd' are not really the only two inputs you can expect to get, your tests shouldn't be coupled to those two inputs.  Further, when you go to write your tests for your other rule subclasses, you will be unable to re-use your isErroneous and getError tests because they have specifically named null as erroneous and 'asd' as acceptable.

I'm not a mocha expert, so I don't know how helpful or cooperative it will be, but you can refactor your suites to test states rather than classes, and it will be far DRYer.  From what I can tell, the rule subclasses all have the following features:

A (theoretically unbounded) set of inputs to the test method that will:

return false
leave the object in an erroneous state

A (theoretically unbounded) set of inputs to the test method that will:

return true
leave the object in a validated state

An initial state before test is ever called, whose behavior remains unspecified.

Each of your subclasses has a different set of erroneous and valid inputs, but you can easily define the behavior of those three states independently:

A rule object in an erroneous state should:

return true from isErroneous()
return non-null from getError()
(become | not become) valid when a valid input is provided to test

A rule object in a validated state should:

return false from isErroneous()
return null from getError()
(become | not become) erroneous when an invalid input is provided to test

A rule object in its initial state should:

probably have defined behavior for getError and isErroneous, too.
become valid when a valid input is provided to test
become erroneous when an invalid input is provided to test

Now, your tests for all of your classes are reduced to the task of generating the input test cases and expected states they will generate.  For the RequiredRule, that could be easily expressed in two arrays; you might want something different for your more complicated rules, since the criteria are presumably individualized per object for those subclasses.  I might go with something like a generator.

The concept of a class is helpful for BDD when you have specific class invariants, but with javascript you are by no means limited to a one-to-one correspondence between a class (constructor/prototype) and its defined behaviors.  Like anything else in software design, you can tell your unit test is wrong as soon as you type the same thing 2 or 3 times.  Usually, you can fix the repetition by making the object of your suite (parameter to describe) something more applicable than the name of the constructor.


I think this depends a lot on your motivation for separating these into two methods.

One simple option I would consider first is to just have 1 version of each of these functions to avoid the duplication in the first place.
The caller can just ignore the max_dist value if they don't need it.

If performance is an issue and max_distcalculation could be a bottleneck, you could add a Boolean argument to the single function to indicate if max_dist should be calculated or not.

If the logic for max_dist is complex enough to hurt the readability of the basic search, I think you may be better off going with the duplication instead of doing something more complex.  It could be done, but not in a way I would consider reasonable in most cases.


Parallel computation to be merged, depending on single call

Option 1 defeats the whole purpose of Promises. You are nesting the callbacks. Option 2 and 3 are not different, just how they're formatted. That's up to personal preferences.

Now going with the fact that get_phase_count, get_phase_info and get_phase_votes are wrapper functions to API calls, let's not touch those. That leaves us with join_phase_promises. join_phase_promises is unnecessary as it's just a wrapper for Promise.all which you can simply use directly.

Now over to code styles, JS follows camelCase convention. This makes your function names, which are underscore-cased, look like outcasts. Suggesting you use camelCase instead.

If you happen to use Node.js 4+ (current version is 5.7), the native Promise is already available. No need to use Bluebird for that. You can also start using arrow functions to make your callbacks a bit more compact. Lastly, JS has a bunch of array operations and recently included destructuring. There's little need to use underscore.

If I were to write your function, it would go like

getPhaseCount().then(amount => Promise.all([
  getPhaseInfo(amount),
  getPhaseVotes(amount)
])).then(args => {
  let merged = args.reduce((p,c) => c.map((a, i) => ({...a, ...p[i]}) ), []);
  console.log(merged);
});

The above logic took me a while to figure out using only native operations, but what it does is to allow us to see the previous and current values using reduce. This way, on each item, map essentially creates a new array containing a merged version of the previous and current.


Have you tried:

    public IEnumerable<WebQuery> GetQueries(Request request)
    {
        List<string> keys = request.Reports.Select(i => i.UserKey).ToList();
        var queries = new List<WebQuery>();
        queries.AddRange((from query in _context.WebQueries
            join qg in _context.WebQueryGroups on query.QueryKey equals qg.QueryKey
            join wp in _context.WebPermissions on qg.QueryGroupNameKey equals wp.TaskGroupNameKey
            join wugn in _context.WebUserGroupNames on wp.UserGroupNameKey equals wugn.UserGroupNameKey
            join wug in _context.WebUserGroups on wugn.UserGroupNameKey equals wug.UserGroupNameKey
            join wt in _context.WebTasks on query.QueryCategory equals wt.TaskReportCategory
            where wt.TaskKey == request.Key
                && wp.ResourceKey == 4
                && wt.TaskKey == request.Key
                && keys.Contains(wug.UserKey)
            select query).OrderBy(x => x.QueryTitle));
        return queries;
    }

?


Has the following query been made in the optimum way?

CREATE TABLE Manufacturers ( id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB

CREATE TABLE parts ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(30) NOT NULL,
man_id int(11) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB

your structure looks OK for performance, because you have index the common field where you make the join on.  How ever, shouldn't you use PK and FK instead?.  If you need to know a bigger description use the explain command to be sure that the index are correctly used.