The overall design seems a bit complicated to me. Setters and getters are often more of an hindrance than a real asset, and the benefits of having a simple struct should not be under-estimated. In particular, it reminds you that you don't have to encapsulate everything, and that defining functions at the point of use is often the most convenient way to proceed:

struct Point { float x, y; };

// ...

// here I need to compare points by y and then x
auto best = std::max_element(v.begin(), v.end(), [](auto point_a, auto point_b) {
    return std::tie(point_a.y, point_a.x) < std::tie(point_b.y, point_b.x);
    //      -> tie gives you the lexicographic comparison for free
});

// and there by angle with etc.
auto widest = std::max_element(v.begin(), v.end(), [origin](auto point_a, auto point_b) {
    // ...
});

In a nutshell, why having a namespace and custom classes where you can simply use a lambda?


Timed requests and parsing JSON in Python

While this is a good start, there are several things that should be noted.

  r = requests.get("http://citibikenyc.com/stations/json")

This is code snippet is network-based, and so errors may occur. You will want to handle these errors in some way, with a try-except block like so:

try:
    r = requests.get("http://citibikenyc.com/stations/json")
except ConnectionError:
    pass # handle the error
except TimeoutError:
    pass # handle the error

and so on, as per the requests documentation.

Additionally, do not sleep and do in the same function. These are two responsibilities and so should be separated as per the Single Responsibility Principle.

I would suggest adding the sleep(62) to the while True: block.

Also, there is no point to this:

  exit()

as it will never be executed. This leads me to my next point, you should probably do the file writing in Python instead of the command line, so you can open the file, append some data, and then close it to make sure it is safe between network errors and power outages.


The code is pretty short, so there's not much to comment on.

Magic numbers

int literal = (100 * pair.getA()) + (10 * pair.getB()) + k

I have no idea what that means. What is 100? What is 10? Why do you sum them up? I suggest creating a method int getLiteralId(int firstDigit, int secondDigit, int thirdDigit) and add a comment that explains what's actually going on.

clause.add(-1 * pair.getA());
clause.add(-1 * pair.getB());

Why are multiplying them by -1? At least create a method with an appropriate name (something like int negateLiteral(int literalId)).

Variable names

k and pairs isn't very descriptive. I suggest something like digit and digitPairs.

Overall design

Representing a boolean expression as a list of integers leads to confusion. I'd redesign it in the following way:

A BooleanExpression abstract base class.
A Variable subclass for representing variables.
A Negation subclass for representing negations.
A Conjunction subclass for representing  conjunctions.
A Disjunction subclass for representing disjunctions.
The signatures will be
BooleanExpression exactlyOneOf(List<BooleanExpression> expressions) and
BooleanExpression exacltyOneDigitForEachEntry()

It'll make the code much more readable. For instance,

Conjunction conjunction = new Conjunction();
...
conjunction.add(new Negation(expression));

and

Disjunction disjunction = new Disjunction();
disjunction.add(new Variable(firstDigit));
disjunction.add(new Variable(secondDigit));
disjunction.add(new Variable(thirdDigit));
conjunction.add(disjunction);

looks much better than some "magic" multiplication and addition of seemingly unrelated numbers, doesn't it?

It's safer in a sense that an arbitrary integer can't accidentally turn into a literal/expression.

It also makes more sense because a boolean expression is a boolean expression. It's not a list of integers (it might be implemented as such, but it's an implementation detail).

What if you use a third-party solver and it needs a list of integers in a specific format?  It doesn't really matter. You can still use the design shown above. Just add a toList method to the BooleanExpression and implement it in concrete subclasses according to the rules of the solver. Call it only once before passing your expression to the solver.


X86 Feature detection in preparation for Long Mode

Documentation for this flag reads:

  If a software procedure can set and clear this flag, the processor executing the procedure supports the CPUID instruction

This clearly means that the flag does not have a defined value. It could be OFF or ON at any time!

Where your comment says that you "Toggle bit 21 (ID)", the instruction actually sets the bit. I don't think that would be too useful since you don't use the pre-existing value of this bit.
When you exclusive or XOR the registers AL and DL, you should prudently mask away the 7 remaining bits.

All the forementioned boils down to the fact that the final test (notice the typo in the comment; should be bit 5)

xor     al, dl          ; Bit 4 of AL & DL is (ID)
jz      TstExt

will always check out fine.

Although your method to get a DS:BX pointer is quite ingenious, I prefer using [bp-2] as you can see in below code.

    mov     bp, sp
    pushfd
    mov     al, [bp-2]        ;Pre-existing value
    xor     byte [bp-2], ID   ;Toggle bit 21
    popfd
    pushfd
    mov     ah, [bp-2]        ;Hopefully changed value
    popfd
    and     ax, (ID<<8)+ID    ;Mask off unimportant bits
    cmp     al, ah
    jne     TstExt

FncErr:

I omitted preserving the ID bit as per definition this should not be necessary.

FncErr: mov di, (22*80+39)*2 ; Point to center position of 21th row in video

The address points to the 23rd row.

cmp     eax, edx   <<< EDX=0x80000000
jb      FncErr

Are you sure the service can't report EAX=0x80000000 ?
Perhaps it could be better to bail out with:

jbe     FncErr

Now you're certain that leaf 0x80000001 exists.

Reaching leaf 0x80000001 through mov al, 1 will continue to work for as long as the manufacturer doesn't create some high numbered leafs (0x80000100 and up). You have to ask yourself how future-proof that you want your program to be!


String data manipulated given CSV variables

This code is a decent start, as it uses ES6 features like arrow functions. However it could take advantage of many Javascript features - e.g. IsExpenseItemAcceptable could be reduced to a single line using Array.includes(). Additionally, the index variables can be eliminated using the ES6 feature Destructuring assignment - specifically array destructuring.
Instead of lines like

var expenseItemized = expense.split(',')

if ((categoryIndex < expenseItemized.length) && IsExpenseItemAcceptable(AcceptableCategories, expenseItemized[categoryIndex])){

Destructuring assignment can greatly simplify this to something like:
const [vendor, date, item, price, category] = expense.split(',');
if (category && IsExpenseItemAcceptable(AcceptableCategories, category)){

Not only is that condition shorter, it doesn't require the use of the index and is more readable (and a typo on the word "vendor" was fixed).
In the example above const was used instead of var. It is recommended that const be the default keyword for initializing variables. If assignment is required, then use let.
The function GetAcceptableCategories could be simplified using Array.reduce(), similar to Array.forEach().
The data structure could be changed from an array to a plain object - i.e. {} to provide a mapping of vendor and date combinations to prices. This would allow the elimination of the functions updatePrice and IsVenderDateIncluded because the loop could be simplified to:
if (category && IsExpenseItemAcceptable(AcceptableCategories, category)){
    const vendorDate = [date, ": ", vendor, " - $"].join('')
    if (vendorDate in AcceptableExpenseTotals) {
        AcceptableExpenseTotals[vendorDate] += parseFloat(price);
    }
    else{
        AcceptableExpenseTotals[vendorDate] = parseFloat(price);
    }
}

This would require reformatting the output - e.g.
for (const [vendorDate, price] of Object.entries(AcceptableExpenses)) {
    console.log(vendorDate, price);
}


You play with up to 199 dice per player. So most of the time, the attacker will attack with 3 dice and the defender will attack with 2 dice. As long as that's the case, you could simply pick one of the three possible outcomes (with precalculated probabilities) and apply it. Outline:
def _attack_(n_atk,n_def):
    while n_atk >= 3 and n_def >= 2:
        # pick random outcome and update the dice numbers
    while n_atk >0 and n_def>0:
        # same as before
    return [n_atk,n_def]

You could even precompute the result distributions for all \$199^2\$ possible inputs and randomly pick the result according to the given input's distribution. Outline:
def _attack_(n_atk,n_def):
    return random.choices(results[n_atk, n_def], cum_weights=cum_weights[n_atk, n_def])


Handling SIGINT signal for a server program

It depends on what you want the server to do when an interrupt is sent.

If you really want the program to stop when it is sent an interrupt, even though it is a service (Windows) or daemon (Unix), then what you did works.  If, however, the program was run with settings to ignore interrupts, your code overrides that.  The canonical sequence for setting a signal handler (for signal number signum) is:

if (signal(signum, SIG_IGN) != SIG_IGN)
    signal(signum, sighandler);

If the program was ignoring the signal, it continues to do so.  Otherwise, it sets its own handler to handle the signal.

On Unix, you usually use SIGTERM to do a controlled stop of a program, and for daemons, you typically use SIGHUP to indicate that the daemon should revisit its configuration.

Also, in the POSIX world, it is generally recommended to use sigaction() rather than signal() because it gives different and better guarantees about what happens.

If your program needed to continue after receiving the signal, you would have to reset the signal handler in the signal handler - and there's a small window of vulnerability which means that if two signals are sent fast enough, the program stops despite your handler.  Using sigaction() avoids this timing vulnerability.


Is this higher order function any use at all without relying on a side-effect?

The answer to this question is obviously no, since the function returns always nil.

  The general question I'm seeking to explore here is the purity or non-purity of higher order functions in practical use cases (and hence, how to use them well).

I'm not sure to understand what you are looking for, but if you want an example of recursive higher order function on binary trees that returns something (without performing side effects), consider the following one, in which the function gets another parameter that “combine” the results of the visit (assuming that an empty tree is represented with nil and that the function should return nil when an empty tree is passed to it):

(defun inorder-traverse (combine fn bin-tree)
  "in order traversal of a binary tree"
  (when bin-tree
    (funcall combine
             (inorder-traverse combine fn (node-l bin-tree))
             (funcall fn (node-elt bin-tree))
             (inorder-traverse combine fn (node-r bin-tree)))))

for instance:

(defun flatten (bin-tree)
  (inorder-traverse (lambda (x y z) (append x (list y) z))
                    #'identity
                    bin-tree))

returns the list of the leaves of a binary tree in order from left to right; if the tree is a BST, the list is sorted;

(defun reverse-flatten (bin-tree)
  (inorder-traverse (lambda (x y z) (append z (list y) x))
                    #'identity
                    bin-tree))

like the previous one, only in reverse order;

(defun map-tree (fn bin-tree)
  (inorder-traverse (lambda (left el right) (mk-tree el left right))
                    fn
                    bin-tree))

returns a new tree, with the same structure of the input one, and with the elements transformed by the function fn;

(defun my-copy-tree (bin-tree)
  (inorder-traverse (lambda (left el right) (mk-tree el left right))
                     #'identity
                     bin-tree))

makes a copy of a binary tree;

(defun reverse-tree (bin-tree)
  (inorder-traverse (lambda (left el right) (mk-tree el right left))
                    #'identity
                    bin-tree))

a symmetrical copy of a binary tree;

etc.


Some points in addition to what Roland already said:

You are correct that the readLine() returns an optional and you need
to ensure that it is not nil. However, nil is only returned on an
end-of-file condition, which means that it makes no sense to call
readLine() again. You can only terminate the program in that
situation. That is a typical use-case for guard:

func readInteger() -> Int {
    while true {
        guard let line = readLine() else {
            fatalError("Unexpected end-of-file")
        }
        if let n = Int(line) {
            return n
        }
        print("Please enter an integer")
    }
}

Now let's have a look at

var signArray2 = [Int]()
for i in 0...signArray.count-1 {
    signArray2.append (signArray[i])
}

First, this will crash if signArray is empty. Better use a half-open
range instead:

for i in 0..<signArray.count { ... }

or iterate over the indices

for i in signArray.indices {
    signArray2.append (signArray[i])
}

or just iterate over the elements:

for e in signArray {
    signArray2.append(e)
}

But actually, you are just copying the array:

var signArray2  = signArray

Determination of the divisors should be done in a separate function.
Your code

divArray = []
for i in 1...input {
    if input % i == 0 {
        divArray.append (i)
    }
}

can be simplified to

divArray = (1...input).filter { input % $0 == 0 }

There are various ways to make this faster. For example the observation
that with each divisor \$ i \$ of a number \$ n \$, \$ n/i \$ is another
divisor (see for example Find all divisors of a natural number).
That allows to reduce the number of loop iterations to the square-root of the
given number, and could look like this:

func divisors(n: Int) -> [Int] {
    var divs = [Int]()
    for i in 1...Int(sqrt(Double(n))) {
        if n % i == 0 {
            divs.append(i)
            if n/i != i {
                divs.append(n/i)
            }
        }
    }
    return divs // or divs.sorted(), if necessary
}

Your code

signArray = []
for j in 1...divArray.count {//
    signArray.append(0)
}

creates an array with the same size as divArray, but filled with
zeros. That can be simplified to

signArray = Array(repeating: 0, count: divArray.count)

There is no need to use string interpolation when printing an integer
(or any single value),

 print ("\(input)")

can be simplified to

 print(input)

Why is your code slow?

There is a logical error in

 let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1

because the number of possible combinations of divisors is
just \$ 2 ^ {\text{number of divisors}} \$, which can be computed as

 let x = 1 << divArray.count

With that change, your program computes all practical numbers
up to 200 in 0.2 seconds, and up to 1,000 in 25 seconds
(on a MacBook, compiled in Release mode, with optimization).

A faster algorithm

In order to determine if \$ n \$ is a practical number,
you test all numbers \$ 1 \le i \le n \$ if they are a sum
of distinct divisors of \$ n \$, and for each \$ i \$ that is done by building all
possible sums of divisors, until \$ i \$ is found.

It is more efficient to work the other way around. From the list of
divisors of  \$ n \$, build a list of all sums of distinct divisors.
This can be done iteratively: Starting with  \$ 0 \$, the first, second, ...
divisor is added to the numbers obtained previously.
Then check if all numbers from \$ 1 ... n-1 \$ are in that list.

The following implementation uses a boolean array to mark all numbers
which are confirmed as sums of divisors. In addition, it uses that
powers of two are always practical numbers (using the method from
Determining if an integer is a power of 2).

func divisors(_ n: Int) -> [Int] {
    var divs = [Int]()
    for i in 1...Int(sqrt(Double(n))) {
        if n % i == 0 {
            divs.append(i)
            if n/i != i {
                divs.append(n/i)
            }
        }
    }
    return divs.sorted()
}

func isPractical(n: Int) -> Bool {
    // 1 and 2 are practical numbers:
    if n == 1 || n == 2 {
        return true
    }
    // Every other practical number must be divisible by 4 or 6:
    if n % 4 != 0 && n % 6 != 0 {
        return false
    }
    // Every power of 2 is a practical number:
    if n & (n-1) == 0 {
        return true
    }

    var isSumOfDivisors = Array(repeating: false, count: n)
    isSumOfDivisors[0] = true
    var last = 0 // Index of last `true` element.

    // For all divisors d of n (except n):
    for d in divisors(n).dropLast() {
        // For all i which are a sum of smaller divisors (in reverse order, so that
        // we can simply update the array):
        for i in stride(from: min(last, n-1-d), through: 0, by: -1) where isSumOfDivisors[i] {
            // Mark i + d:
            isSumOfDivisors[i + d] = true
            if i + d > last {
                last = i + d
            }
        }
    }

    // n is "practical" if isSumOfDivisors[i] == true for all i = 0...n-1:
    return !isSumOfDivisors.contains(false)
}

Test code:

let startDate = Date()
let practicalNumbers = (1...10_000).filter(isPractical)
let endDate = Date()
print(endDate.timeIntervalSince(startDate))

print(practicalNumbers)

On my MacBook, this computes the practical numbers up to 1,000 in 0.003 seconds, and up to 10,000 in 0.1 seconds.


General review tips:

It'd be better to document your code. In particular functions like

union :: ([Int], Int) -> ([Int], Int) -> ([Int], Int)

need documentation - it's not clear which Int has what purpose at all without examining the source.
Some of your functions are polymorphic (sndhalf), others not. Why? I'd suggest to have all types consistent. Either just sort Ints, or make the types as generic as possible, for example

union :: (Ord a) => ([a], Int) -> ([a], Int) -> ([a], Int)

Notice how this generality also makes the types easier to understand.
I'd suggest to wrap list + its inversion count into a newtype such as:

newtype List a = List [a] Int

This makes the code better structured, and also allows you to use smart
constructors, if you decide
so.
Investigate Haskell's
sort
for inspiration.

Now specific to performance:
- For each pass you traverse the list several times,
which can impact the performance considerably. In particular: take and
length in fsthalf, the same in sndhalf. Also length in mergeSort. This
makes it 5 traversals before the merging pass. I'd try to reduce this number.

Matching on length is wasteful, if you need just to distinguish if it's 0 or 1, you traverse the whole list needlessly:

mergeSort (s, c) | length s `elem` [0, 1]  = (s, c)

Instead:

mergeSort ([], _) = ([], 0)
mergeSort (xs@[_], _) = (xs, 1)
...

Make sure you're compiling with -O.

I hope this helps!


Well, first of all there is a bug in the code. You are getting the index of a number by looking for it in the list, but if the number occured earlier in the list you will get the wrong index. You should use the index in the loop instead of using a foreach.

You are using the Count() extension method to get the number of items in the list, but you should use the Count property instead.

You are casting all enum values to integers, but you can just use the enum values directly.

You are casting a lot of values to double, but they are already double values.

You are using the value of answer in the code where you have determined that it's always zero.

You are comparing the answer value to zero to determine if it's the first iteration, but that could occur later in the loop too.

Instead of handling the first iteration differently, you can just put the first number in the answer variable and start the loop from 1.

The code suddenly got a lot simpler. :)

private double Calculate() {
  double answer = numbers[0];
  for (int index = 1; index < numbers.Count; index++) {
    switch (operators[index - 1]) {
      case Operator.Plus:
        answer += numbers[index];
        break;
      case Operator.Minus:
        answer -= numbers[index];
        break;
      case Operator.Divide:
        answer /= numbers[index];
        break;
      case Operator.Multiply:
        answer *= numbers[index];
        break;
    }
  }
  return answer;
}


Any ideas/opinions about the code I written?

A couple of points on readability:

your code does too much. It reads from the database, it prints to a file, it prints to a GUI, and it formats strings. I would create separate methods for each of these activities (or at least for the formatting and the printing to GUI).
240 characters are definitely too long for one line. I would try for 80 chars, 120 max.
your directory location string is duplicated. Define it in a static field and then use new PrintWriter(location + "\\PasswordList.txt", "UTF-8");
why are there so many backslashes in your path? I'm not that familiar with Java + Windows, but this seems unnecessary.
just using a bunch of tabs for alignment is quite messy (the code is messy, and the result will be messy as well). Use either CSV (the code will be cleaner, the output really messy, but at least it will be on purpose), or use some code for proper alignment.
you have way too many println. Just use \n.
your indentation is off, which makes it harder to read.
try to reduce the length of your try blocks. It's really hard to see what exception might be thrown by what operation if you just catch them all at the very end. You could also use try-with-resources.
Please COPY the FILE ADDRESS above and DELETE the 'PasswordList.txt' file: people are not going to do that. If this is important for security (and it kind of seems like it would be), you should find a different way to handle this.
a lot of your variables seem to be defined in a large scope, even though it isn't necessary. Eg entryX (which aren't needed at all, just use the value directly), pstmt, res, etc.


Return the state of collection based on individual object states

You can also use bitwise flags for that:

[Flags]
internal enum State
{
    None = 0,
    Error = 1,
    Warning = 2,
    Okay = 4,

    OkayAndWarning = Okay | Warning,
}

internal State GetCollectionState(IList<MyClass> objectList)
{
    return objectList.Select(o => o.State)
                     .Aggregate((result, next) => result |= next);
}

You can then check the aggregated state using HasFlag method or equality operator:

var state = GetCollectionState(...);
var error = state.HasFlag(State.Error);
var allWarnings = state == State.Warning;
var allOkay = state == State.Okay;
var okayAndWarnings = state == State.OkayAndWarning;
//etc.

On the plus side this approach is easy to implement and State enum is easy to extend when needed. Combining flags is a trivial process of applying | (bitwise OR) operator.

On the minus side you give up some of the type safety. With this approach any flag combination is a valid state, (including no flags at all). Also there is no longer a distinction between individual state and collection state (both use State enum), compiler will not warn you if you accidentally mix them. So in general, you'll have to be more careful, when checking states.


Pattern that adds a different value to the same attribute for many classes

You can minimize your SASS code using @each and nesting for :hover

.parent-div a {
  border-bottom: 10px solid;

  @each $color in blue, red, green, yellow, pink, purple { // Iterate through colors
    .#{$color} & {
      border-color: $color;

      &:hover { // Nested inside
        border-color: darken($color, 10%);
      }
    }
  }
}

which compiles to the following output

Codepen Demo

.parent-div a {
  border-bottom: 10px solid;
}
.blue .parent-div a {
  border-color: blue;
}
.blue .parent-div a:hover {
  border-color: #0000cc;
}
.red .parent-div a {
  border-color: red;
}
.red .parent-div a:hover {
  border-color: #cc0000;
}
.green .parent-div a {
  border-color: green;
}
.green .parent-div a:hover {
  border-color: #004d00;
}
.yellow .parent-div a {
  border-color: yellow;
}
.yellow .parent-div a:hover {
  border-color: #cccc00;
}
.pink .parent-div a {
  border-color: pink;
}
.pink .parent-div a:hover {
  border-color: #ff8da1;
}
.purple .parent-div a {
  border-color: purple;
}
.purple .parent-div a:hover {
  border-color: #4d004d;
}

  Test

    Test

    Test

    Test

    Test

    Test

    Test

But the above code seems to carry little logic. I think you were looking to nest the color classes after parent element like this:

.parent-div a {
  border-bottom: 10px solid;

  @each $color in blue, red, green, yellow, pink, purple { // Iterate through colors
     &.#{$color} {
      border-color: $color;

      &:hover { // Nested inside
        border-color: darken($color, 10%);
      }
    }
  }
}

which would be logically correct and with better HTML and CSS syntax:

Codepen Demo

.parent-div a {
  border-bottom: 10px solid;
}
.parent-div a.blue {
  border-color: blue;
}
.parent-div a.blue:hover {
  border-color: #0000cc;
}
.parent-div a.red {
  border-color: red;
}
.parent-div a.red:hover {
  border-color: #cc0000;
}
.parent-div a.green {
  border-color: green;
}
.parent-div a.green:hover {
  border-color: #004d00;
}
.parent-div a.yellow {
  border-color: yellow;
}
.parent-div a.yellow:hover {
  border-color: #cccc00;
}
.parent-div a.pink {
  border-color: pink;
}
.parent-div a.pink:hover {
  border-color: #ff8da1;
}
.parent-div a.purple {
  border-color: purple;
}
.parent-div a.purple:hover {
  border-color: #4d004d;
}

  Test

  Test

  Test

  Test

  Test

  Test

  Test

  Test


If all your business classes (e.g., User) could inherit from a common class or interface that has Modified and ModifiedBy properties, you could make your Repository a generic Repository<T>. Class-specific methods like GetByEmail would be replaced with generalized methods that take Expressions. Would that address your concern about "creating the repository instances like that", while keeping the business-level concerns (e.g., the fact that you're retrieving by email and not something else) away from your data access code?

Here's an untested and even uncompiled example of what I'm talking about.

public interface IBusinessEntity
{
    User ModifiedBy { get; set; }
    DateTime Modified { get; set; }
}

public class Repository<T> where T : IBusinessEntity
{
    private readonly IWorkUnit workUnit;
    public Repository(IWorkUnit workUnit)
    {
        this.workUnit = workUnit;
    }
    public virtual T Get(Expression<Func<T,bool>> expression)
    {
        return workUnit.Query<T>().FirstOrDefault(expression);
    }
    public virtual T Update(T objToUpdate, User updater)
    {
        objToUpdater.ModifiedBy = updater;
        objToUpdate.Modified = DateTimeOffset.Now;
        return workUnit.Update(objToUpdate);
    }
}

As for your naming conventions, they make sense to me.

Just one more idea: Unless your application will always be used in just one timezone, and hosted in the same timezone, you might consider storing your Modified property as UTC.


This is pretty good. I only have a few small nitpicks

Return directly

You do this a few times:

 if ship['passengers'] != "unknown" and int(ship['passengers']) >= num:
    return True
return False

The above can be rewritten as:

return ship['passengers'] != "unknown" and int(ship['passengers']) >= num

Superfluous int call

int(20), here the int call does nothing, 20 is already an integer.
You can get more out of the request module.

Python's requests lib is very powerful and has a lot of features you can use.

It supports adding params for instance, so instead of:

#specifies api parameters
url = endpoint + urllib.parse.urlencode({"format": type, "page": page_num})
#gets info
json_data = requests.get(url).json()

You could do:

json_data = requests.get(endpoint, params={"format": "json", "page": page_num}).json()

Remove unused imports

sys module is not used, I suggest removing it.


You could change the innermost loop to foreach-style to make it slightly more readable:

for (int coin : coins) {
    if (i >= coin && i - coin >= 0 && calculationsCache[i - coin] + 1 < calculationsCache[i]) {
        calculationsCache[i] = calculationsCache[i - coin] + 1;
    }
}

Considering you do:

for (int i = 0; i <= sum; i++) {
    calculationsCache[i] = Integer.MAX_VALUE;
}
calculationsCache[0] = 0;

You could start the count in the loop from 1, since you're overwriting the first element right after anyway.

If coins[] doesn't contain a coin with value 1, then your function will return incorrect result:

// actual: -2147483646 (Integer.MAX_VALUE)
Assert.assertEquals(2, findMinCoins(new int[]{2, 5}, 7));

As you yourself found, the cause of this was the integer overflow in calculationsCache[i] = Integer.MAX_VALUE;, and you correctly fixed it by changing to calculationsCache[i] = Integer.MAX_VALUE - 1;.

For reference, an alternative implementation with unit tests:

private int findMinCoins(int[] coins, int sum, int index, int count) {
    if (sum == 0) {
        return count;
    }
    if (index == coins.length) {
        return 0;
    }
    if (sum < 0) {
        return 0;
    }
    int countUsingIndex = findMinCoins(coins, sum - coins[index], index, count + 1);
    int countWithoutUsingIndex = findMinCoins(coins, sum, index + 1, count);
    if (countUsingIndex == 0) {
        return countWithoutUsingIndex;
    }
    if (countWithoutUsingIndex == 0) {
        return countUsingIndex;
    }
    return Math.min(countUsingIndex, countWithoutUsingIndex);
}

private int findMinCoins(int[] coins, int sum) {
    return findMinCoins(coins, sum, 0, 0);
}

@Test
public void testExample() {
    Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 10));
    Assert.assertEquals(3, findMinCoins(new int[]{1, 2, 5}, 11));
    Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 4));
    Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 7));
    Assert.assertEquals(3, findMinCoins(new int[]{1, 2, 5}, 8));
    Assert.assertEquals(3, findMinCoins(new int[]{1, 2, 5}, 9));
    Assert.assertEquals(3, findMinCoins(new int[]{1, 5, 2}, 9));
    Assert.assertEquals(3, findMinCoins(new int[]{5, 1, 2}, 9));
    Assert.assertEquals(3, findMinCoins(new int[]{5, 2, 1}, 9));
    Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 3));
    Assert.assertEquals(2, findMinCoins(new int[]{2, 5}, 7));
    Assert.assertEquals(3, findMinCoins(new int[]{5, 7}, 15));
}


Searching through a contact list for given criteria

If you are limited to use only Arrays, you can create a interface like this

public static interface Checker {
    public boolean check(Person p, String searchString);
}

Create a Checker for every type of comparison you want.

And compare with the Checker

for (int x = 0; x < numberOfContacts; x++) {
    if (checker.check(contacts[x], searchString)) {
        results[found] = x;
        found++;
    }
}

You can see a working example here (with your classes and methos): http://ideone.com/2C6kei

Note:
With this method is easy to expand the search criteria (as you see in the example, with a anywhere Checker).


Good Vs. Evil - Battle For Middle Earth - CodeWars

I see at least two things about your code that could be improved.

  let goodArmyPoints = [];
  //multiply goodWorth by type:
  for (let i = 0; i < goodWorth.length; i++) {
    goodArmyPoints.push(good[i] * goodWorth[i]);
  }

  goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

Here you allocate a whole array to store the results of multiplications, and then reduce over it. This extra array is wasteful. It would be much clearer and cleaner (and faster) to write simply

  let goodArmyPoints = 0;
  for (let i = 0; i < goodWorth.length; ++i) {
    goodArmyPoints += good[i] * goodWorth[i];
  }

Another confusing thing about your original code is that in the line

  goodArmyPoints = goodArmyPoints.reduce(...);

you are assigning over goodArmyPoints. And not just assigning over its value, but actually changing its type — from "array of numbers" to "just a single number."

Since a variable's name usually reflects what's stored in it, and what's stored in it is usually a function of its type, it follows that variables of different types rarely end up with the same name. For example, if I had two variables, one that stored an array of point-values and one that stored a single point-value, I would probably name them goodScores and goodScore, or goodPartialScores and goodTotal, or something like that. But I definitely would not give them the same exact name!

By giving each variable a unique name, and never changing the type of an existing variable, we increase the understandability of the code. Because now, when the reader asks, "What is the type of variable goodArmyPoints?", we can actually give an answer! In your original code, if the reader asks "What is the type of variable goodArmyPoints?", all we can do is hedge: "Well, at this point in the code it's an array, but when we use it two lines later, it's a number..." That's a more complicated and confusing answer, which is just another way of saying that your original code is more complicated and confusing than the simplified code above.


You should be using the clause group by

SELECT   h.id, h.name, im.id, im.name  --  What you want to select
FROM     house h,image im              --  Tables in join
WHERE    h.id = im.house_id            --  The join (equivalent to inner join)

GROUP BY h.id                          --  This compresses all entries with the
                                       --  same h.id into a single row
HAVING   min(im.id)                    --  This is how we select across a group
                                       --  (thus compressing the image table per house)

LIMIT    20;                           --  Selecting the first n values is very
                                       --  DB specific on mysql use the limit clause
                                       --  But I see in your DB it is `top 20`

Note:

Accosding to this page: http://developer.mimer.com/validator/parser200x/index.tml#parser

The having clause is more standard when specified like this (though I can't test this).

HAVING   im.id = min(im.id)

Edit (Based on question Edit).

Your problem is this line:

GROUP BY h.id, im.id, h.name, im.name

This means for every line that is unique across all four values will be compressed together (ie if all four values are the same the lines are compressed together). You need to maintain the original GROUP BY clause (and fix another part of the query).

GROUP BY h.id

I can't test this as I only have MySQL available and you seem to be using an MS product (and my original query worked on MySQL). But based on the error message:

  *_image.id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.*

We don't want to add anything to the GROUP BY clause. Thus following the error message indicates we need to use aggregate functions (in the select probably).

Try changing the select:

SELECT   h.id, h.name, min(im.id), im.name
                       ^^^^^^^^^^

I am sure if you play around with this you should be able to get it working. Sorry I can not be more exact but that would require using the same product as you.


Optimize parsing of number for currency conversion

This code has various issues. Here is what I understand your code does:

  The code takes a formatted number which consists of digits, separators (commas or periods). The last separator is used as the decimal separator, all other separators are deleted.

  Then it multiplies the number with some exchange rate, and returns that as a string.

The issues with your code are:

format is not used.
exchangeCurrencyID is not used.
The exchange rate is hard-coded
You use regexes for simple transliterations
Your code obfuscates the intent.
Your method does multiple unrelated things:

Sanitizing and parsing the number string
Applying exchange rate conversion
These separate responsibilities should be performed by two separate methods.

If we wish to avoid using regexes for a task that does not need them, we could write something like this:

StringBuilder sanitized = new StringBuilder();
boolean decimalSeparatorFound = false;
char[] chars = value.toCharArray();
for (int i = chars.length-1; i >= 0; i--) {
    if (chars[i] == ',' || chars[i] == '.') {
        if (decimalSeparatorFound) continue;  // skip this char
        decimalSeparatorFound = true;
        sanitized.append('.');
    } else {
        sanitized.append(chars[i]);
    }
}
double price = Double.valueOf(sanitized.reverse().toString());

...


The code can be simplified and improved in several ways, and the inner loop can be made tighter. Let me show you how:

private static List<List<String>> readTXTFile(String csvFileName) throws IOException {

    String line = null;
    BufferedReader stream = null;
    List<List<String>> csvData = new ArrayList<List<String>>();

    try {
        stream = new BufferedReader(new FileReader(csvFileName));
        while ((line = stream.readLine()) != null) {
            String[] splitted = line.split(",");
            List<String> dataLine = new ArrayList<String>(splitted.length);
            for (String data : splitted)
                dataLine.add(data);
            csvData.add(dataLine);
        }
    } finally {
        if (stream != null)
            stream.close();
    }

    return csvData;

}

A method should throw an exception as specific as possible, here it's better to use IOException instead of simply Exception
Whenever possible, return interface types instead of concrete classes. Using List is preferred to using Vector, this allows you the flexibility to change the implementation of the collection later
Talking about collections: Vector is thread-safe and synchronized in many of its public methods, that can cause a performance hit. If you don't need that, it's better to use ArrayList, it's a drop-in replacement and won't incur in the performance penalty of synchronization.
There's a simpler way to instantiate a BufferedReader, using a FileReader instead of using an InputStreamReader plus a FileInputStream. Besides, FileReader will take care of pesky details regarding character encoding
There's a simpler way to add elements to the last List added to csvData, as shown in the code
There's a simpler way to iterate through the String[] returned by split(), using an enhanced loop
Don't forget to close your streams! preferably inside a finally block

If you don't need to add more elements to the returned List<List<String>>, you can use the following alternate version. It's faster because it avoids copying the String[] of split elements, but it won't allow adding new elements, as per the contract of asList():

private static List<List<String>> readTXTFile(String csvFileName) throws IOException {

    String line = null;
    BufferedReader stream = null;
    List<List<String>> csvData = new ArrayList<List<String>>();

    try {
        stream = new BufferedReader(new FileReader(csvFileName));
        while ((line = stream.readLine()) != null)
            csvData.add(Arrays.asList(line.split(",")));
    } finally {
        if (stream != null)
            stream.close();
    }

    return csvData;

}


Per the other example - step 1 should be to get out your profiler.

In any case -
I suspect you would get significantly reduced round trip times by taking advantage of JDBC batching capability. Here's an example: http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm (see the second one - using a prepared statement).

In short - you create your DELETE prepared statement, drop the values into a batch, and then execute the batch in one go. Use a prepared statement to reduce parse time for the server.

Depending on if you want to ramp up the complexity, you might want to split the rows into tasks and run them in parallel threads.


Your code breaks the rules slightly by using two queues as auxiliary storage - I've done it with the allowed single stack. As you can see the first part of the code is very similar to yours, but the reconstruction and equals checking are simpler. By knowing that I always put the elements from s1 first, I need to reconstruct the other way around so s2 first later on from aux.

The code works nicely with empty inputs and puts them back in the correct order

    public boolean equals(Stack<Integer> s1, Stack<Integer> s2){
    Stack<Integer> aux = new Stack<>();
    boolean equal = true;
    while(!s1.isEmpty() && !s2.isEmpty()){
        int first = s1.pop();
        int second = s2.pop();
        aux.push(first);
        aux.push(second);
        if(first != second){
            equal = false;
            break;
        }
    }
    // Equal if both stacks are empty
     if(!(s1.isEmpty() || s2.isEmpty())){
        equal = false;
     }

    // Reconstruct
    while(!aux.isEmpty()){
        s2.push(aux.pop());
        s1.push(aux.pop());
    }
    return equal;
}


Return the shortest substring containing all the characters in the set

I couldn't remove the ifs and the flag , so i thought about a diffrent aproach,

Using regular expressions seem more reasonable aproach, you can have a function that returns all the possible combinations of the letters in the array, create regular expressions from the resulting combinations and match against the orignalStr,

function perm(xs) {
  let ret = [];
  for (let i = 0; i < xs.length; i = i + 1) {
    let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));

    if (!rest.length)
      ret.push([xs[i]]);
    else
      for (let j = 0; j < rest.length; j = j + 1)
        ret.push([xs[i]].concat(rest[j]));
  }
  return ret;
}

const originalStr = 'figehaeci', letters = ['a', 'e', 'i'];
let result = originalStr;

const combinations = perm(letters).map(combo => combo.join('.*?'));

// combinations : ["a.*?e.*?i","a.*?i.*?e","e.*?a.*?i","e.*?i.*?a","i.*?a.*?e","i.*?e.*?a"]

combinations.forEach(combo => {
  const exp = new RegExp(combo, 'g');
  const matches = originalStr.match(exp) || [];

  matches.forEach(match => {
    if (match.length <= result.length)
      result = match;
  });
});

console.log(result);

The code you posted returns only one value if there's more substrings containing those letters, here's a tweak to store all possible shortest combinations in an array :

function perm(xs) {
  let ret = [];
  for (let i = 0; i < xs.length; i = i + 1) {
    let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));

    if (!rest.length)
      ret.push([xs[i]]);
    else
      for (let j = 0; j < rest.length; j = j + 1)
        ret.push([xs[i]].concat(rest[j]));
  }
  return ret;
}

const originalStr = 'figehaecizaexi', letters = ['a', 'e', 'i'];
let shortestLength = originalStr.length, result = [];

const combinations = perm(letters).map(combo => combo.join('.*?'));

// combinations : ["a.*?e.*?i","a.*?i.*?e","e.*?a.*?i","e.*?i.*?a","i.*?a.*?e","i.*?e.*?a"]

combinations.forEach(combo => {
  const exp = new RegExp(combo, 'g');
  const matches = originalStr.match(exp) || [];

  matches.forEach(match => {
    if (match.length < shortestLength) {
      shortestLength = match.length;
      result = [match];
    }
    if (match.length === shortestLength) {
      result.push(match);
    }
  });
});

const deduped = [...new Set(result)];

console.log(deduped);


Comparison to infinity when checking if a point is above a line

It would be faster to use the math.isinf() function:

>>> from math import e, pi, isinf
>>> s = [0, float('inf'), e, pi]
>>> map(isinf, s)
[False, True, False, False]

The reason your current check is taking so long is due to how much work it has to do:

>>> from dis import dis

>>> def my_isinf(f):
        return f == float('Inf')

>>> dis(my_isinf)
  2           0 LOAD_FAST                0 (f)
              3 LOAD_GLOBAL              0 (float)
              6 LOAD_CONST               1 ('Inf')
              9 CALL_FUNCTION            1
             12 COMPARE_OP               2 (==)
             15 RETURN_VALUE

There is a global load which involves a dictionary lookup.  There is a two-arguments function call.  The Float constructor has to parse the string and then allocate (and refcount) a new float object in memory.  Then the comparison step dispatches its work to float.__eq__ which returns a boolean value which is then the fed to the if-statement.


You have a bug: .getMinimum() loses track if you push the same new minimum value twice.

You should use both inheritance and composition.

Use inheritance for the "main" stack, because your data structure is a stack — one with an extra feature.  That gives you the read-only operations .peek(), .size(), and .isEmpty() for free.

Use composition for the "minimum" stack, as you have currently done.


I have one big swooping recommendation that I feel you should address before tackling anything else:

Mind your class invariants!

When designing a class, ideally you want to ensure every single public member function handles correctly any possible valid state of the class, in conjunction with any possible passed argument. In your case, ask yourself:

What happens if Loop() gets called before Init()? What happens if Init() gets called twice in a row? What happens if Create3DWindow() is called after Init()?

A good way to tackle that is to define what's known as a class invariant.

First, jot down on paper a description of the legal internal states of the class. That's known as the class invariant.

For example, you may want to have m_hInstance is either NULL or points to a window instance in your invariant definition, but m_hInstance points to a window instance would be even better, because it allows you to rely on that being true, so you don't have to constantly check.

Second, for each public member function, make sure that the function's behavior is well defined for every possible invariant state, and that it leaves the class in an invariant state after it's done.

Mind you, it doesn't mean that every public member function must "work", just that it doesn't explode, cause memory leaks, etc...

Edit: There are some extreme exceptions to this, such as std::vector<>'s operator[]. But this is an exception, and the class' documentation makes it extremely clear that you enter no-mans land if you call that with an index outside of the bounds.


The greatest problem with this is that you want to make these elements optional without actually marking whether they are present.  There are at least two alternatives to this or normal GET parameters that allow for all three to be optional.

Mark whether they are present

Consider a URI that looks like /jobs/keyword/engineer/c++/type/full_time/part_time/location/canada or /jobs-keyword-engineer-c++-type-full_time-part_time-location-canada (if you want everything in the first slot for search engine optimization).  You may prefer something like kword, etype, and loc to make those less likely to show up as keywords themselves.  I would dislike those as variable names, but the exigencies here may make them better as parameter names.  Ideally those would be things that make no sense as keywords.

This is still slug based.  It simply has some extra information to help you parse.

Look up everything

You currently have a PHP-based list of valid employment types.  Instead, put every valid employment type and location in a database table.  Then you can say something like

SELECT parameter_id, parameter_name, parameter_type
FROM parameters
WHERE parameter_name IN (?, ?, ?, ?, ?)

where you then pass (for example)

['engineer', 'c++', 'full_time', 'part_time', 'canada']

as the things to select.

I would prefer to store employment types in the database, as they are data to me.  Storing them in code is itself a spaghetti code problem in my opinion.

The results will be all the employment types and locations, which you can then easily represent by objects or IDs.  Whatever remains will be the keywords, which presumably aren't bounded in the same way that employment types and locations are.


Design

It's not great that some functions that manipulate internal state are exposed.
It would be better to make them private,
inaccessible from outside the class.

Alternatively, change them in a way that they will not modify the internal state.

Avoid unnecessary evaluation

Here, test2 doesn't need to be evaluated when test is true:

let format = /\w{3,9}?\s\d{1,2}?,\s\d{4}?/;
let unixFormat = /^\d[0-9]{0,20}$/;
let test = format.test(string);
let test2 = unixFormat.test(string);

if (test === true){
  this.natToUnix(string);

} else if (test2 === true) {
  this.unixToNat(string);

I would rewrite like this:

if (this.isNaturalFormat(input)) {
  return this.getResultWithUnixFormat(this.naturalToUnix(input));
}
if (this.isUnixFormat(input)) {
  return this.getResultWithNaturalFormat(this.unixToNatural(input));
}
return this.getResult();

All the functions I invented here, I suggest to write them ;-)
That is, getResultWithUnixFormat takes as parameter a date in unix format, and returns {unix: ?}, and so on.

Use boolean values directly

Since .test(...) returns a boolean, you could use if (test) instead of this:

let test = format.test(string);
// ...

if (test === true){
  // ...

Naming

test and test2 don't tell much about their purpose:

let format = /\w{3,9}?\s\d{1,2}?,\s\d{4}?/;
let unixFormat = /^\d[0-9]{0,20}$/;
let test = format.test(string);
let test2 = unixFormat.test(string);

I suggest to rename them to isNaturalFormat and isUnixFormat.

Also, I would spell out nat as natural in unixToNat and natToUnix.

Thread-safety

It's true that thread-safety is not a practical concern in JavaScript,
as user code is typically executed on a single thread in browsers and in node.js too.
However, I think it's still a good idea to write thread-safe code when it's easily possible, in order to avoid picking up bad habits that may bite you later in other languages.

The implementation is not thread-safe.
checkstring calls functions that mutate the internal state of the instance (naturalDate and unixTime),
so if this function gets called from concurrent threads,
you may get incorrect results.

You can easily make it thread-safe by eliminating the naturalDate and unixTime fields.
You don't need them.
These can be local variables in checkstring,
and passed as parameters to getResults.

In fact, the best would be to replace getResults with dedicated functions that return {unix: ?, natural: ?} with the appropriate value filled,
as I did in the examples above.


The are lots of different sorting algorithms out there. You seem to have re-implemented "Bubble Sort". This is one of my favorite algorithms as it is very easy to write and sufficient (or even preferable) for very small data sets.

The problem with bubble sort is that it has a very bad complexity so when the data sets become large it becomes very expensive and there are other much better algorithms for large data sets.

Overview

  This started as a simple exercise in sorting an array.

Good thing to work on when you are a beginner.

  I wanted to make it a bit more complex which is why I made it a 2D array.

I don't think this adds anything to the problem. One of the main concepts of computer science is abstraction. In sorting we usually abstract the comparison out so that it simply becomes a comparison operation (usually less than i.e. operator<). If you abstract out the comparison you are simply left with the sorting algorithm (which then is the same for every type). So you should have written a less than operation and then you could have re-used the sorting algorithm for any type.

  I then noticed that each pass that checked and swapped values, it was checking all ten values. This seemed unnecessary because with each pass the highest value gets moved all the way to its final position. So I made it check one less element each pass until it finished.

This is a standard optimization for "Bubble Sort". Unfortunately it does not reduce the complexity that much. Still making this the worst sort for large data sets.

One other optimization (which is a very make Bubble Sort great) is that if you do a full inner loop and there was not a single swap then the array is sorted. You can not break out of the outer loop. This optimization is great as it turns the best case situation (where the data is already sorted (or very close to sorted)) into an O(n) (i.e. linear) operation.

  I did not want to use std::sort, this was an exercise in finding my own solution.

Yes. Experimenting with sorting is good. But you should read up on the different types of algorithm and try and re-implement them. Doing this is great experience and will teach you the advantages of the different types.

  The program was "falling off" the end of the array, and although I managed to work around it, I'm not sure I did it in the right way, or even why it was doing it in the first place.

Can't help with that unless I see the code from before your fix. But even if you did this is the wrong site for that. We only review working code.

OK. I found the the bug you mentioned (and fixed). It seems like a common one so I will talk about that below.

  The program seems to work as intended but would like some feedback on how it can be improved, or any issues etc.

OK. Lets have a look.

Code Review

Your Bug:

    if (person[i][1] > person[i + 1][1] && i != ROWS - 1)
    // The && condition stopped the  program falling off the end of the array
    // but not sure why it was in the first place

So you have a loop:

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

This will allow you to loop over the array so you can accesses all the elements with person[i]. Where ROWS is the number of rows in the array. So this allows you to access all the valid rows. Remember that valid rows in an array are counted from 0 so the last valid row is ROWS - 1 (this is why most loops use less than operator< as you do in the loop test.

The problem is that you also accesses the element person[i + 1]. The largest value of i is ROW-1 so the largest element accessed is person[ROW-1+1] or person[ROW] that is one past the end of the array.

int  array[3] = {1,2,3};
std::cout << array[0];   // first  element
std::cout << array[1];   // second element
std::cout << array[2];   // third  element
// Only 3 elements in the array
std::cout << array[3];   // This is one beyond the end.

Abstraction and self documenting code

Pull out simple pieces of code into their own well named function. This documents what you are doing and makes the underlying algorithm easier to read.

            {
                int temp = person[i][1];
                person[i][1] = person[i + 1][1];
                person[i + 1][1] = temp;
            }

This is obviously a swap. Why not write a function called swapPerson(person[i], person[i+1]); that swaps the values of two people. This will make the sort algorithm easier to read. This also moves the actual swapping processes out of the algorithm allowing you to more easily replace it with another one when you use a different type.

Note: This is so common that the standard library has a std::swap() that swaps two values of a the same type.

Now looking at the comparison:

            if (person[i][1] > person[i + 1][1])

Your code is comparing two elements adding the extra [1] on the end does not change much. But I would change it so that I was comparing two people.

             if (lessPerson(person[i + 1], person[i]) {
             }

Still looks a bit ugly. But it shows you can use a function to do the test. But C++ lets you define functions that look like maths operations. So you can change the named lessPerson() function into operator<() function that allows you to compare two people.

             if (person[i + 1] < person[i]) {
             }

Optimizing the loop

        for (int i = 0; i < ROWS; ++i, ++count )
        {
            if (loop + count == ROWS + 1)   // skips unnecessary checks
            {
                break;
            }

This seems like a very complex way of writing:

        for (int i = 0; i < j; ++i) {

Now if we look at your sort Algorithm after these changes:

    for (int j = ROWS - 1; j > 0; --j) {
        for (int i = 0; i < j; ++i) {
            if (person[i + 1] < person[i + 1]) {
                std::swap(person[i], person[i+1]);
            }
        }
    }

Boiled Down Code.

We seem to have boiled down your code to the absolute minimum. I would add the optimization I mentioned above and wrap this in its own function to make it:

void sort(Person person[], int const ROWS)
{
    for (int j = ROWS - 1; j > 0; --j) {
        bool swapped = false;
        for (int i = 0; i < j; ++) {
            if (person[i + 1] < person[i + 1]) {
                swapped  = true
                std::swap(person[i], person[i+1]);
            }
        }
        if (!swapped) {
            break;
        }
    }
}

Notice I have added the type Person so can explicitly write functions to swap and compare objects of type Person. Now you can write a less than (operator<) and assignment (operator= used by std::swap) specifically for people that would allow the algorithm to work without having to be specific to the algorithm.

The next step is then to make the sort work for any type. Usually we do this with templates. So we can pass any type into the sort function and allow it to be sorted (as long as the type has an operator< and an operator=).

template<typename T>
void sort(T array[], int const ROWS)
{
    for (int j = ROWS - 1; j > 0; --j) {
        bool swapped = false;
        for (int i = 0; i < j; ++) {
            if (array[i + 1] < array[i + 1]) {
                swapped  = true
                std::swap(array[i], array[i+1]);
            }
        }
        if (!swapped) {
            break;
        }
    }
}

The next step is to learn about the concepts of Iterators and how that can make the above function even more useful. But I will leave that as an exercise for now.

Bad Habits

Please don't do this:

using std::cout;
using std::cin;
using std::endl;

Is it that much harder to write std::cout over cout? This is a kind of habit that will get you into a lot of trouble. Especially when you put using at the top level of a file. If you must do this, do it inside a function so it does not pollute the code.

Not sure what the extra level of braces is for.

        {
            cout << endl;
        }

But prefer to use '\n' rather than std::endl. The only difference is that std::endl performs a forced flush of the stream. The stream will auto flush so there is no need to force a flush to start with. Also manually flushing the stream (by the programmer) is nearly always going to cause sub optimal flushing and lead to performance degradation.

You don't need a return 0 in main().

    return 0;


Multiple anonymous IIFEs inside outer function

Modules You're already using export syntax, so you're currently in a module. Rather than defining multiple IIFEs, you might consider using separate sub-modules:
// fadeInHeadings.js

// Renaming from headingFadeIn to fadeInHeading for readability
function fadeInHeading(heading) {
    if (!heading) return;
    const parent = heading.parentNode.parentNode;
    const triggerHeight = parent.offsetTop - window.innerHeight / 1.5;

    if (window.scrollY > triggerHeight) {
        heading.style.opacity = '1';
    } else heading.style.opacity = '0';
}

export const fadeInHeadings = () => {
  const headingIds = [
    'portfolio-heading',
    'skills-heading',
    'bio-heading',
    'contact-heading',
  ];
  for (const id of headingIds) {
    fadeInHeading(document.getElementById(id));
  }
};

// scrollHandler.js
import { fadeInHeadings } from './fadeInHeadings';
import { transformBars } from './transformBars';
import { transformReviews } from './transformReviews';

export default function scrollHandler() {
  fadeInHeadings();

  const { capToggled, newTriggerCalculateHeight } = transformBars();
  capToggle ||= capToggled;
  triggerCalculateHeight ||= newTriggerCalculateHeight;

  transformReviews();

  // ...

This way, when, for example, a review isn't scaling properly, you can navigate directly to transformReviews to debug and fix the problem, rather than wander around in a significantly larger file looking for where reviews are referenced.
Variable names and iteration Your two forEaches are a bit confusing:
bars.forEach((i, index) => {

When i is used as a variable name, it's almost always used to reference the index of a collection. To have i not only not refer to an index, but to also have an index variable, is confusing. Instead, consider:
bars.forEach((bar, index) => {

Same sort of thing in Contact:
const groups = document.querySelectorAll('.form-group');
if (!groups) return;
groups.forEach((i, index) => {

i should probably be renamed to formGroup or something similar. Also, querySelectorAll will return an array-like NodeList. Even if it's empty, it'll never be falsey, so you can remove the if (!groups) return; line.
children You have
formGroup.childNodes[1].blur();

childNodes returns a collection that includes text nodes. Text nodes can be empty, and including them in a collection can make logic more tedious than it needs to be. Since you want to select an element with that, better to use .children (which only returns element children nodes), so you can do
formGroup.children[1].blur();
// or
formGroup.children[0].blur();
// or, be more specific and use a CSS selector
formGroup.querySelector(<some-selector>).blur();

Persistent variables? The persistent module variables seem a bit odd. If they really need to be in persistent state, it might make sense to expose a function that returns their current values. If they aren't meant to be persistent, initialize them to false inside scrollHandler instead - or, inside the sub-module which reassigns its value, which is returned to scrollHandler and then returned by scrollHandler. For example, it'd be great if you could do this:
// showFormGroups.js
export const showFormGroups = () => {
    const groups = document.querySelectorAll('.form-group');
    let scrollEnd = false;
    groups.forEach((formGroup, index) => {
        formGroup.children[1].blur();
        if (window.scrollY > (formGroup.getBoundingClientRect().top * 10) / 1.5) {
            formGroup.style.opacity = '1';
            if (index >= groups.length - 1) {
                scrollEnd = true;
            }
        }
    });
    return scrollEnd;
};

// scrollHandler.js
export default function scrollHandler() {
    // ...
    const scrollEnd = showFormGroups();
    // ...
    return { capToggle, triggerCalculateHeight, scrollEnd };

Styles into CSS You have
if (window.scrollY > bound) {
    mainBackground.style.opacity = '1';
    mainBackground.style.transform = 'scale(1) rotate(45deg)';
    backgrounds.forEach(i => (i.style.opacity = '1'));
    backgrounds[0].style.transform = 'translate(-4%, -9%) skew(45deg)';
    backgrounds[1].style.transform = 'translate(-6%, -2%) skew(45deg)';
    backgrounds[2].style.transform = 'translate(-5%, 1%) skew(45deg)';
    texts.forEach(i => (i.style.opacity = '1'));
}

To apply this logic, I think it'd make more sense to put the CSS rules in your CSS file, and then just toggle a class. Something like:
// SCSS for brevity
body.showReviews {
  #ul-bg {
    opacity: 1;
    transform: scale(1) rotate(45deg);
  }
  .blockquote-bg {
    opacity: 1;
  }
  .blockquote-bg:nth-of-type(1) {
    transform: translate(-4%, -9%) skew(45deg);
  }
  .blockquote-bg:nth-of-type(2) {
    transform: translate(-6%, -2%) skew(45deg);
  }
  .blockquote-bg:nth-of-type(3) {
    transform: translate(-5%, 1%) skew(45deg);
  }
  .reviews-toggle {
    opacity: 1;
  }
}

// transformReviews.js
export const transformReviews = () => {
  const el = document.getElementById('reviews-inner');
  if (!el) return;
  const bound = el.getBoundingClientRect().top * 10;
  document.body.classList.toggle('showReviews', window.scrollY > bound);
};

Framework On a larger scale, all of this careful element selecting, iterating, examining, and manual manipulation of the DOM seems a bit tedious. For a professional project that isn't tiny, I would prefer to look into a framework like React to tie element state directly to their respective DOM elements.


Verifying the Entity Data Model schema against a production database

Is there a better way?
  Does Entity Framework already provide a mechanism for achieving this?

In fact this is one question. If EF would provide a mechanism, undoubtedly that would be better, because you'd know for sure it yields something that EF is happy with. Unfortunately, no, EF hasn't got such a mechanism.

As far as EF checks the consistency of the database with an existing model, it only compares a previously stored model hash in the database with the current model hash. It never compares actual database objects. That would take far too much time in checking whether a migration should be applied. And then, all these methods are internal.

There is however a shorter and more reliable way to get entity and property names from a context. More reliable, because you'll only get the mapped entities and properties without having to jump through hoops to exclude non-mapped ones. I'll give you the heart of it, so you can fit it in appropriately.

var oc = ((IObjectContextAdapter)dbcontext).ObjectContext;

var items = oc.MetadataWorkspace.GetItems(DataSpace.CSpace).OfType<EntityType>();
foreach (var entityType in items)
{
    var props = string.Join(",", entityType.Properties);
    Debug.WriteLine(string.Format("{0}: {1}", entityType.Name, props));
}

  Would this be better in the data layer or in another assembly?

I would make the part that provides table and column names part of the data layer, because there you have all required references. I would not include the part that queries the database, because it's done with Dapper, and...

  Is adding Dapper (just for this purpose) overkill, does it add unnecessary complexity to the project?

No, Dapper is great. But since this is a third-party dependency I would use it in a separate assembly that has a reference to your DAL (to obtain the database object names), so your DAL doesn't have this dependency.


This is a really great idea! I could certainly use a class like this. Here are some thoughts:
Don't Multiply Declare public
It's very odd that you're prefixing every single method with its visibility. I really hate working with code that has multiple public, private or protected sections. I expect all public methods and members to be grouped together, all protected methods and members to be grouped together, and all private methods and members to be grouped together (usually in that order). While it's not required by the language, it's a pain to constantly have to figure out which section you're in when reading, and it's a pain to write it out for every method prototype when you're writing the code.
Avoid protected Member Variables
In general protected member variables are a bad idea. They essentially mean that any other object of the class or subclass can change their value out from under you. There's a case to be made for public member variables when performance is of the utmost importance, but in general member variables should be private so you can control who's changing them and when.
Retains and Releases Should Be Matched
It's a little surprising that I can tell the constructor not to retain the object, but the destructor will still release it. This is almost like a false cognate in another language - it looks similar to another pattern where you tell the constructor of some object that you're going to manually manage the memory for a given resource, so it shouldn't delete it when destructed. I understand the reason why - some CF methods return retained objects. Still, as someone potentially reading the code, it's a little unexpected. In Objective-C you could autorelease the value when calling the constructor and not worry about the retain, but there's no such mechanism for the C interface to CoreFoundation. Furthermore, the likelihood that I'll remember to pass false to the constructor when I can't remember to do the release manually is unlikely. For that reason, I recommend at least removing the default value. I'm also left wondering if there's some better way to handle this particular case. (I guess a first-class interface to CoreFoundation from C++ would be the ideal answer, but that's not going to happen unless you write it yourself.)


32-bit factorial calculator in x86 NASM assembly

There are a couple of things that may be of use to you for this code, and some general comments that should be useful for any assembly language programs you write in the future.

Make it modular

The code that implements the factorial routine does a je display_result to exit, but that needlessly ties it to the display routine.  In assembly language, it's generally better to use either a ret to return (implying it's written as a subroutine) or to have the routine "fall through" the end.  Either is acceptable, but implementing as subroutines is more common.

Prefer subroutines to macros

The macros you've got might, underneath, result in a subroutine call to some code other than that which you've posted, or more likely, it implements directly the code used to perform those functions.  There might be a slight performance advantage to replicating the code multiple times via a macro invocation, but more often, it just leads to code bloat.  (Although even with this "bloat" it's probably smaller than the corresponding C program!)

Comment fully

If we look at the comment for calc_factorial it currently reads this way:

    ; EAX - current value
    ; EBX - counter
    ; ECX - current total (for multiplication)
    ; EDX - counter (for multiplication)

This may be accurate, but which are inputs?  Which are outputs?  What does the routine do?  I'd recommend a comment style something more like this:

    ;****************************************************************************
    ;
    ; PrintString
    ; prints the string at DS:DX with length CX to stdout
    ;
    ; INPUT:     ds:dx ==> string, cx = string length
    ; OUTPUT:    CF set on error, AX = error code if carry set
    ; DESTROYED: ax, bx
    ;
    ;****************************************************************************

Use mul rather than add

The mul instruction is definitely going to be faster than the corresponding loop with add instructions.  The mul instruction as a 32-bit instruction multiplies EAX by some other register, yielding a result in EDX:EAX meaning that the high part of the result will be in EDX and the low 32 bits of the result will be in EAX.

Structure code to avoid unconditional jumps

If we look at the code, (with comments removed for clarity) we can see that the code does a jmp mult_with_addition but it's jumping over an instruction that cannot be reached!  For that reason, you could eliminate both jmp instructions.

    calc_factorial:
       dec   EBX
       cmp   EBX, 1
       je    display_result

       mov   ECX, EAX
       mov   EDX, EBX
       jmp   mult_with_addition

       jmp   calc_factorial

    mult_with_addition:
       dec   EDX
       cmp   EDX, 0
       je    calc_factorial

       add   EAX, ECX

       jmp   mult_with_addition

Minimize register moves

As much as practical, try to minimize register moves, preferring instead to have the data already in the register you need for instructions or subroutines which have register-specific needs.  For example, because the mul instruction uses EDX and EAX, it makes sense to try to make sure that the number being multiplied is already in that register pair.

Don't fail silently

As with any code in any language, failing silently must be avoided.  In the case of a factorial operation, an overflow condition should be checked and passed back to the calling code.  If you use the mul instruction, and return a 32-bit result in EAX, checking for overflow is as simple as checking EDX for a zero value.

Look carefully at instruction encodings

In one place in your code, you have the instruction cmp EDX,0 followed by a conditional jump based on the Z flag.  In 32-bit mode, that instruction is probably coded as 83FA00 but if you had used or EDX,EDX it is likely to be coded as 09D2 which is one byte shorter.  However, neither are really needed because the dec EDX instruction before it (encoded as 4A) already sets the Z flag. There may be no reason to care about one or two bytes one way or the other, but if that's the case, why code in assembly at all?  If you're going to do it, do it well.


Thread-Safe and Lock-Free - Queue Implementation

Yes.

The combination of volatile and compare-and-swap operations is enough to make sure that the Node objects are safely published.
The compare-and-swap must be before the assignment to a volatile variable in both methods, so you're fine there. They do not need to happen atomically.

The queue exhibits odd behavior. Let's say thread 1 stops in putObject() after the CAS but before the last assignment. Next thread 2 executes putObject() in its entirety. Next thread three calls getObject(), and it cannot see either of the first two objects, even though thread 2 is completely done. There's a small chain being built up in-memory. Only after thread 1 completes putObject() are both objects visible on the queue, which is somewhat surprising, and has weaker semantics than most non-blocking data structures.

Another way of looking at the odd API is that it's nice to have a non-blocking put() but it's very strange to have a non-blocking get(). It means that the queue must be used with repeated polling and sleeping.


Pythonic way to flatten nested dictionarys

dictionary_ = dict(
        ii
        for i
        in [unpack(key, value) for key, value in dictionary_.items()]
        for ii
        in i
    )

This is probably the worst part in the code, yet this is pretty much the whole code. Variable names are terrible and the intent is a bit hidden. I understand that unpack returns lists so your list-comprehension generates a list of lists. So this expression is flattening a list of list of tuples and turning it into a dictionary.

For starter, flattening iterables of iterables can be achieved more easily using itertools.chain.from_iterable so you just need dictionary_ = dict(itertools.chain.from_iterable([unpack(key, value) for key, value in dictionary_.items()])) and get rid of the awful variable names.

Second, and this also apply to the all() call, you can use simpler generator expression instead of full list-comprehension to play it nicer with the memory. This only means removing the square brackets around the expression:

dictionary_ = dict(itertools.chain.from_iterable(
        unpack(key, value) for key, value in dictionary_.items()
))

Lastly, but this is highly debatable, I would use itertools.starmap instead of the whole expression:

dictionary_ = dict(itertools.chain.from_iterable(itertools.starmap(unpack, dictionary_.items()))

I would also change unpack to fit more nicely with these changes: make it a generator instead of building lists (that you are going to discard right away). And just to propose an alternative way, I’ll go with an EAFP approach:

def unpack(parent_key, parent_value):
    """A function to unpack one level of nesting in a dictionary"""

    try:
        items = parent_value.items()
    except AttributeError:
        # parent_value was not a dict, no need to flatten
        yield (parent_key, parent_value)
    else:
        for key, value in items:
            yield (parent_key + delimiter + key, value)

You may also find this function to choke on dictionaries whose keys are not strings. This is due to the parent_key + delimiter + key part that will fail to "concatenate" numbers and strings for instance. Or any custom object…

There are two solutions to this problem depending on the intended use-case:

use str.format to convert each key to a string;
use a tuple as the flattened key instead of a string.

I prefer the second solution as a key of '3.14' can ambiguously be comming from the key '3' and '14' or '3.14' in the first solution. Whole code would be:

from itertools import chain, starmap

def flatten_dict(dictionary):
    """Flatten a nested dictionary structure"""

    def unpack(parent_key, parent_value):
        """Unpack one level of nesting in a dictionary"""
        try:
            items = parent_value.items()
        except AttributeError:
            # parent_value was not a dict, no need to flatten
            yield (parent_key, parent_value)
        else:
            for key, value in items:
                yield (parent_key + (key,), value)

    # Put each key into a tuple to initiate building a tuple of subkeys
    dictionary = {(key,): value for key, value in dictionary.items()}

    while True:
        # Keep unpacking the dictionary until all value's are not dictionary's
        dictionary = dict(chain.from_iterable(starmap(unpack, dictionary.items()))
        if not any(isinstance(value, dict) for value in dictionary.values()):
            break

    return dictionary


Validate that a relative path exists or is an external URI

Very interesting,

I only have 1 snarky comment, if files is an array of 'paths', maybe you should call it paths ;)

Also, as a user of this function, I might want to override your regex so you might want to provide support for that.


delete eventCheck.data;

This line invokes undefined behavior, because you aren't allowed to call delete on an incomplete type (and certainly not on void). Both GCC and Clang warn on this line:

(clang++)
prog.cc:4:5: warning: cannot delete expression with pointer-to-'void' type 'void *' [-Wdelete-incomplete]
    delete p;
    ^      ~

(g++)
prog.cc:4:12: warning: deleting 'void*' is undefined
     delete p;
            ^

Anyway, it won't do what you want (whatever that might be).

For an open set of types, the type-safe way to do what you're trying to do is to use type erasure, as seen in library containers such as std::function<void(void)>. (Shameless plug for my CppCon 2014 talk — type erasure is covered starting at 23m00s.) This kind of type-erasure is easy to implement yourself from scratch in about 20 lines of code.

For a closed set of types, you might see whether your compiler of choice supports C++17 std::variant and/or Boost boost::variant; you can use the visit function to perform an operation on a variant in a type-safe way, and of course you wouldn't even need delete at that point because you wouldn't be using pointers, just plain old value semantics. If you can't use Boost, then I don't recommend trying to implement variant yourself.


Function that check's file type based on certain keywords

Regarding your naming:

I'd rename:

validationTypeOfSQL() to isSQL()
createSourceCodeTokens to sourceCodeTokens
createSourceCodeTokens() to sourceCodeTokens()
x to token
tokenToSmallerToken() to smallerTokens()
smallerTOkenValue to smallerToken
result to containsComma (It's better, of course, to remove it completely according to Robert Snyder's answer.)
tokenSplit to splitTokens
ts to st or splitToken
t to k or keyword
uniqueKeyword to keyword

I'd change String smallerTokens[] to String[] .... as you write it 4 lines later anyway.

I' d use replaceAll(String regex, String replacement) with replaceAll("[(,)\t]", "") instead of the replace() chain.


A simple calculator to calculate the frequency of a recessive allele

Some suggestions:

call variables this_way not thisWay
use less comments
put your interaction with user into separate functions
if code will be splited properly you will be able to user return and while True: instead of test variable
return object or dict from calculate_frequency rather than long tuple
don't create strings like that:

str(hzDominantNum)+'/'+str(total)+' ('+str(hzDominantFreq)+'%) are normal (homozygous dominant).\n'

this is mutch better:

'%f/%f (%d%%) are normal (homozygous dominant).\n' % (hzDominantNum, total, hzDominantFreq)

if you have to run this as a program do it this way:

def main():
    print "test"

if __name__ == "__main__":
    main()


First Unique Character in Java by frequency

As from @RobAu 's comment the title is misleading because you returns the index of the first unique character in your frequencies array so that the index 0 refers to the 'a' char, 1 refers to the 'b' char, etc., making the assumption that your string just contains only letter chars coerent with the ascii table.
In your code you make use of string methods length() and charAt to iterate over the string , you can iterate directly over one char array like below:
private static int firstUniqueChar(String string) {
    int freq[] = new int[26];
    char[] arr = string.toCharArray();

    for(char c : arr) { ++freq[c - 'a']; }

    //other instructions
}

You are using subtraction by 0 in these lines:
System.out.println(string.charAt(j)-0);
System.out.println('a'-0);

I presume you are using this subtraction because you want to print the int value of the char, you can solve this issue casting the char value to int. Below my version of your code:
private static int firstUniqueChar(String string) {
    int freq[] = new int[26];
    char[] arr = string.toCharArray();

    for(char c : arr){
        ++freq[c - 'a'];
    }

    for (int j =0;j < arr.length; ++j){

        System.out.println((int) arr[j]);
        System.out.println((int) 'a');

        if(freq[arr[j] - 'a'] == 1) {
            return j;
        }
    }

    return -1;
}

From your code I have the impression at the moment you are mixing different concepts in an unclear manner.


A Person class containing a list of Persons

But how does it look from an OOP perspective?

Not very good because it combines multiple responsibilities in a single class.

the one of a data object as the Person is clear, I guess. The other two are
the repository represented by

private static List<Person> persons = new List<Person>();

public static Person GetPersonById(int id)
{
    foreach(Person per in persons)
    {
        if (per.ID == id)
            return per;
    }
    return null;
}

public static List<Person> GetPersons()
{
    return persons;
}

and the factory represented by

private static int statId;
statId++;

This means that the Person should actually be three classes.

On top of all this you cannot test it because the nested factory is a static one and if you try to write a test validating the statId++ you couldn't because you cannot verfiy that it'll do +1 to the last id because if any other test executes at the same time the result might actually be +2 or even more. You also cannot verify that it correctly adds the new instance to the list because agian, if any tests execute at the same time you could have more then one object added to the list.

id = statId;
statId++;

I find this is not how the id increment should be implemented. statId should not be the next index but the last one. What if you decide to add a property like LastId? You'd have to calculate it first with statId - 1 - ugly. Instead use the prefix ++ like id = ++statId and start with int statId = -1; that is usually considered as na invalid index in many APIs. Then the LastId property could just be LastId => statId;.


var truncate = pageCount > (7 + (surroundingPageLinkSize * 2));
  if (!truncate) {
    for (var i = 1; i <= pageCount; i++) {
      buttons.push(i);
    }
  }
  else {
    var truncateEnd = currentPage < (1 + (surroundingPageLinkSize * 2)),
        truncateBoth = (pageCount - (surroundingPageLinkSize * 2)) > currentPage && currentPage > (surroundingPageLinkSize * 2);

    if (truncateEnd) {
      for (var j = 1; j < (4 + (surroundingPageLinkSize * 2)); j++) {
        buttons.push(j);
      }
      appendTruncateButtons(buttons, pageCount);
    }
    else if (truncateBoth) {
      prependTruncateButtons(buttons);
      for (var k = (currentPage - surroundingPageLinkSize); k <= (currentPage + surroundingPageLinkSize); k++) {
        buttons.push(k);
      }
      appendTruncateButtons(buttons, pageCount);
    }
    else { // Truncate start
      prependTruncateButtons(buttons);
      for (var l = pageCount - (2 + (surroundingPageLinkSize * 2)); l <= pageCount; l++) {
        buttons.push(l);
      }
    }
  }

Note that all of these cases have essentially the same for loop.

  var start = 1,
      end = pageCount;

  if (currentPage > surroundingPageLinkSize * 2) {
      start = currentPage - surroundingPageLinkSize;
      prependTruncateButtons(buttons);
  }

  if (currentPage < pageCount - surroundingPageLinkSize * 2 - 2) {
      end = currentPage + surroundingPageLinkSize;
  }

  for (var i = start; i <= end; i++) {
      buttons.push(i);
  }

  if (end < pageCount) {
      appendTruncateButtons(buttons);
  }

Now we call it just once, only changing the parameters.

We also only call the prepend and append methods once each.  You could even pull those into this method if you wanted, as they are no longer repeated code.

I also like that this gets rid of the three single use Boolean variables.  Since they weren't reused, they don't seem necessary.

I'm not sure if the output is an exact match for what you had originally, but it should give the same kind of display.

I didn't change it here, but consider changing buttons to pages or even pageNumbers.  These are the pages that you want to make links or buttons that go there.  But they aren't buttons yet.


Don't do using namespace std;

Qualify names properly with std:: where necessary.

string getProdName() const { return prodName; }
int    getQuant() const { return quant; }

Avoid abbreviations as they harm code clarity. Most IDE's provide auto-completion, so abbreviations don't save typing anyway.

receipt(const string& prdNm, int qnt)
      : prodName(prdNm), quant(qnt)
{}

The initializer list allows you to use the same name for the function argument as for the member variable, so this would be fine:

receipt(std::string productName, int quantity)
      : productName(std::move(productName)), quantity(quantity)
{}

(Since the product name is a "sink argument" (we want to copy and store it locally), we can take it by value and move it into place).

I don't think it's a good idea to overload operator< for these classes. These aren't mathematical types, so there's no inherent ordered relationship. It would make just as much sense to sort by product price as by name.

We're using the operator< for sorting in a particular structure, so we want to associate the ordering with that structure, not with the type itself. We can do that using a "functor" class to define comparison, and specifying it as a template argument:

struct ProductLessThanByName
{
    bool operator()(const Product& a, const Product& b) const {
        return a.getName() < b.getName();
    }
};

...

    std::map<Product, int, ProductLessThanByName> products;

record is a rather ambiguous name. Maybe client_purchases or purchase_record or something might be better.

Since we already have the receipt class, that stores product and quantity, we could perhaps use that internally.

Although encapsulation is important, people often interpret it as "make all member variables private and add getter / setter functions". This is fine for classes that have associated logic in member functions, or where we can't change a member without extra work (we must adhere to the class invariants).

However, it's unnecessary for simple data containers. If we don't want to allow the user to change a member of the product or receipt classes, we can enforce that by giving them a const& to the class. So we can save a lot of work and use plain structs. e.g.:

struct  receipt
{
    std::string productName;
    int quantity;
};

It's probably better to use unsigned types for the quantity and price. We don't expect these to ever be negative, and it's easier to rule out invalid values.

As far as the design goes, I'm not sure we need to add clients outside of a transaction. I don't think it really makes sense to "remove" a client either. We have to keep the transaction history intact.

I think it would be helpful to separate the idea of "adding a product-type to the database" from "adding stock (actual items of a product-type) to the shop".

As Kyy13 notes in the comments, we need to store the price at which we sold an item in the transaction history.


Computing the relative magnitude of the values in one double array to another

You are auto-boxing the results of your function call, only to un-box them later. If everything else is using double (a primitive), there is no reason to declare the local variables in solution() as Double (an object). This doesn't effect the big-O of your solution, but it is extra operations for the JVM to execute.

Give your class and public method better names. If you actually needed this in production code, there would be no way to know what this code did. The names tell you nothing and there is no documentation.

There is a max(), but it works on Collections, not arrays. However, writing your own max method is not that hard, so it is up to you if you want to replace it.

Note: Until seeing you question, I didn't know that Double.MIN_VALUE and Integer.MIN_VALUE do not represent the same concept for the respective type. This isn't your fault, but it is unintuitive. Explination


I have one advice, but since the code is not compiling, it's a bit hard to make a proper review.

Instead of using an java.util.LinkedList, I suggest that you use the java.util.concurrent.ExecutorService to handle the threads and use it to check the end of the threads.

        ExecutorService taskExecutor = Executors.newFixedThreadPool(4);

        CompletableFuture<Iterable<ManagedObjectRepresentation>> response = new CompletableFuture<>();

        subscriptions.runForEachTenant(() -> {
            String tenant = subscriptions.getTenant();
            taskExecutor.execute(CompletableFuture.runAsync(() -> {
                subscriptions.runForTenant(tenant, () -> {
                    Iterable<ManagedObjectRepresentation> objects = inventoryApi
                            .getManagedObjectsByFilter(customInventoryFilter).get().allPages();

                    if (!ObjectUtils.isEmpty(objects)) {
                        response.complete(objects);
                    }

                });
            }));
        });

        taskExecutor.shutdown();
        try {
            taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {

        }

        // The threads are finished.

Ref: https://stackoverflow.com/questions/1250643/how-to-wait-for-all-threads-to-finish-using-executorservice


Style

Be consistent in your style. If you use braces {} for single if statements then you should use them always.

Using guard conditions help you to save horizontal space.

NameValueCollection mapQuery = UriExtensions.ParseQueryString(requestUri);
if (mapQuery == null) { return target; }

string fields = mapQuery.Get("fields");
if (String.IsNullOrEmpty(fields)) { return target; }

IEnumerable<string> requiredFields = fields.Split(new char[] { ',' });
if (requiredFields == null) { return target; }

your loop here

otherwise your code looks good.


Python code to guess the roots of any integer

Ignoring points already made in comments...
Escapes
x = int(input('Enter an integer who\'s root value you need: '))
I find reading this line of code jarring.  There is an escape \' in the middle of the string.  Python gives many different types of literal strings with allow you to embed special characters in strings without using escapes.  At the simplest end of the spectrum, a double-quoted string will allow you to embed a single quote without an escape.
x = int(input("Enter an integer who's root value you need: "))
There are also triple-quoted strings """...""" or '''...''' both of which will allow you to embed unescaped single and double quotes, as well as new lines.  You don't need this here, but it is good to be aware of.
Input Validation
Your validation has holes.
At the first pair of prompts, enter "1" and "-1".  This causes you to enter the while e < 0: loop, where you can enter another pair, like "-1" and "2".  This will cause you to enter the while e %2 == 0 and x < 0: loop, where you can enter "0" and "0".
At this point, x is neither greater than or less than zero, so neither low nor high are assigned a value, causing an exception at ans = (high + low)/2.0
You want the earlier tests to be repeated for the new inputs.  This is easiest achieved with a single while loop around the input.
while True:
    x = int(input("Enter an integer who's root value you need: "))
    e = int(input("Enter an +ve integer for root value: "))

    if e < 0:
        print("I SAID +VE INTEGER FOR ROOT!")
    elif e % 2 == 0 and x < 0:
        print("-ve nos. can't have root value for even roots!")
    else:
        # The input is now good, exit the while-loop.
        break

if x==0:
    print("Zero power anything is zero!")
elif e==0:
    print("Anything power zero is one!")
else:
    epsilon = 0.0000001
    numGuesses = 0
    ...

Now, the input is requested.  If it fails either test, the while loop repeats, and all the validation checks are repeated with the new input.
Exceptions
If the user enters a non-integer value, int(...) will raise an ValueError exception.  You could be kind and capture that as well.
while True:
    try:
        x = int(input("Enter an integer who's root value you need: "))
        e = int(input("Enter an +ve integer for root value: "))

        if e < 0:
            print("I SAID +VE INTEGER FOR ROOT!")
        elif e % 2 == 0 and x < 0:
            print("-ve nos. can't have root value for even roots!")
        else:
            # The input is now good, exit the while-loop.
            break
    except ValueError:
        print("Only integer values are permitted.")

if x == 0:
    ...
...

Unnecessary conditionals
    if x>0:
        low = -x
    elif x<0:
        low = x
    if x>0:
        high = max(1.0,x)
    elif x<0:
        high = max(1.0,-x)

You are testing x>0, x<0, x>0, and x<0.  We can remove half of these, by combining the two if-elif statements:
    if x>0:
        low = -x
        high = max(1.0,x)
    elif x<0:
        low = x
        high = max(1.0,-x)

This is arguably clearer.  But the second test, x<0 is unnecessary.  We've already checked for x == 0 earlier, and now have just tested x>0.  The only other possibility is x < 0, so we can get away with just an else:
    if x>0:
        low = -x
        high = max(1.0,x)
    else:
        low = x
        high = max(1.0,-x)

PEP 8
The Style Guide for Python Code lists many conventions which Python programs should follow, for maximum readability by other Python programmers.

Binary operators should be surrounded by one space.  For instance, you should write x == 0, e % 2 == 0, x > 0 and (...) / 2.0 instead of x==0, e %2 == 0, x>0 and (...)/2.0.
snake_case should be used for function names and variables.  For example, num_guesses instead of numGuesses.
constants should be in UPPER_CASE.  For example, EPSILON = 0.000_000_1 instead of epsilon = 0.0000001 if the value never changes.
Use _ in long numerical constants to group digits for easier readability, as in above example.
Commas should be followed by a space.  For instances, max(1.0, x) instead of max(1.0,x).


Shortest distance from one word to another. eg: cat -> cot -> dot -> dog

I'm not sure about the exact complexity, but it is certainly huge! One-letter edits are fine to spell check one word given a large dictionary, but does not work if you only have a few words and the edit distance can be arbitrarily large. To look for close words in the dictionary, you should use the Levenshtein distance, as mentioned by ratchet freak. (Implementing the Levenshtein distance is a good idea.)

//        dictionary = new TreeSet<String>();
//        ....

Please don't post unused code here unless you want it reviewed too.

private CatToDog () { };

A default constructor is provided by Java already, only use that if you need to put something in there.

public static List<String> listWords(String startWord, String endWord) {
    final Queue<String> queue = new LinkedList<String>();
    final Map<String, String> backTrack = new HashMap<String, String>();
    queue.add(startWord);
    backTrack.put(startWord, null);

    while (!queue.isEmpty()) {
        String currentWord = queue.poll();
        if (currentWord.equals(endWord)) {
            return mapToList(backTrack, endWord);
        }
        addValidOneChangeWords(currentWord, queue, backTrack);
    }
    return Collections.EMPTY_LIST;
}

How do you know this is the shortest path? It feels a lot like depth first search, but I think you want to implement Dijkstra's algorithm instead to be able to notice shorter subpaths.

private static void addValidOneChangeWords(String startWord, Queue<String> queue, Map<String, String> backTrack) {
    for (int i = 0; i < startWord.length(); i++) {
        char[] endWord = startWord.toCharArray();
        for (char ch = 'a'; ch < 'z'; ch++) {
            endWord[i] = ch;
            String word = new String(endWord);
            if (validate(word, backTrack, startWord)) {
                queue.add(word);
                backTrack.put(word, startWord);
            }
        }
    }
}

You're only focusing on one-letter edits here, but what about deletions, insertions and even transpositions (dog -> dgo)? The Damerau-Levenshtein distance handles them.

And finally, mapToList is poorly named: I already know that the type change, I want to know about semantics! Something like editPath would be better.