Reinventing the basic calculator functions

Let's say you have this situation:

if ...:
    ...
    return ...
else:
    return ...

What if the if condition is True?  Some statements will be executed, and then the function will return.  In other words, if the condition is True, execution never leaves the if block.  Therefore, you really don't need the else.  Just put the return directly under the if:

if ...:
    ...
    return ...
return ...

It is generally a bad idea to use the pattern type(...) == ....  Usually, we use isinstance(..., ...).  That way, subclasses are allowed.  Of course, you might keep it if you don't want subclasses to be allowed, but I don't see a reason to restrict the user.  I'm assuming you want only integers because only integers can be passed to range, but subclasses of integers can indeed also be passed.  For example, booleans are integers.  range(False, True) is perfectly valid.  Also, True + False + False is valid, so it won't mess up your arithmetic.  That makes your is_positive_int function look like this:

def is_positive_int(x):
    if isinstance(x, int) and x >= 0:
        return True
    return False

But what do you see?  If a condition is True, we return True.  If it is False, we return False.  In other words, we are really just returning the condition, so why not do it like this:

def is_positive_int(x):
    return isinstance(x, int) and x >= 0

I see a very similar pattern in all of your functions:

if is_positive_int(x) and is_positive_int(y):
    ...
else:
    return False

First of all, we can remember what I mentioned earlier about not leaving the if block unless the condition is False.  Therefore, I would actually switch the if and else:

if not is_positive_int(x) or not is_positive_int(y):
    return False
...

We remove a level of nesting that way.  The problem is that we use the same code in a bunch of different functions, so we can make a decorator.  A decorator is a function which, when given another function (a) to wrap, returns a wrapper function (b) for a.  b overrides a and does its special thing, but it usually calls a later.  This is my idea:

def guarantee_positive(function):
    # Each function takes two arguments
    def wrapper(x, y):
        if is_positive_int(x) and is_positive_int(y):
            # Deal with it normally
            return function(x, y)
        return False
    # Now wrapper(x, y) will be called instead of function(x, y)
    return wrapper

To use it, add @guarantee_positive before each function definition.  For example:

@guarantee_positive
def divide(x, y):
    floor = 0
    remainder = 0
    for i in range(x):
        remainder += 1
        if remainder == y:
            floor += 1
            remainder = 0
    return {'floor': floor, 'modulus': remainder}

That makes for a much cleaner function.  Of course, subtract has an extra condition, but I'll get to that later.

With all that about function decorators, why do you need them both to be positive?  I can see why you might want y to be positive: because range doesn't work the same with negative numbers, but you aren't using i most of the time, so just use the absolute value of y.  I'll give an example:

def multiply(x, y):
    m = 0
    function = add if y > 0 else subtract
    for _ in range(abs(y)):
        m = function(m, x)
    return m

It doesn't require a decorator, and it is capable of more.  You can now use it with any combination of negative and positive:

-3,  3 -> -9
-3, -3 ->  9
 3, -3 -> -9
 3,  3 ->  9

Your add function would be like this:

def add(x, y):
    # Add 1 if y is positive; subtract 1 if it is negative
    y_add = (1 if y >= 0 else -1)
    for _ in range(abs(y)):
        x += y_add
    return x

Again, it's shorter than the original, and it does more.

There are some functions where it isn't quite that easy.  For example, power() would be difficult to implement a negative y (x doesn't need to be positive even with the current implementation), but most of the others don't need the decorator.  I won't tell you all of them, but I have given examples of the more common hangups.

Back to the decorator, I think it is better to raise an exception when something is wrong than to return False.  After all, they are called exceptions for a reason.  Normally, the function does one thing, but there are exceptions (or there should be).

I see a lot of for i in range(y) when i isn't used.  The common way of signifying that i is just a place holder is using _ as the variable name.

It looks like you cheated with divide() :)  You don't actually have division, you have divmod.  I think a name similar to that would be more appropriate.  another thing is that you return a dictionary.  I prefer something closer to how the built-in function does it:

return floor, remainder

That way, you can do:

floor, remainder = divide(...)

Instead of the equivalent:

result = divide(...)
floor, remainder = result['float'], result['modulus']

Either one should have a doc string that explains what the return value is.  If I called divide(...) when it had a doc string of just x / y, I would assume that I would get x / y, not a dictionary with the floored result and the remainder.  Your floor and modulus functions would then be:

def floor(x, y):
    """a // b"""
    return divide(x, y)[0]

def modulus(x, y):
    """x % y"""
    return divide(x, y)[1]

Except that divide will hopefully have a more descriptive name.

I did notice that floor is inside of divide(), but I am assuming that is just a typo.

You seem to be following PEP 8 fairly well, but I noticed that you don't have any whitespace between the key-value pairs in your dictionary.  PEP 8 recommends that you put a space between the colon and the value.  I don't see it in the PEP, but I think you should put a space between a comma and the following object.  For example:

def divide(x, y):

not

def divide(x,y):

Without the space, it feels smooshed, like you're golfing (code golfing, not with a golf club).


I recommend looping through slice with range syntax.

for _, v := range(input) {
    val, err := strconv.Atoi(v)

    if err != nil {
        panic(err)
    }

    numbers = append(numbers, val)
}

You can replace case "" with default.

Besides that, it looks OK to me.


Given the constraints, the maximum sum, N * max(A), would be 2000000000, which fits within a Java int.  You don't need a long.

Your code is a straightforward implementation of the challenge; there's nothing to micro-optimize.  Your only hope is to use a different approach.

Assuming that the test is heavy on "S" queries, you would be better off keeping an array of cumulative sums.  Then you could answer an "S" query in constant time.

What to do with "G" and "T" operations, though?  The elegant approach would be to update the entire cumulative sums array for each "G" or "T".  However, since N is likely to be larger than Q, you might get better performance keeping the "G" and "T" operations as a list of exceptions instead.


I ran your code, and played a bit:

$ python2 test.py
X, which row?1
X, which place?1
['X', '/', '/']
['/', '/', '/']
['/', '/', '/']
O, which row?2
O, which place?2
['X', '/', '/']
['/', 'O', '/']
['/', '/', '/']
X, which row?3
X, which place?1
['X', '/', '/']
['/', 'O', '/']
['X', '/', '/']
O, which row?2
O, which place?1
['X', '/', '/']
['O', 'O', '/']
['X', '/', '/']
X, which row?2
X, which place?4
Traceback (most recent call last):
  File "test.py", line 95, in <module>
    game()
  File "test.py", line 84, in game
    xsturn()
  File "test.py", line 15, in xsturn
    if row2[place] == '/':
IndexError: list index out of range

First, there is no presentation of the board when play starts. So you're relying on the X player to know what's going on.

Second, using two lines to ask for the move raises the issue of making a mistake and needing to go back. I'd suggest you either add a "go back" feature of some kind, or convert to using a single line of input for the entire move- some kind of X, Y input, or numbering the cells from 1-9.

Third, you don't do any range checking on the input, as is obvious from the end of my game. Given that you don't prompt the user with a definition of what input is valid (1-3), that's a double error. You need to tell the user what's valid, and double-check the input to make sure that it is, in fact, valid.

Fourth, you need to improve the presentation of the board. You should display it prior to each move, even the first move, so the players know what's what. You should also label the board, so that input is obvious. If you ask what row, column for a move, then label the rows/columns on the board display. And please change the '/' into something more sensible - use a space (' ') or a dot ('.') or something that looks like an empty cell.

That said, let's look at some code:

def xsturn():
    row = input('X, which row?')
    place = input('X, which place?') - 1
    if row == 1:
        if row1[place] == '/':
            row1[place] = 'X'
        else:
            print 'Move not possible!'
            xsturn()
    elif row == 2:
        if row2[place] == '/':
            row2[place] = 'X'
        else:
            print 'Move not possible!'
            xsturn()
    elif row == 3:
        if row3[place] == '/':
            row3[place] = 'X'
        else:
            print 'Move not possible!'
            xsturn()

def osturn():
    row = input('O, which row?')
    place = input('O, which place?') - 1
    if row == 1:
        if row1[place] == '/':
            row1[place] = 'O'
        else:
            print 'Move not possible!'
            osturn()
    elif row == 2:
        if row2[place] == '/':
            row2[place] = 'O'
        else:
            print 'Move not possible!'
            osturn()
    elif row == 3:
        if row3[place] == '/':
            row3[place] = 'O'
        else:
            print 'Move not possible!'
            osturn()

These two functions are all but identical. Replace them with a single function taking a character parameter:

def take_turn(sigil):
    row = input(sigil + ', which row?')
    place = input(sigil + ', which place?') - 1
    if row == 1:
        if row1[place] == '/':
            row1[place] = sigil
        else:
            print 'Move not possible!'
            take_turn(sigil)
    # etc.

You can then modify the game function to pass in the player sigil:

def game():
    while win() == 0:
        take_turn('X')
        printingrows()
        if win() == 1:
            print 'X won the game!'
            break
        else:
            take_turn('O')
            printingrows()
            if win() == 1:
                print'O won the game!'
                break

Next, rename printingrows to something more accurate: show_board or some such. Try to always write your code using the vocabulary of the problem domain. In this case, the problem domain is a board game.

Finally, there are a bunch of opportunities for you to tighten things up. For example, checking for a win in the turn function instead of separately, or using a list-of-lists instead of three separate row lists. If you can make the changes above and update your code, then we can get into those changes.


Using LIS from Wikipedia.

def max_russian_doll(seq):
    if not seq: return 0
    seq.sort()
    M = [0] * (len(seq) + 1)
    L = 1
    for i in xrange(len(seq)):
        lo = 1
        hi = L
        while lo <= hi:
            mid = (hi - lo)/2 + lo
            if seq[M[mid]][1] < seq[i][1] and seq[M[mid]][0] < seq[i][0]:
                lo = mid + 1
            else:
                hi = mid - 1
        newL = lo
        if newL > L:
            M[newL] = i
            L = newL
    return L

print max_russian_doll([]) == 0
print max_russian_doll([(1,1)]) == 1
print max_russian_doll([(1,1), (1,1), (1,1)]) == 1
print max_russian_doll([(4,5), (4,6), (6,7), (2,3), (1,1)]) == 4 # e.g (1,1) -> (2,3) -> (4,5) -> (6,7)
print max_russian_doll([(4,5), (4,6), (6,7), (2,3), (1,1), (1,1)]) == 4
print max_russian_doll([(5,4), (6,4), (6,7), (2,3)]) == 3


Get resulting rectangle from two overlapping rectangles

float minX;
float maxX;
float minZ;
float maxZ;

The declarations can be inlined so that it is clearer when they are being set. However, in geometry and other applications it may be preferable to declare them like this.

if (a.max.x < bounds.max.x)
            maxX = a.max.x;
        else
            maxX = bounds.max.x;

These conditions can be replaced with calls to Math.max and Math.min.

The variable names such as minX and maxX seem to be reversed; minX seems to be referring to maxX and vice-versa. I am not very familiar with geometry so I don't know if my suggestion is correct to swap the names.

After applying these suggestions, the method becomes the following:

  public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
    {
        result = new Bounds();
        //they don't overlap
        if (!a.Intersects(bounds)) return false;

        float minX = Math.Max(a.min.x, bounds.min.x);
        float maxX = Math.Min(a.max.x, bounds.max.x);

        float minZ = Math.Max(a.min.z, bounds.min.z);
        float maxZ = Math.Min(a.max.z, bounds.max.z);

        // using XZ plane for debug
        Vector3 min = new Vector3(minX, 0, minZ);
        Vector3 max = new Vector3(maxX, 0, maxZ);
        result.SetMinMax(min, max);
        return true;
    }

Edit: to respond to the comment (minimizing if statements), it could be expressed as:

  public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
    {
        result = new Bounds();

        float minX = Math.Max(a.min.x, bounds.min.x);
        float maxX = Math.Min(a.max.x, bounds.max.x);

        float minZ = Math.Max(a.min.z, bounds.min.z);
        float maxZ = Math.Min(a.max.z, bounds.max.z);

        // using XZ plane for debug
        Vector3 min = new Vector3(minX, 0, minZ);
        Vector3 max = new Vector3(maxX, 0, maxZ);
        result.SetMinMax(min, max);
        return !a.Intersects(bounds);
    }

This would be slightly less efficient; I don't know if this is valid as if the Vector3 class will accept input which did not pass .Intersects.


Parsing XML and prepend HTML every 3 elements

Perhaps using a template system can help you, check http://handlebarsjs.com/ you can integrate with jquery and reuse partial html code as a templates


You should never generate dynamic SQL by concatenating incoming values into an SQL string that is executed later. This type of code leads to SQL injection vulnerability, and by using your service as it is now it's very easy to get access to any user account without knowing its password.

If you plan to develop your service further take your time to learn one of the ORM frameworks (Entity Framework, NHibernate, or maybe one of the NoSQLs like MongoDB or RavenDB) and get rid of low-level DB management code from your service. Alternatively (if you prefer inventing a wheel :)) move DB-related code to separated class and name it "DB repository" so that your service doesn't have too many responsibilities (currently it has business logic responsibilities combined with DB access management).

About exception handling - here is a good article that describes what you should and should not do. Basically you should only catch specific exceptions, and only if you know how to recover from that exception in a meaningful way, that doesn't leave your application in an inconsistent state. In case when WCF service has no way to return a meaningful response (e.g. when response is based on DB data and database is not available) you should pass exception to the client.

And finally, store your connection strings in the configuration files rather than hardcoded.


IndexOrDefault that functions like FirstOrDefault

public static TListType IndexOrDefault<TListType>(this List<TListType> list, int index)

You're extending a concrete type, and the type parameter's name is misleading - it's not the type of the list, it's the type of its items. I'd just call it T. IList<T> calls it T, so I don't see a problem with T ;)

You should be extending an interface, in this case probably an IEnumerable<T>, like LINQ extension methods do.

var count = list.Count();

You're iterating the List<T> through its IEnumerable<T> interface (doesn't apply to List<T> because a List<T> is also an ICollection<T> see @svick's comment below, but in other cases that would be \$O(n)\$ already), and you haven't tried to find anything yet! A List<T> doesn't need to be iterated to retrieve its count, just use the Count property getter, like this:

var count = list.Count;

Actually this whole block:

    var count = list.Count();
    if (index > count -1)
        return default(T);
    if (index < 0)
        return default(T);
    return list[index];

Could be simplified to:

if (index > list.Count - 1 || index < 0)
{
    return default(T)
}

return list[index];

But that's still extending a List<T>. You're going to want to extend IEnumerable<T> instead... but the method you're implementing already exists in System.Linq:

public static T IndexOrDefault<T>(this IEnumerable<T> source, int index)
{
    return source.ElementAtOrDefault(index);
}

You're duplicating the functionality of the IEnumerable<T>.ElementAtOrDefault extension method.


Do what you say

 * return 0 if operation is succesfull
 *        1 if malloc failed */

So if a malloc fails, you are supposed to return 1.  But when you do the actual check:

    ElementNode *new_node = make_node(pos, data);
    /* Malloc fail check*/
    if (new_node == NULL)
    {
      return 0;
    }

You return 0.

You return 1 on success -- the exact opposite of the comment.  You should either update the comment to match the code or change the code to match the comment.  Or remove the comment--if you have to read the code anyway, why bother?

Keep it simple

      ElementNode *next     = current->next;
      current->next         = new_node;
      new_node->next        = next;

Why do you need next?  Consider

      new_node->next = current->next;
      current->next = new_node;

You save an assignment and a variable declaration by just changing the order in which two lines happen.


It's a little verbose.

I would write

try {
    using(var connection = new OleDbConnection(...)) {
        connection.Open();
        return true;
    }
} catch {
    return false;
}

You should also use OleDbConnectionStringBuilder to properly escape the variables in the connection string.


Mocking dependencies when unit testing AngularJS services with QUnit

e.g. I'm unsure when it's common to prefix variables with a $

A quick Google and I found a StackOverflow thread about this,

The accepted answer had this to say:

  It's a common reference to a jQuery wrapped object. It makes reading the code easier to know which variables are jQuery wrapped.

I would say that you don't need to use $ prefix in your code at all, at least what you have posted.

If you were using $scope that would be different as noted by this answer

  $scope variables bind to the view where as var does not and is local to the function it was declared in!

also noted in the comments

  The $ prefix is used as a naming convention identifying native AngularJS services

▼▼▼

  Do not use $ to prepend your own object properties and service identifiers. Consider this style of naming reserved by AngularJS and jQuery.

From Google's AngularJS Style Guide


Use list comprehensions instead of creating empty array and appending to it in a for loop. It's both faster and more readable.

@staticmethod
def get_comments(soup):
    return [
        Comment(*DatabazeKnih.parse_comment(comment)
        for comment in soup.find_all('div', {'class': 'komholdu'})
    ]

But If would argue that you don't need classes here at all.

from bs4 import BeautifulSoup
from collections import namedtuple
import requests as r

Book = namedtuple('Book', 'title rating text authors year comments')
Comment = namedtuple('Comment', 'user text date')
PAGE_URL = 'http://www.databazeknih.cz/'

def search(name):
    page = r.get(PAGE_URL + 'search', params=dict(q=name, stranka='search')).text
    link = BeautifulSoup(page, 'html.parser').find(type='book').attrs['href']
    book_page = r.get(PAGE_URL + link, params=dict(show='alldesc')).text
    return book_info(book_page)

def book_info(book_page):
    soup = BeautifulSoup(book_page, 'html.parser')
    title = soup.find(itemprop='name').string
    rating = soup.findAll('a', {'class': 'bpoints'})[0].string
    text = soup.find(itemprop='description').string
    authors = [elem.string for elem in soup.find(itemprop='author').find_all('a')]
    year = soup.find(itemprop='datePublished').string
    comments = [
        Comment(*parse_comment(elem))
        for elem in soup.find_all('div', {'class': 'komholdu'})
    ]
    return Book(title, rating, text, authors, year, comments)

def parse_comment(comment):
    user = comment.find('a').string
    text = comment.find('p', {'class': 'odtopm new2 justify'}).text
    date = comment.find('span', {'class': 'pozn_lightest odleft_pet'}).string
    return user, text, date

My suggestions are.

Use requests library, It's more pythonic than urllib.

Use namedtuples instead of classes where possible. Easier to read and to write. If you need to add functionality you can inherit from namedtuple.

Don't write one liner get_this get_that functions. It's useful when you're hiding some implementation, but hiding one or two lines - it's useless and it's even a bit less readable (when you would need this implementation).

What you're doing with function name get_authors you can do just as easy with giving a variable self-explanatory name like authors = .... Everybody would understand that next one or two lines (if it's a comprehension) is getting authors in some way and they can read this lines if they want details.

Also get_book_info means suggesting it's loading or getting something from somewhere. In java it just means that this is some property, but in python we have @property decorator and don't need getters and setters so get is used when you're loading something. Instead it's more accurate to think of it as pure function that takes html and outputs Book. You can call it make_book_info, def book_info_from(html): or just book_info.


It looks to me as you want to join the array. I don't know TypeScript, it it should have a join method on the array.

selectPropertyQuery = properties.join(",")


Using Mockito to verify that an object is saved

Looking at your production code, my positive test case would check the getToken() and savePayload() methods were invoked; and the same string returned from getToken() was also returned by processTokenRequest().

Some points:

I wouldn't use the any matcher with verify(). Explicitly state what you want.
No need to return value from a method when you don't use the returned value i.e. doAnswer for savePayload() is unnecessary.
As mentioned, times(1) is the default for verify() and used in your first test.
Tests shouldn't throw exceptions.
Static imports often make short code easy to read.
Is isNotBlank() enough?


Computer Science glossary made with Tkinter

PEP-8

As always, follow the PEP-8 coding standards.

Don't exceed 79 characters per line
You a space around the = assignment operator (you mostly do this, but violate it in entered_text=textentry.get()

Use a main function

Avoid writing code in the main scope.  Move the code into a main function, and call it ... but only if the script is not imported into another file:

def main():
    window = Tk()
    # ...
    window.mainloop()

if __name__ == '__main__':
    main()

Catch only the exceptions you expect

The following code:

try:
    definition = my_compdictonary[entered_text]
except:
    definition = "Sorry definition not found"

will catch any and every exception, and ignore them all, regardless of the correct type.  Why is it bad?  Imagine you correct the spelling error in your main program, and change my_compdictonary to my_compdictionary, but you don't correct it in this section of code.  You test the program, and it doesn't crash, but every definition you look up returns "Sorry definition not found".  Where is the bug?  How hard is it to debug?

If instead the code was written as:

try:
    definition = my_compdictonary[entered_text]
except KeyError:
    definition = "Sorry definition not found"

the program would crash with a NameError, with the traceback showing you the exact line in question.  Now how hard is it to debug?

In this particular case, the try...except structure is really overkill.  You can provide a default argument when getting a key from the dictionary to handle the key not found case.  That reduces the above four lines to only one:

definition = my_compdictonary.get(entered_text, "Sorry definition not found")

Keep related code together

You have:

output.delete(0.0, END)
# Four
# unrelated
# lines of
# code
output.insert(END, definition)

It would be clearer to keep output.delete() and output.insert() as back to back lines.  Eg)

definition = my_compdictonary.get(entered_text, "Sorry definition not found")
output.delete(0.0, END)
output.insert(END, definition)

Avoid global

Avoid using global as much as possible.  It is a sign of poorly organized code, and makes it harder to reason about the correctness of the code, and harder to test the code because side-effects increase in scope.

In this case, it is simple to avoid the global definition because definition is never used anywhere except in the click() function.  It should not be a global variable; it is local!

Never ask for more than you need

with open("glossary.txt", "r+") as file:

Why are you opening the file for reading plus?  Will you ever be writing to it?  Can the program now accidentally write to the file because it has write privileges, corrupting the file?  You are only reading the file; just open it for reading.

with open("glossary.txt") as file:

Be liberal in what you accept

The Robustness Principle warns us about the input we get from the outside.  Be fault tolerant.  Or perhaps better, make it so faults can't happen.

    word, defintions = line.strip().split(" : ")

What happens when a definition contains a colon?

noun : A person, place, or thing.  Can be classified into two groups : common or proper.

split(" : ") now returns 3 items, and you've only got variables for two.  So you'll get ValueError: too many values to unpack (expected 2).  How can you avoid this?  How about telling split() that you only expect to find one delimiter:

    word, defintions = line.strip().split(" : ", 1)

Now, word is "noun" and defintions is "A person, place, or thing.  Can be classified into two groups : common or proper."

What about blank lines?  They will still crash the program.  You might want to test for those as well.  What about non-blank lines that don't have a definition?  Those, well maybe it would be ok if those result in an exception; that would be really bad input in the "glossary.txt".

Make it easier for reviewers to run your code.  You have an image 'me.gif' in your code that we don't have.  Running without it crashes the program due to file not found.  How big was that image?  32x32?  300x300?  It would affect the size of the resulting window.  Do we just delete the lines of code so we can test the program?

How about 'glossary.txt'?  Do we have to guess what the file format is?  Perhaps you could have given a sample file with 3 or 4 entries.

Future Improvements

You might want to allow the user to look up a definition by just pressing "Enter" after typing in the word.  The way it works right now, the user has to move their hands from the keyboard to the mouse.

What if the user enters with CAPS LOCK on?  What if the definition is provided with a capital letter?  Is the definition really not found?  Could you be a little more liberal in what you accept?

Here is a simple refactoring of your original code with some of the suggestions from comments above.  No global variables.  The click() function is moved into main(), so it has access to the local variables textentry, my_compdictonary and output.  The image was deleted, so I could quickly run the program.  The dictionary is generated using list comprehension, and will ignore blank lines.

This is by no means the "best" code.  Many improvements can still be made in naming (can we have something better than click?), spelling of variables, and so on.  Perhaps a class may be in order.

from tkinter import *

"""
A Computer science glossary made with Tkinter

Requires a "glossary.txt" file with definitions, one per line, with a
space-colon-space separating the term from the definition.  Eg)

    word : a fragment of language
    term : a word or phrase used to describe a thing or to express a concept

Also should require a "me.gif" image of approximately 64 x 64 pixels, but
that was removed temporarily.
"""

def main():
    """Main function.

       This function creates the UI, and enters the tkinter mainloop.
       It does not return until the user closes the UI."""

    def click():
        entered_text = textentry.get()
        definition = my_compdictonary.get(entered_text,
                                          "Sorry defintion not found")
        output.delete(0.0, END)
        output.insert(END, definition)

    window = Tk()
    window.title("Computer Science Glossary")
    window.configure(background="black")

    Label(window, text="Enter the word you want the definition for:",
          bg="black", fg="white", font="none 12 bold"
         ).grid(row=1, column=0, sticky=N)

    textentry = Entry(window, width=20, bg="white")
    textentry.grid(row=2, column=0, sticky=N)

    Button(window, text="SUBMIT", width=6, command=click).grid(row=3, column=0, sticky=N)

    Label(window, text="\nDefinition:", bg="black", fg="white",
          font="none 12 bold"
         ).grid(row=4, column=0, sticky=N)

    output = Text(window, width=60, height=4, wrap=WORD, background="white")
    output.grid(row=5, column=0, columnspan=1, sticky=N)

    with open("glossary.txt", "r") as file:
        my_compdictonary = dict( (line.split(" : ", 1)) for line in file if line )

    window.mainloop()

if __name__ == '__main__':
    main()


I'm not sure I understand what you're asking, but what if you just use setInterval() instead of setTimeout()?

function startWorker(obj) {
  if (!code) {
    setInterval( () => {
      console.log(obj.action);
    }, 2000);
  }
}

const code = false;
const someObj = {
  action: "tick"
};

startWorker(someObj);


Optimizing a JavaScript snippet for portability and readability

I would make it less compact to improve readability.  Leave it up to your build process (minifier) to make things compact.  Your goal should be to make things understandable.

Use regular expressions

In cases like this, where you have a strict format, I love using regular expressions:

/** @const */
var TIME_FORMAT = /(\d{2}):(\d{2})/;
...
"10:30".match(TIME_FORMAT) // == ["10:30", "10", "30"]

This makes it clear that you expect a date to consist of two digits a colon, and two more digits.  As a bonus, let everyone know it's a constant with JSDoc and common coding conventions.

Define functions

Short modular code is easy to read:

/**
 * Parses a time string and returns the hours and minutes.
 */
function parseTime(text) {
    var match = String(text).match(TIME_FORMAT);

    if (match === null) {
        throw new Error('Time "' + text + '" could not be parsed.');
    }

    return {
        hours:   Number(match[1]),
        minutes: Number(match[2])
    };
}

/**
 * Gets the total minutes of overtime based on time worked and number of working hours
 * in a day.
 */
function calculateOvertime(parsedTime, workingHours) {
    var minutesWorked = parsedTime.hours * 60 + parsedTime.minutes;
    var minutesRequired = workingHours * 60;
    return minutesWorked - minutesRequired;
}

Here, the parseTime parses the time, returning an object, and calculateOvertime calculates the overtime.

Put it all together

Putting it together, your actual function does become more compact and more readable because tangental functions are extracted:

/**
 * Gets the total minutes of overtime from a tracking table.
 *
 * @param selector A CSS2.1 selector, DOM element or jQuery object pointing to the
 * tracking table.
 */
function getOvertimeFromTable(selector, dailyWorkingHours) {
    var totalMinutesOfOvertime = 0;
    var $dailyTimes = $(selector).find("font:not(:empty)");

    $dailyTimes.each(function () {
        var parsedTime = parseTime($(this).text());
        var minutesOfOvertime = calculateOvertime(parsedTime, dailyWorkingHours);

        totalMinutesOfOvertime += minutesOfOvertime;
    });
}

alert('Overtime so far: ' + getOvertimeFromTable('.links', 8) + ' minutes');

Protecting global, enabling compilation

Right now we are exposing a variety of variables and functions on the global object.  This means that anyone could call parseTime or read a similar function.  It also means a minifier can't rename the function to a shorter name.  Wrapping everything in a closure will be the final step for making sure your output code is more compact and your source needn't be:

/**
 * Alerts the number of hours of overtime you have accumulated so far in this pay cycle,
 * assuming a standard 8-hour day.
 */
(function () {
    /* Your code here */
}());


Be more generic

As I've suggested here, you should not force the use of an std::function. Instead, take any type of callable and either a fixed or an unlimited number of arguments, using std::invoke inside your implementation.

More importantly, you really don't need multiple functions for a different number of arguments; use variadic templates, e.g. have a signature such as:

template< class F, class... Args>
std::optional<double> getFunctionTime(F&& f, Args&&... args) noexcept;

(ignoring any other potential changes)

This will make it easier for you to invoke, too:

auto ftime = gstd::getFunctionTime(number_crunching);
auto f1time = gstd::getFunctionTime(multiplier, 5);
auto f2time = gstd::getFunctionTime(sum, 4, 5);

Alternatively, you could only accept 0-argument runnables, in which case you simply pass lambdas:

auto f1time = gstd::getFunctionTime([]() { return multiplier(5); });

Return a chrono::duration

Don't convert your duration to a plain numeric value - keep the more specific type.

Use integral values for durations

Why use a floating-point value in the duration? Stick with integral values unless you have a good reason to do otherwise.

Consider changing the name

I'd use time_an_invocation or time_invocation but I guess that's a matter of taste.

Consider leaving it to the caller to handle exceptions

You're forcing a certain behavior w.r.t. exceptions. I'd consider simply not handling them, so that timing the invocation of a function that throws an exception, throws an exception. That would simplify your code and avoid a  dependence on std::optional, which the caller might not be interested in. Remember the caller has to have additional code to handle the empty-optional case anyway.

Consider using a stopwatch class instead

In a related question, @Edward suggests keeping the invocation and the time measurement separate, using a "stop-watch" class. That might not be "better" but it's certainly worth considering.


Check if modelitem refers to currently logged in user with mvc identity

I would add the logic in the controller

 public ActionResult(){
    ApplicationDbContext db = new ApplicationDbContext();
    List<ApplicationUser> model = db.Users.ToList();

    // Viewbag just being an example for a model. It would be better to
    // pass this into a property in the model that is being passed to the view.
    foreach (var item in model)
    {
        ViewBag.UserEmail = System.Web.HttpContext.Current.User.Identity.Name
                         == item.Email ? item.Email : null;
    }
  // If we were returning a viewmodel we could add this check into a
  // ApplicationUser ( public ApplicationUser AppUser {get; set;})
  // property which could then be accessed in the model as Model.AppUser. This
  // would hold all the values for the application user. If that is
  // something you would need

 return View(model);
 }

This will assign the ViewBag.UserEmail to either the currently logged in users email or null. I added the full namespace because sometimes Current is not directly accessible

And in the view

 if(Viewbag.UserEmail != null)
 {

 THIS IS ME

 }

This then just checks if the ViewBag is null and displays a code block if it is not.

This will still work in a loop. Because the ViewBag holds the current users email which can be checked against in a foreach

@foreach ( var item in Model){

@item.Name

       if(ViewBag.UserEmail == item.Email){
          <button>Edit </button> // Should only be visible to logged in user
       }

       // Or Like
        @( ViewBag.User == item.Email ?
          Html.Raw("<button class='btn btn-primary'>Edit</button>") :
          Html.Raw("<button class='btn btn-primary'>View</button>"))
}


A basic calculator in C that uses a loop

Indentation

Frankly, your indentation is all over the place!

The basic idea of indentation is that you indent based on scope. A scope begins with { and ends with } (you can omit the { } sometimes but you shouldn't). I'll indent a few snippets of your code and you can do the rest. You seem to put { on the next line more often than you put { on the same line so that's the convention I've used. Using this convention, the { should be indented to the same depth as the matching }.

printf("Please enter any number:\n");
if (scanf("%f", &a) != 1)
{
    fprintf(stderr, "error: first input must be a number\n");
    return EXIT_FAILURE;
}

// ...

switch(n)
{
    case 1:
        c = a + b;
        printf("The answer is:%f\n", c);
        break;
}
printf("would you like to try again? (y/n)\n");
scanf(" %c", &choice);

Indentation is really the only major problem with this code.

Extensibility

You could use doubles instead of floats to gain a little bit of extra precision. If you want to make this program really easy to extend (after you've learnt about a bunch of new stuff) then you could store the operations in an array. Then the user will type add you'll look up a function pointer in an array. Something like this:

typedef struct {
    const char *name;
    double (*func)(double, double);
} Operation;

const Operation ops[] = {
    {"add", add},
    {"sub", sub}
    // ...
};

I'll let you figure out the details. Some things you'll need to look up are arrays, structs, function pointers and string comparison (strcmp).

Unary operations

You could complicate things further by allowing unary operations (e.g. sin, sqrt). You'll need separate arrays for unary and binary operations.

typedef struct {
    const char *name;
    double (*func)(double);
} UnaryOperation;

typedef struct {
    const char *name;
    double (*func)(double, double);
} BinaryOperation;

Parsing

If you're up for a real challenge you could allow the user to enter an expression like 14 + 2 * sin(0.8) and evaluate the expression. This sort of thing is quite tricky indeed! You'll need to learn about recursive descent parsing (there are other types of parsing but this is probably the easiest), memory management and pointers. The last time I did something like that, the resulting program was 700 lines so it's quite a step up from the code in your question.


Your program is over-engineered in a way that makes it hard to decipher.  Because every method is one line long, it's like reading a poem whose lines have been scrambled.  You would be much better off writing a simple function, like this:

require 'fileutils'

def move_screenshots(src_dir, dest_tree)
  re = /^Screen Shot (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) at/
  Dir.foreach(src_dir) do |filename|
    if date = re.match(filename)
      dest_dir = "#{dest_tree}/#{date[:year]}/#{date[:month]}/#{date[:day]}"
      FileUtils.mkdir_p(dest_dir)
      FileUtils.mv("#{src_dir}/#{filename}", dest_dir)
    end
  end
end

move_screenshots("/Users/home/Desktop", "/Users/home/Pictures/Screenshots")

I wouldn't bother with Dir#glob, since it's a bit redundant with the regex.  Note that screenshots aren't necessarily in PNG format: the image format can be configured using defaults write com.apple.screencapture type ….  I also wouldn't bother testing File#exists? before calling FileUtils#mkdir_p, since mkdir_p implicitly performs that check anyway.

Instead of an hourly cron job, consider creating a Folder Action Script that is triggered instantly when a file is added to the folder.


Should I be using a stored procedure for this function in my code behind?

This is overall comments on above code

1) Encapsulate what is repeating

In your method you are opening sql connection, adding parameter  and executing it one by one. Rather doing this please extract out it into one method.

 private void ExecuteNonQuery(string connectionstring, string query, IEnumerable<SqlParameter> parameters =null)
  {
            using (var connection = new SqlConnection(connectionstring))
            {
                connection.Open();
                using (var command = new SqlCommand(query, connection))
                {
                    if (parameters != null)
                    {
                        foreach (var parameter in parameters)
                        {
                            command.Parameters.Add(parameter);
                        }
                    }
                    command.ExecuteNonQuery();
                }
            }
   }

2) Always dispose the connection

In above code your opening connection and closing it, but this can lead into connection leak in case of errors. Please wrap your code into using statement or try clause like this

using (var connection = new SqlConnection())
{

}

3) Distribute your responsibility into layer

The above code is doing too much

script registering
Sql Connection stuff
Data Populating and clearing

Please separate out your code into at least two classes
1) Fetching data class
2) UI binding stuff class

4)inline SQL vs Stored Procedure

Stored Procedure is good as your code lies at one place in db but creating Stored Procedure for one line of SQL is not a good idea. If your logic is going to be complex and big ,Use a Stored procedure other wise inline sql.

PS: I have created a  gist named SQLHelper class for you to abstract out the sql connection and command things,

https://gist.github.com/paritoshmmmec/5c3855af7215ac87d787


The following function works without for loops or any function of the *apply family. Furthermore, it does not require additional packages but makes use of base functions only. See the code comments for further details.

significant_drydowns <- function(rain, threshold = 10, k = 48) {
  # all values except the first one
  rain_tail <- rain[-1L]
  # logical index of start of no-rain period
  starts <- head(rain, -1L) > 0 & !rain_tail
  # no-rain groups
  groups <- cumsum(starts)
  # sum of the amount of rain in the last k elements
  # (for e.g., k = 5 the filter is c(1,1,1,1,1), therefore
  # the sum of 5 preceding elements is calculated)
  past_rain <- filter(rain, rep.int(1L, k), sides = 1L)
  # valid groups (previous amount of rain exceeds threshold)
  valid <- past_rain[starts] >= threshold
  # replace `groups` values with NA if
  #  (a) there is rain or
  #  (b) this is the first rain or no-rain period
  is.na(groups) <- rain_tail | !groups
  # replace `groups` values with NA if amount of rain is below threshold
  # (here `groups` is used as a numeric index for `valid`)
  is.na(groups) <- !valid[groups]
  # add NA to match length of original vector and set names
  setNames(c(NA_integer_, groups), rain)
}

Some results:

> significant_drydowns(rain, 5, 5)
 0  0  0  2  3  0  0  0  1  5  0  0  0  0  0  0  6  1  1  1  0  0  0
NA NA NA NA NA  1  1  1 NA NA  2  2  2  2  2  2 NA NA NA NA  3  3  3
> significant_drydowns(rain, 7, 4)
 0  0  0  2  3  0  0  0  1  5  0  0  0  0  0  0  6  1  1  1  0  0  0
NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA  3  3  3


public static async Task<T> ReadJson<T>(String fileName)

The Task-based asynchronous pattern says that the names of Task-returning methods should end with Async, e.g. ReadJsonAsync.

if (String.IsNullOrEmpty(fileName)) return default(T);

Why return the default value here? Empty fileName seems like a bug that should be discovered as soon as possible, so a more reasonable (and common) response would be to throw an exception.

TaskEx.Run

Usually, calling Task.Run shouldn't be done in a library, it should be done by the user. That way, the user will understand that the method is not truly asynchronous. But this library seems to be specifically meant to be called from the UI thread, so I guess it's okay here.

I don't quite understand the need for the Mutex here. Do you really expect to access the same file multiple times at the same time from one application? That doesn't sound like a common situation to me.


JavaScript-function for to convert a dash-separated string into camel case

Yes, I think you should use String.prototype.replace instead of array looping. I think so because .replace is probably going to be faster and because the code will be easier to understand.

I would also like to warn you about equality operator (===) in JavaScript. This returns false:

"ddd"===new String("ddd")

This returns true:

"ddd"==new String("ddd")

Also try to avoid if( !xxx ) with variables that are not supposed to be boolean, because it can get quite confusing for people reading your code.

Here's the callback replacement you talked about. You should use that and improve it so that it fits your exact definition if the conversion, which is missing in the question, so it wasn't addressed.

// -------- THE ACTUAL FUNCTION -------------------------

/* blah blah blah */
function dashedToCamelCase( dashed ) {
  if( typeof dashed != "string" || dashed.length==0 )
    return "";
  return dashed.toLowerCase().replace(/\-([a-z]?)/g, function(match, letter) {
      return letter.toUpperCase();
  });
}

// -------- THE ACTUAL FUNCTION - END -------------------

// --- TESTING ---------------------------
var test = [ 'north',
             'north-east',
             'north-east-east',
             'south-west-west-north',
             'south-wEst-EaSt',
             'North-west-EAST',
             'NORTH-EAST-SOUTH-WEST',
             248,
             '' ];
var expect = [ 'north',
               'northEast',
               'northEastEast',
               'southWestWestNorth',
               'southWestEast',
               'northWestEast',
               'northEastSouthWest',
               '',
               '' ];

var output = document.getElementById("output");
test.forEach(function(item, i) {
  try {
    var result = dashedToCamelCase(item);
    if(result==expect[i]) {
      writeOutput(item+" => "+result, "correct");
    }
    else {
      writeOutput(item+" => "+"got '"+result+"' instead of '"+expect[i]+"'", "wrong");
    }
  }
  catch(e) {
    writeOutput(e.message, "error");
  }
});
function writeOutput(text, className) {
  var p = document.createElement("p");
  p.appendChild(new Text(text));
  p.className = className;
  output.appendChild(p);
}
.correct {
  color: green;
}
.wrong {
  color: red;
}
.error {
  font-weight: bold;
  color: red;
}


Avoiding code duplication for reading in similar values for each derived class

Just scatching the surface of your code, but

By default, the first enum constant has a default value of 0 , so this code

       public enum GrooveType : int
            {
                TKY = 0,
                VSingle = 1,
            }

could be written as

       public enum GrooveType : int
            {
                TKY,
                VSingle
            }

Your ProcessParam was implemented twice. When things like this occur you should change  ProcessParam into an abstract class. This is called Dependency Inversion

  Dependency Inversion: In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:1

  High-level modules should not depend on low-level modules. Both should depend on abstractions.
  Abstractions should not depend on details. Details should depend on abstractions. More details of this Dependency Inversion

This line of code should have been

public class ProcessParam
    {
        public ProcessParam() { }
        public double probeStartAngle { get; set; }
        public double probeStartDist { get; set; }
    }

should have been

abstract class ProcessParam   // Abstract class
{
    public abstract void AbstractMethod();   // Abstract method
    public abstract double probeStartAngle { get; set; }
    public abstract double probeStartDist { get; set; }
}

Dependency Injection : Inject dependency rather than creating an object in the constructor. This is good

public SimulationParamVSingle(ProcessParam parameters)
    : this()
{
    this.processParam = parameters;
}

This is bad

 public SimulationParamVSingle()
        {
            this.processParam = new ProcessParam();
        }


Bug
You're code has a bug-ish. When using this, if instead of hitting enter when asked to enter a character you enter some other letter and then you press enter, then next newline will be skipped and you will have two lines merged into one:

Fooa
BarHello, World!
Spama
Eggs

where the text file was:

Foo
Bar
Hello, World!
Spam
Eggs

To be honest, I'm not quite sure which line this is occurring on, but I think it has something to do with the getchar() call; when I pressed a, the next line was printed out.
Bug #2
Using the same file as above but this time passing it through STDIN like so:
./a.out < Foo

I got this as a result:

 Fooarello, World!pamggs

I didn't touch the keyboard at all; it just flew through the file. I don't think this is intended.
However, this time, I think I know why. It's this line:
getchar();

When the end of a line is reached, then this is called. However, since the file you are reading is from stdin and getchar() also reads from stdin, then this call is going to remove the next character from the file.
See the input again, but with the characters removed by getchar:

FoobarHello, World!spameggs

The bolded characters are the characters that appeared after each newline.


Ruby command to edit a field in a SAM file

There isn't much to say here, it is clear what your solution is doing, and attempts to make it more concise would just make it harder to read.

I recommend replacing map! with each - map! indicates that you want the values returned by grep to be changed in place. Since that result is then discarded, it makes the code more difficult to understand.

Personally, I avoid ! methods whenever possible. The hidden mutation which can occur makes code harder to reason about. It is fine in this small example (especially once map! is replaced with each), but in a larger program it will hide bugs.

Avoiding mutation in this case makes the code a bit longer, but it has the benefit of not needing to stop and think about what has changed and if it matters. I spent several minutes trying to figure out why your code didn't fail when a field didn't include a - since gsub! returns nil when no replacements are made.

Though less concise, I prefer the following version:

ruby -ane '
$F[11..] = $F[11..].map { |x| x.start_with?("RX:Z:") ? x.gsub(/-/, "") : x }
puts $F.join "\t"
' file.sam

Not automatically joining $F back together to create $_ makes sense, what should ruby do if you use (or modify) $F but then set $_ to something else? Setting $_ whenever $F is modified would be rather confusing and bad for performance.


If you've only learned VBA a week ago, then congratulations and a good job getting a working solution! Hopefully the information and tips here can provide some help in refining not only your solution, but to help guide your code in the future.

You've avoided some basic traps because you're already using Option Explicit and you are assigning a type to each variable on the Dim line. Most professional VBA developers will advise that it's a better habit to declare each variable immediately before it's used, even down lower in the method. This avoids the "wall of declarations" up front.

You have a potential problem on the statement to determine the lastrow value. It's an easy thing to miss, but when you use Rows.Count, you are referring to the number of rows on the active worksheet, NOT the number of rows on ShNote (which is what you want). So the fully accurate line is

lastrow = ShNote.Range("C" & ShNote.Rows.Count).End(xlUp).Row

Of course the same thing goes for similar statements throughout your code.

(I'm skipping around in your code, it will all make sense in the end I promise)

The values that you're using in the Select Case statement are simple numbers, but those numbers are meaningless unless you give them context. What do those numbers mean in your workbook and for your data? Translate that "meaning" into your code. One way can be to create a set of constants. I've defined a set like this:

Const MAX_THRESHOLD As Long = 20
Const HIGH_THRESHOLD As Long = 17
Const MED_THRESHOLD As Long = 15
Const LOW_THRESHOLD As Long = 13

Now you can change the values just be changing the definitions, and your code makes more sense as you (or me) reads it.

Next, I have to question why you're calculating the same last row value on ShPPT eight times in a row. You can calculate it once, then copy the assignment to the other variables. You can also use more meaningful variable names, since we're defining why we're keeping track of the different rows.

Dim lastSourceRow As Long
lastSourceRow = ShNote.Range("C" & ShNote.Rows.Count).End(xlUp).Row

'--- start all the rows at the same value
Dim lastMaxRow As Long
Dim lastHighRow As Long
Dim lastMedRow As Long
Dim lastLowRow As Long
lastMaxRow = lastSourceRow
lastHighRow = lastSourceRow
lastMedRow = lastSourceRow
lastLowRow = lastSourceRow

The separate "counters" you had for the columns of each threshold hold the exact same value as the rows, so they aren't needed.

I see that each value is incremented separately, but there's also a very consistent pattern to the logic within each Case. When you see that, your first thought should be to break out a separate function that can isolate the logic in a single place. That makes it easier to change later. For example, your method could be

Private Function NowCopyPaste2(ByVal fromRow As Long, _
                               ByVal toRow As Long, _
                               ByVal toColumn As Long, _
                               ByRef fromWS As Worksheet, _
                               ByRef toWS As Worksheet) As Long
    fromWS.Cells(fromRow, 3).Copy
    toWS.Cells(toRow + 6, toColumn).PasteSpecial xlPasteValues
    fromWS.Cells(fromRow, 5).Copy
    toWS.Cells(toRow + 6, toColumn + 1).PasteSpecial xlPasteValues
    NowCopyPaste = toRow + 1
End Function

This produces the same logic that exists in your original post. However, you're using copy/paste to transfer a value from one cell to another and there's a much simpler way that uses far less resources. Just simply assign the value of one cell to the other. The improved NowCopyPaste function is

Private Function NowCopyPaste(ByVal fromRow As Long, _
                              ByVal toRow As Long, _
                              ByVal toColumn As Long, _
                              ByRef fromWS As Worksheet, _
                              ByRef toWS As Worksheet) As Long
    toWS.Cells(toRow + 6, toColumn).Value = fromWS.Cells(fromRow, 3).Value
    toWS.Cells(toRow + 6, toColumn + 1).Value = fromWS.Cells(fromRow, 5).Value
    NowCopyPaste = toRow + 1
End Function

Finally, the main logic of your code is more clear for the upfront work you've done and the clear definitions used:

'--- values are copied to the PowerPoint worksheet and sorted by
'    columns according to the threshold tests
Dim i As Long
For i = 6 To lastSourceRow
    Select Case ShNote.Cells(i, 5).Value
        Case Is = MAX_THRESHOLD
            lastMaxRow = NowCopyPaste(i, lastMaxRow, 3, ShNote, ShPPT)

        Case Is >= HIGH_THRESHOLD
            lastHighRow = NowCopyPaste(i, lastHighRow, 6, ShNote, ShPPT)

        Case Is >= MED_THRESHOLD
            lastMedRow = NowCopyPaste(i, lastMedRow, 9, ShNote, ShPPT)

        Case Is >= LOW_THRESHOLD
            lastLowRow = NowCopyPaste(i, lastLowRow, 12, ShNote, ShPPT)

        Case Else
            '--- what will you do here? (could be nothing but it's
            '    still a good idea to document with a comment that
            '    values in this range are not copied
    End Select
Next i

Notice that I also have used comments prior to each logic block that explain what the code does and why. This will always be important for maintaining the code, even if you are the only one to ever look at it again.

Here's the whole module in a single block:

Option Explicit

Public Sub AnalysisClientRating()
    Const MAX_THRESHOLD As Long = 20
    Const HIGH_THRESHOLD As Long = 17
    Const MED_THRESHOLD As Long = 15
    Const LOW_THRESHOLD As Long = 13

    Dim lastSourceRow As Long
    lastSourceRow = ShNote.Range("C" & ShNote.Rows.Count).End(xlUp).Row

    '--- start all the rows at the same value
    Dim lastMaxRow As Long
    Dim lastHighRow As Long
    Dim lastMedRow As Long
    Dim lastLowRow As Long
    lastMaxRow = lastSourceRow
    lastHighRow = lastSourceRow
    lastMedRow = lastSourceRow
    lastLowRow = lastSourceRow

    '--- I don't know what your entry and exit points do, but you should
    '    create a comment that gives the next developer an idea why these
    '    methods exist and why they are here. what do they do?
    Entry_Point

    '--- values are copied to the PowerPoint worksheet and sorted by
    '    columns according to the threshold tests
    Dim i As Long
    For i = 6 To lastSourceRow
        Select Case ShNote.Cells(i, 5).Value
            Case Is = MAX_THRESHOLD
                lastMaxRow = NowCopyPaste(i, lastMaxRow, 3, ShNote, ShPPT)

            Case Is >= HIGH_THRESHOLD
                lastHighRow = NowCopyPaste(i, lastHighRow, 6, ShNote, ShPPT)

            Case Is >= MED_THRESHOLD
                lastMedRow = NowCopyPaste(i, lastMedRow, 9, ShNote, ShPPT)

            Case Is >= LOW_THRESHOLD
                lastLowRow = NowCopyPaste(i, lastLowRow, 12, ShNote, ShPPT)

            Case Else
                '--- what will you do here? (could be nothing but it's
                '    still a good idea to document with a comment that
                '    values in this range are not copied
        End Select
    Next i

    Exit_Point

End Sub

Private Function NowCopyPaste(ByVal fromRow As Long, _
                              ByVal toRow As Long, _
                              ByVal toColumn As Long, _
                              ByRef fromWS As Worksheet, _
                              ByRef toWS As Worksheet) As Long
    toWS.Cells(toRow + 6, toColumn).Value = fromWS.Cells(fromRow, 3).Value
    toWS.Cells(toRow + 6, toColumn + 1).Value = fromWS.Cells(fromRow, 5).Value
    NowCopyPaste = toRow + 1
End Function

Private Sub Entry_Point()
    '--- does something interesting?
End Sub

Private Sub Exit_Point()
    '--- does something interesting?
End Sub


Using Interlocked on a class reference grants atomic transaction when you exchange an object for another;

For example, using

Interlocked.Exchange<T>(ref _data, value);

will exchange an object for an other, returning the previous object.

ReaderWriterLockSlim will protect some parts of your code, and you could also protect the object get/set with it.

Use only one of the lock, not both !

Also, you don't need usually to protect the initial set statement in your Ctor. Basically, you can only create a new object once in only one thread, before  sharing anything related to this object.

One last point, with this code you are protecting the object reference, not the object itself. See below ...

class MyString {
    public string Data {get; set;}
}
...
var myString = new MyString() ;
var mySharedString = new SharedData<MyString>(myString) ;
...
... thread 1
... mySharedString.Value.Data = "Hello" ;
...
... thread 2
... mySharedString.Value.Data = "BAD" ;

If the shared object is ReadOnly, it works, if the object is mutable, it will fail badly.


Implement Java hasNext() and next() in C++

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

Make sure all control paths return

Within your implementation of next(), what happens if hasNext() is not true?  The calling function will be expecting a type T but it won't get anything.  This should be addressed.

Consider throwing an error

The Java version of next() throws a NoSuchElementException if there are no more elements.  You could reproduce this behavior by actually deleting code (which would also address the above issue):

T next(){
    return container.at(curr_pos++);
}

This works because at throws a std::out_of_range error if there are no further items.

Think carefully about signed vs. unsigned

The curr_pos member does not have a reasonable interpretation for negative values, so it would make more sense to declare it unsigned rather than int.

Prefer modern initializers for constructors

The constructor could be written using the more modern parameter intialization style.  That version would look like this:

iterator(std::vector<T> vec)
    : container{vec}, curr_pos{0}
{}

Use const where practical

The current hasNext() routine does not (and should not) modify the underlying object, and so it should be declared const:

bool hasNext() const { /* code */ }

Simplify expressions

The hasNext() routine is overly complex.  It could instead be this single line:

bool hasNext() const {
    return curr_pos < container.size();
}

Use const references where practical

The constructor could and should take a const reference to avoid a copy and to preserve flexibility.  You could also use default parameters to eliminate the no-argument constructor:

iterator(const std::vector<T> &vec = {})
    : container{vec}, curr_pos{0}
{}

Consider providing an initializer list constructor

The code has a few versions of something like this:

std::vector<int> int_vec {1,2,3,4};
iterator<int> int_it(int_vec);

It would be convenient to instead be able to write this:

iterator<int> int_it{1,2,3,4};

Here is a constructor that will allow that usage:

iterator(const std::initializer_list<T>& v)
    : container{v}, curr_pos{0}
{}


Deploy folder to desired path - PowerShell function

The code is very cleanly written, and its easy to see what is going on.
The verb you are using for the command is not officially 'supported'. Every command should stick to the official list of verbs, that can be checked with get-verb.  would suggest New-Folder
I don't know why you go through this much code to create a folder when you could append a -force to the back end of the new-item command. I guess if you have a system that required you to log every instance where one would create a folder, this would make sense.
If you have a system where you do commands to an external module, i would suggest you look into the #require tag in powershell, instead of having import-module at the start of your command
you can easily cast to a psobject just by doing [PSCustomObject]@{cancel=$cancel}.
use [CmdletBinding()] at the start of your function to get powershell standard switches (-verbose, -debug, -erroraction etc..). just put it between the function definition line and the param definition line (line 2)


AngularJS shopping cart using local storage

This is interesting,

you have quite a bit business logic in your code there..
If I were try to break this, I would definitely change the price of the items I buy in the local storage to 1 cent and see if the server side would accept that price. (It should not, and recalculate any pricing from item master data). Next I would place a breakpoint in some of your btw related routines and make it return 1 cent and see if the server side could be broken that way.

Other than that, I see no security flaws in there. Let me know if you want me to do a review of other aspects of your code.


A regular expression parsing library in C

What you did well

The code seems clean and logically organized.  I like your 0x100-bit hack to indicate special characters.  You could make that convention more obvious in the comments, though.

What you could improve on

The return value of regex_match() is weird.  I'd like it to return a non-zero value if the match succeeded, and a zero value if the match failed, so that I can call it like this:

if (regex_match(...)) {
    // Do stuff for successful match
} else {
    // Do stuff for failed match
}

Trying to return the position of the match just leads to confusion, reminiscent of the way PHP's strpos() returns 0 to indicate a successful match at the beginning of the subject (but FALSE to indicate a non-match).  You don't want to be like PHP, do you?

I suggest that the signature for regex_match() should look like this:

/**
 * Returns 1 if matched, 0 if not matched.
 *
 * Pass a pointer to a match_result if you care to find out the
 * details of the match (its length, position, and possibly other
 * information supported in the future, such as parenthesized
 * capture groups), or pass a NULL if you don't care about the details.
 */
int regex_match(const char *regex, const char *subject, struct match_result *result);

Alternatively, return a pointer to a new struct match_result if the match succeeded.  The caller would have to free() the result later, though, so I don't like it as much.
Regular expressions often include modifier flags, such as a case-insensitive flag or a continue-searching-where-the-previous-match-ended flag.  You might want to plan your interfaces accordingly.  (To support the latter, the struct match_result* would probably become an in-out parameter rather than an out-parameter.)
For performance, regular expressions are frequently compiled into an automaton.  You interpret the regular expressions as you go.  You may wish design the library's interface to have a regex_compile() function that transforms the expression into a struct that is meaningful to your library but opaque to the user.  For now, the "compilation" could just be the identity transformation; you can enhance it later when the need for better performance arises or when you enhance the feature set of the regular expressions.
The function name regex_matchGroup() confuses me.  "Group" implies something like parentheses, I think.  regex_matchAtom() might be a more appropriate name.
You need unit tests!


Use the standard library

But I'd like to refine IDigest more elegantly. How can I do it?

Your IDigest basically reimplements std::vector<uint8_t>. Realizing this, I would therefore remove it entirely and replace it with std::vector<uint8_t>. You could add this to namespace chash if you like:
using Digest = std::vector<uint8_t>;

Your IDigest has limitations: you cannot compare two digests with each other. But you can with std::vector<uint8_t>. The only feature your class has is that it has a function to convert it to a string containing hexadecimal characters. I would leave that out entirely, and leave it up to the application to implement whatever they need to convert a digest to some other form, if they need that at all. But if you do want to provide this as a utility, simply create an out-of-class function to do this:
std::string toHex(const Digest &digest) {
    std::string outHex;
    outHex.reserve(digest.size() * 2);

    for (auto b: digest) {
        ...
    }

    return outHex;
}

Consider whether you need virtual base classes
Do you really need virtual base classes? These come with a cost: derived classes will now have a vtable, and function calls need to go through an extra level of indirection. Consider using a non-virtual base class, and make the base class's constructor protected, so you can no longer create an instance of a base class.


Simplex number calculation (all dimensions) in python

You should use a for loop rather than a while loop to solve the problem.
This is as you're just re-writing a for loop.
Using a for loop you can change the loop to a comprehension, and take the sum of it.
This allows you to get the code:

def simplex(n, dim):
    if dim == 1:
        return n
    dim -= 1
    return sum(simplex(i, dim) for i in range(1, n + 1))

However this can be simplified.
When dim is the bullet point the function is:

\$n\$
\$\Sigma_{i = 1}^{n} i\$
\$= \frac{n(n + 1)}{2}\$
\$\Sigma_{i = 1}^{n} (\Sigma_{j = 1}^{i} j)\$
\$= \frac{n(n + 1)(n + 2)}{6}\$
\$\Sigma_{i = 1}^{n} (\Sigma_{j = 1}^{i} (\Sigma_{k = 1}^{j} k)))\$
\$= \frac{n(n + 1)(n + 2)(n + 3)}{24}\$
\$\Sigma_{i = 1}^{n} (\Sigma_{j = 1}^{i} (\Sigma_{k = 1}^{j} (\Sigma_{l = 1}^{k} l))))\$
\$= \frac{n(n + 1)(n + 2)(n + 3)(n + 4)}{120}\$

Since we're getting a pattern, we know that the top part of the fraction is:

\$\Pi_{i = 0}^{dim - 1} n + i\$

And if we use oeis to find the denominator it says it's probably the factorial sequence.
And so it's likely:

\$\frac{\Pi_{i = 0}^{dim - 1} n + i}{dim!}\$

This is actually really easy to write in Python.
And so you can get a significant speed up.

from functools import reduce
from math import factorial
from operator import mul

def simplex(n, dim):
    return reduce(mul, (n + i for i in range(dim))) // factorial(dim)


This appears to be an implementation of something akin to the observer pattern. Your implementation is straightforward enough, but there are two things that jump out at me.

First, I'm surprised that this involves two top-level decorators? I think I would rather see a pattern similar to what property provides. Namely, rather than exposing both @Hook and @OnHook, make @Hook add an attribute to the function that can itself, as a decorator, hook other functions to the first (implementation left as an exercise):

@Hook
def pre_initiative(): pass

@pre_initiative.when_called   # or preferred name
def dummy_func_1(): print("pre-initiative!")

Second, I'm a little confused about your larger use case. Do hooks have a chance to change the inputs or outputs of the hooked function? Are you working on this project with other people who may be more used to some particular approach? (If so, it's easier for them to work with if it matches the approach they expect.) Are these phases easier to implement as functions called on an instance or a subclass?

class Player:
    def pre_initiative(self): pass
    def post_initiative(self): pass

def encounter(players):
    for player in players:
        player.pre_initiative()
    for player in players:
        player.post_initiative()


Setting enum flags by string (in any order)

Here is my take on your code

[Flags]
public enum SalaryFeatures
{
  None= 0,
  Children = 1,
  Graduate = 2,
  Disability = 4
}

class Program
{

  public static void Main()
  {
    string Employee = "10023 Mark Male 6.7 70 30 20 Children Graduate";
    SalaryFeatures f;
    f = GetFeaturesByString(Employee);
    // f.Dump(); //LinqPad only
  }

  public static SalaryFeatures GetFeaturesByString(string fields)
  {
    SalaryFeatures features = SalaryFeatures.None;

    if (fields.IndexOf("children", StringComparison.OrdinalIgnoreCase) >= 0) features |= SalaryFeatures.Children;
    if (fields.IndexOf("graduate", StringComparison.OrdinalIgnoreCase) >= 0) features |= SalaryFeatures.Graduate;
    if (fields.IndexOf("disability", StringComparison.OrdinalIgnoreCase) >= 0) features |= SalaryFeatures.Disability;

    return features;
  }
}

First of the definition of your Enumeration is not complete. You need to define a None value for it

  Use None as the name of the flag enumerated constant whose value is
  zero. You cannot use the None enumerated constant in a bitwise AND
  operation to test for a flag because the result is always zero.
  However, you can perform a logical, not a bitwise, comparison between
  the numeric value and the None enumerated constant to determine
  whether any bits in the numeric value are set.

See also the Guidelines when defining a Flags enum. I also change the naming of the enum to PascalCase (SalaryFeatures).

After that I have improved your method GetFeaturesByString to use bitwise OR to combine the values depending on the values that are found in your string. I also use the method IndexOf(string, StringComparison) to check if the search string exists in the source string, instead of using ToLower() and Contains().


Graph and minimum spanning tree in Python

There are no docstrings. How do I use this class? What arguments should I pass to the methods and what do they return?
There's no way to add a vertex with no edges to a graph.
The test code shows that it is quite laborious to initialize a graph. It would make sense for the constructor to take an iterable of edges.
The attribute g is not intended for use outside the class (callers should use the public methods). It is conventional to name internal attributes with names starting with one underscore.
The code in add could be simplified by making use of collections.defaultdict:

def __init__(self, edges=()):
    """Construct a graph containing the edges from the given iterable.
    An edge between vertices v1 and v2 with weight w should be
    specified as a tuple (v1, v2, w).

    """
    self._g = defaultdict(dict)
    for edge in edges:
        self.add(*edge)

def add(self, v1, v2, w):
    """Add an edge between vertices v1 and v2 with weight w.
    If an edge already exists between these vertices, set its
    weight to w.

    """
    self._g[v1][v2] = self._g[v2][v1] = w

The has_link method uses "link", but the rest of the code uses "edge". It would be better to be consistent.
The __getitem__ method uses "node", but the rest of the code uses "vertex". It would be better to be consistent.
Since add ensures that edges are stored in both directed, it's only necessary to test one direction:

def has_edge(self, v1, v2):
    """Return True if the graph has an edge between vertices v1 and v2."""
    return v2 in self._g[v1]

The edges method accumulates a list of edges. To avoid an edge appearing twice, the code checks each edge to see if it is already in the list. But lists do not have an efficient membership test, so the runtime is quadratic in the number of edges. It would be more efficient to make a set of edges:

def edges(self):
    """Return the edges in the graph as a set of tuples (v1, v2, w)."""
    edges = set()
    for v1, destinations in self._g.items():
        for v2, w in destinations.items():
            if (v2, v1, w) not in edges:
                edges.add((v1, v2, w))
    return edges

In the sorted_by_weight method, it would be better to name the keyword argument reverse, for consistency with Python's built-in sorted.
In spanning_tree, the parent and rank dictionaries can be initialized directly:

parent = {v: v for v in self._g}
rank = {v: 0 for v in self._g}

The parent data structure is known as a disjoint-set forest. An important optimization on this data structure is path compression: that is, when you search the parent data structure for the root of the tree containing a vertex, you update the parent data structure so that future searches run quickly:

def find_root(v):
    if parent[v] != v:
        parent[v] = find_root(parent[v])
    return parent[v]

In the union function, you always attach the tree for root2 to the tree for root1:

if rank[root1] > rank[root2]:
    parent[root2] = root1
else:
    parent[root2] = root1

It's more efficient to always attach the smaller tree to the bigger tree, so that the length of the searches in find_root doesn't increase:

if rank[root1] > rank[root2]:
    parent[root2] = root1
else:
    parent[root1] = root2

The __len__ and __getitem__ methods treat the graph as a collection of vertices, but __iter__ treats it as a collection of edges. This seems likely to lead to confusion. It would be better to be consistent and have all special methods treat the graph as a collection in the same way.


You can move urls and titles to helpers and articles search to separate method

class HomeController < ApplicationController
  # this methods can be used in view template
  helper_method :next_page_url, :page_title

  @@articles_per_page = 6
  @@first_page_articles_options = {:page=>'1', :per_page=>@@articles_per_page}
  @@second_page_url_options = {:controller =>:home, :action => :page, :page_id=>  2}

  def index
    @paged_articles = articles.search(@@first_page_articles_options)
    @tags = get_tags
  end

  def tags
    @paged_articles = load_articles
    @tags = get_tags

    render :index
  end
   def about
      @page_title = "About"
  end

  private

    def load_articles
      ...
    end

  ...

  # helpers

  def next_page_url
    if filter_by_tags?
      url_for(@@second_page_url_options)
    else
      @@second_page_url_options[:tag_name] = params[:tag_name]
      url_for(@@second_page_url_options)
    end
  end

  def page_title
    if filter_by_tags?
      "Recent articles"
    else
      "Search articles by tags"
    end
  end

  def filter_by_tags?
    params[:tag_name].present?
  end
end


Getting ready for Nullable Reference Types

There are some disadvantanges about this solution. You not only loose the argument-name inside the exception but if you are using ReSharper then you won't be able to quick-fix this in future.

Thus I think it's not necessary to create such helpers because as soon as the new feature is there, ReSharper will probably have nice quick-fix for that so it'll turn all if(foo == null) throw new ArgumentException(..) into the new syntax. I doubt ReSharper will be able to quick-fix this.

Besides if you properly decorate your code with the [NotNull] and [CanBeNull] attributes, you are half-way safe. Since I started using them, It's been ages that I last saw a NullReferenceExcepiton or ArgumentNullExcepiton.

I also find ReSharper's naming convention more appealing. This means

Some becomes NotNull and
Option becomes CanBeNull


Lowering speed on my hybride encryption function for large files

Multithreaded Approach

Since you are using WinForms you can use BackgroundWorker.  BackgroundWorker will automatically use threads from the ThreadPool, and importantly, they have a notification event for when the thread completes.

There are several ways this could be done, and also keep in mind that I only have moderate experience with multithreading in C#.

You will need to create several BackgroundWorkers.  I would start with 4 and adjust from there. We can also simplify reassembling the blocks by writing them to the output file as they complete.

Here is a high level overview for what you should do:

Put the workers in a list of available threads.
In the main thread, check if there is a free worker in the list.

If Yes, read the next block from the file, pass it and the block index to the worker and start it. Remove the worker from the list
If No, then sleep.

After the worker has completed, it will call the RunWorkerCompleted event, where it will return its result (which should be the encrypted block and the block index.
The event handler should write the encrypted block to the corresponding index in the output file, and then add the worker back to the list.
Repeat until all the blocks have been processed.

Some Notes

The RunWorkerCompleted event may run on the background thread (or you may get errors about it) and we don't want that.  First, any updates to the UI, like updating the progress after a block is written, have to happen on the main UI thread.  Secondly, we don't want multiple threads trying to write to the output file at the same time.  There is a simple trick to get the RunWorkCompleted event to run on the main UI thread.

private void bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //if we aren't on the main thread, recursively call on main thread
    if(this.InvokeRequired)
    Invoke( ( MethodInvoker ) delegate {
        bgworker_RunWorkerCompleted(sender, e);
        return;  // don't forget to return or this method will do it twice
    });

   //Write to file
   //Update Progress
   //Add worker back to list
}

The BackgroundWorker.RunWorkerAsync() and RunWorkerCompletedEventArgs only accept/return a single object and you need to pass two (the block index and the block itself).  You will need to either use a tuple/struct/class or something else to hold both objects when passing back and forth.

Finally, You may need special handling for the last block of the file.  Some encryption algorithms (zero) pad a short block to the expected length (1K in this case).  This means that your encrypted file may be slightly longer than your unencrypted file. If this is the case for your chosen algorithm, your allocated output file size may be slightly longer than the original input.  Depending on the file contents, this may or may not be an problem, however you should be aware of it as a potential issue.

Update: What I mean by Block Index

Let's say a file is 10K.  The first block has index 0 and is 1K in length.  The second block has index 1, the third index 2, etc.  The file has 10 blocks with indexes 0-9.

Now lets say that I queue things up and block index 4 finishes first.  In my output file I seek to position 1000*blockIndex, or 4000 and write the 1K bytes.  Then let's say that block 2 finishes.  I seek to position 2000 and write the 1K.  My output file now looks like [0|0|*|0|*|0|0|0|0|0] where '*' denotes valid data and '0' denotes empty/nothing written.

For performance purposes, I'd probably let the UI thread open the output file at the beginning and only close it after the last block is written.  You know the file is done when all of your workers are sitting in the list.  (Workers also have a property to check their status :IsBusy)

Links

Simple tutorial on BackgroundWorker
BackgroundWorker documentation


The concept of creating a new Calculator() with a specified operator and then calling calc.init() to actually perform the operation seems a bit strange. I'd probably have any initialisation built into the constructor, and then have a calc.calculate() method that takes the operation as a parameter.

I don't have time now for a detailed analysis of your code, but one thing I would probably do is make the different operation functions methods of an object:

var operations = {
    "addition" : function(x,y) { return setVal(x + y); },
    "subtract" : function(x,y) { return setVal(x - y); },
    "multiply" : function(x,y) { return setVal(x * y); },
    // etc
}

Because then you can eliminate the if/else structure that decides what function to call and just do this:

calculation = function() {
    if (op in operations)
        operations[op](val1, val2);
    else
        // invalid op requested, so show message, throw exception, whatever
}

If you add more operations in the future, say a toThePowerOf() operation, you'd add it to the operations object but wouldn't need to change the calculation() function.


Parsing NSDictionary from NSJSONSerialization

if ([results count] > 0)
{
    newPlayer = (Player *)[results objectAtIndex:0];
} else {
    //Add a new player
    newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:temporaryContext];
}

This chunk of code could be replaced with:

newPlayer = (Player *)([results firstObject] ?: [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:temporaryContext]);

if ([[playerObject objectForKey:@"title"] isKindOfClass:[NSNull class]])
{
    newPlayer.title = nil;
} else {
    newPlayer.title = [[playerObject objectForKey:@"title"] stringValue];
}

This chunk of code could also be slightly better.

NSString *newTitle = playerObject[@"title"];
newPlayer.title = [newTitle isEqual:[NSNull null]] ? nil : [newTitle stringValue];

The last comment that I'll make is a strong recommendation that you use constants for your keys rather than literal strings.  Defined constants will auto-complete for you, which is nice, but more importantly, it will eliminate misspellings entirely.

static NSString * const kKey_Player = @"Player";
static NSString * const kKey_Title = @"title";
// etc.

Then use it as such:

NSString *newTitle = playerObject[kKey_Title];

Under the covers, this actually doesn't change in the slightest what the code does.  Even when you use string literals, a memory location is still allocated for them.  The advantage here is that you eliminate programmer mistakes.


Per the comment, what you probably want is an abstract class MyAppPage:

abstract class MyAppPage : Page {
    protected Dictionary<NpInfoHelper, object> Informer;
    protected override void OnInit(EventArgs e)
    {
        if (Session.Keys.Count == 1)
        {
            Session.Abandon();
            Response.Redirect("~/Pages/Login?e=true", true);
        }
        else
        {
            Informer = (Dictionary<NpInfoHelper, object>)Session["Informer"];
        }
        base.OnInit(e);
    }
}

then your other pages would extend MyAppPage instead of Page.

Finally, you'll notice I took the liberty of changes Response.RedirectPermanent to Response.Redirect. Permanent redirections return the 301 response "Moved Permanently" and signify that the current page no longer exists at this position and has been moved elsewhere. Using it to redirect someone who hasn't logged in might confuse crawlers.


This script works but keeps timing out with longer inputs. How can I improve its speed? [Ruby]

So, you are generating every possible permutations of the array, which is a O(n!) operation. This is huge.

I think this can be done with an O(n²) algorithm. I would do :

create an array containing the pairs, ordered by the first value
create another one containing the pairs, ordered by the second value
create a third array containing, for each index of the first array, the index in the second array where we can find the corresponding value.
find every subset of this third array whose values are in ascending order.

The result is the length of the biggest subset.

Example

first array | second array | third array
------------+--------------+------------
15,176      | 102,6        | 7
39,47       | 123,37       | 3
44,168      | 72,43        | 6
65,97       | 39,47        | 4
72,43       | 65,97        | 2
90,163      | 90,163       | 5
102,6       | 44,168       | 0
123,37      | 15,176       | 1
191,189     | 191,189      | 8

The ascending subsets are :

7 8
3 6 8
3 4 5 8
6 8
4 5 8
2 5 8
5 8
0 1 8
1 8
8

The biggest subset is (3 4 5 8), and its size is 4.

Complexity

The sorts can be done with O(n log n)
The creation of the third array is O(n²)
To find the subset, I think we can do that with O(n²) (I'm not sure about that)

So, the whole thing should be O(n²).

The algorithm for finding the ascending subsets is not trivial. I'm sure it will be fun to implement !


One to one record mapping without any common column between two tables in SQL server

Even if your solution is (almost) correct, the actual problem is in a wrong formulation of the problem.

The main issue in your question is the assumption of a certain order of records within a table. In reality SQL Server cannot guarantee original order of records when you do a select statement without order by clause, even if you have a clustered index defined.

In order to properly map 2 tables you must have a criteria for matching records. You provided a solution that won't generate consistent results. Imagine that you need to add another student/subject (StudentId = 2, SubjectId = 1) and a mark for that. If you add one record to Student/Subject table and one record to Marks table your data will be screwed up since Marks record will be matched against 3rd record (StudentId = 1, SubjectId = 3).

In order to fix the issue you must add a field or fields that allow unique reference of records, that is you must add both StudentId and SubjectId to Marks table. Alternatively you can create a surrogate key in the Student/Subject table and use it as a reference in Marks table.

UPDATE.
The main difference between original question and example in Edit section is that records can be ordered by unique key (primary key) in latter case, while in original question order by StudentId didn't guarantee specific order and produced inconsistent results.

Your updated example is using mapping properly, according to (updated) requirements, and will produce consistent results as long as SportId and StudentId are unique in corresponding tables


The spacing on your parenthesis in your function declarations is odd and distracting.  Try not to fight what autocomplete will give you.  It should look like this:
func nameOfFunction(firstArgumentName: Int) -> Int

Notice the lack of spaces inside the parenthesis but the addition of the space between the argument name and its type?  This is the expect formatting style for Swift function declaration.

Memoization

func nthTriangularNumber( n:Int ) -> Int {
    var number = 0

    for iterator in 0...n {

        number += iterator

    }

    return number
}

We can immediately improve upon this approach.  We know that for any number n, the nth triangular number will be the n-1th triangular number + n, right?
So we can improve this approach by using some memoization.
Without changing the rules of this function (although, I think the name needs some work), we can use a local struct to hold an array of the previously calculated triangular numbers.
Since Swift doesn't have the same sort of static function variables as Objective-C and other languages have, we have to consult this Stack Overflow question to figure out how to achieve something similar.
So... we're going to want a nested struct that looks like this:
struct Memoizer {
    static var triangularNumbers: [Int] = []
}

Now we'll use this Memoizer.triangularNumbers array to memoize triangular numbers so nothing is ever calculated more than once.  Perhaps this makes sense as an extension to Int though?
extension Int {
    func triangularNumber() -> Int {
        struct Memoizer {
            static var triangularNumbers: [Int] = [0]
        }

        let lastIndex = Memoizer.triangularNumbers.count - 1
        for n in lastIndex...self {
            let next = Memoizer.triangularNumbers[n] + n
            Memoizer.triangularNumbers.append(next)
        }

        return Memoizer.triangularNumbers[self]
    }
}

So, if we try to find 500's triangular number, it still takes just as long as it would have taken using your approach (assuming we've not previously found any other triangular numbers) (and maybe slightly longer since we have to allocate memory for the array).  But once we've calculated the 500th triangular number, anything less than 500 is a simply array look up.  And calculating the 501st triangular number is a matter of grabbing the 500th and adding 501 to it.
That last point is the most important part here though.
In your current implementation, each iteration of your while loop takes progressively longer than the previous one.  Your countOfTriangularNumbers is also the count of addition operations you have to do per loop to calculate that particular triangular numbers.
Using the implementation I just suggested, your number of addition operations to calculate the triangular number stays at a constant one.
The difference between one addition operation and two addition operations may not be measurable.  But by the 500th or 1000th or more iteration of your loop, the difference between one addition operation and 500 addition operations starts to become noticeable.  (And this is minor addition to the time it takes... but when we do find the number, we have to then recalculate it inside your if branch).

There is still a lot to work on for this problem, but I think this answer sets you down a very good path.  Think about what this memoization is doing for us, and try to see where we can apply it in other places (especially as you work through Project Euler).


Graph Implementation in Java using adjacency list - v2

You should make your class final unless you're explicitly intending it to be extended.
adjList should be private. You don't want other classes in your package reaching into a MyGraph and messing with its adjacencies. It would also be reasonable to make it final. Map defines a clear method you can use.
In general, prefer using interfaces where possible. Within your code, the fact that adjList is a HashMap and not a TreeMap is irrelevant. So just refer to it as a Map.
Most of your comments are noise. If the purpose of a block of code isn't obvious, you can usually create a new method with a name that makes it obvious.
There's no charge for extra characters, and it's easier to read adjacencyLists than adjList.
Is it really necessary to throw an error if the user asks you to do something you've already done for them? If they need to know if the edge already existed, you can return a boolean. This is how the Collections API works, and I think it's a good model.
You can't safely return a Set from your adjList, because if a user mucks with that, they're changing the internals of your graph. Use a new Set instance.
For isNeighbor and removeEdge, do those need to be exceptions?
Remember to use generics consistently.
There's no need to call contains in removeVertex. Sets don't break if you try to remove a non-existent element.
In removeVertex, it's a lot easier to just loop over the values in the map, rather than the keys.

If I were to refactor your code, a first pass might look something like:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public final class MyGraph {

    // add vertex name as key, and neighbors as values in set
    private final Map<String, Set<String>> adjacencyLists = new HashMap<>();

    public void addVertex(final String name) {
        if (this.adjacencyLists.containsKey(name)) {
            throw new IllegalArgumentException();
        }
        this.adjacencyLists.put(name, new HashSet<>());
    }

    public boolean addEdge(final String source, final String destination) {
        if (!this.adjacencyLists.containsKey(source) || !this.adjacencyLists.containsKey(destination)) {
            throw new IllegalArgumentException();
        }

        return this.adjacencyLists.get(source).add(destination);
    }

    public Set<String> getNeighbors(final String name) {
        return new HashSet<>(this.adjacencyLists.get(name));
    }

    /**
     * @return true if there is an edge from source -> destination
     */
    public boolean isNeighbor(final String source, final String destination) {
        if (!this.adjacencyLists.containsKey(source) || !this.adjacencyLists.containsKey(destination)) {
            throw new IllegalArgumentException();
        }
        return this.adjacencyLists.get(source).contains(destination);
    }

    public boolean removeEdge(final String source, final String destination) {
        if (!this.adjacencyLists.containsKey(source)) {
            return false;
        }

        return this.adjacencyLists.get(source).remove(destination);
    }

    public boolean removeVertex(final String name) {
        if (!this.adjacencyLists.containsKey(name)) {
            return false;
        }

        this.adjacencyLists.remove(name);

        for (final Set<String> adjacencies : this.adjacencyLists.values()) {
            adjacencies.remove(name);
        }

        return true;
    }

    /**
     * removes all vertexes/edges from graph
     */
    public void clear() {
        this.adjacencyLists.clear();
    }

    /**
     * @return the number of vertexes
     */
    public int size() {
        return this.adjacencyLists.size();
    }

    public boolean isEmpty() {
        return this.adjacencyLists.isEmpty();
    }
}


Cucumber scenario to test REST interface to scuba diving logbooks

Here is how I would update what has been given, but below there are some points for further improvement.

Feature: Get list of Logbooks
    As a client
    I want to get a list of a certain users logbooks
    So that i can present the logbooks name and the number of scuba dives to the client.

Background:
    Given the user "tom" has the email "tom@tom.com"

Scenario: Get a list of logbooks
    Given "tom" owns the logbooks:
      | pacific  |
      | atlantic |
      | gulf     |
    When the client requests for a list of logbooks owned by "tom"
    Then the client gets a list with 3 logbooks
    And the requested logbooks should have the users name and email
    And the requested logbooks should have the names:
      | pacific  |
      | atlantic |
      | gulf     |

Scenario: The user has no logbooks
    Given "tom" owns no logbooks
    When the client requests for a list of logbooks owned by "tom"
    Then the client should see the message "tom has no logbooks"

WAYS TO IMPROVE

BDD is all about conversations.

Cucumber being a BDD tool means that it helps with breaking down the conversational barriers between the business and the development team. You should be agreeing on the language that is used with both the dev team and business before the feature file has been completed.

Is the language stated in the scenarios the same language that the business and the dev team have agreed to use? If not, update the language. (And the requested log books should have the users name and email, for instance)

Are there any extra steps that the business wants to know about? If so, add them in.

Are there any steps that aren't needed? If so, remove them.


Using Python to remove blank lines and comments in Assembly code

I have a few recommendations for your code.

First I noticed that you do not close neither the input nor the output file. This can lead to issues if you or someone else wants to access the files after your script was run. Adding a simple ''finput.close()'' and analogous for the foutput would basically "fix" the issue. However it is considered best practice to use a context manager for accessing resources like files. A context manager is able to open the file for you and close it if you leave the context no matter if you leave it by intent or because of an exception. Using a context manager could look like the following:

with open(input_path) as finput:
    for line in finput:
        print(line)

Another point is how you strip off line endings and what you store in the variables. You say you want to get rid of all comments but nonetheless you are storing them in a variable as well as I would use the strip command before the check if you need to add a new line char. The strip will also remove new line chars and therefore convert empty lines to empty strings one can easily test for. All in all I would write it the following way:

new_line = line.split("//")[0].replace(" ","").rstrip()
if new_line:
    foutput.write(new_line + "\n")

I hope that helps even though I did not add links to the mentioned methods and best practices.