VBA - faster way to list out files in a folder & subfolders

Variables
Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.
When you don't define your variable, VBA will declare it as a Variant, which are objects:
Performance. A variable you declare with the Object type is flexible enough to contain a reference to any object. However, when you invoke a method or property on such a variable, you always incur late binding (at run time). To force early binding (at compile time) and better performance, declare the variable with a specific class name, or cast it to the specific data type.
By not declaring variables, you could possibly be paying a penalty.
You didn't define folder or xDir in MainList.
Your variables in ListFilesInFolder are not really adhering to Standard VBA naming conventions. Why are these prefaced by x? There doesn't seem to be a reason. Also, using the underscore in a variable should be avoided unless it's a constant.

Dim folder_index As Integer

Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.
Referencing
Every time you use Cells or Range without an explicit reference, it is implicitly referencing the active sheet. You want Sheet1.Range etc
Be sure to avoid things like .Select - it just slows the code down by needing to fiddle with the spreadsheet while doing everything else behind the scenes. There's a good question on StackOverflow addressing this.
Take this for instance -

Cells(rowIndex, 6).Select
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=xFolder.Path,
TextToDisplay:=xFolder.Path

The same thing could just be written directly -
 ActiveSheet.Cells(rowIndex, 6).Hyperlinks.Add Address:=xFolder.Path, TextToDisplay:=xFolder.Path

    Cells(rowIndex, 8).Formula = file_type
    Cells(rowIndex, 9).Formula = xFile.Size
    Cells(rowIndex, 10).Formula = xFile.DateLastModified
    Cells(rowIndex, 11).Formula = file_extension

Why are you setting these values via a formula? You want to use the Cells().Value property when assigning a value.
What are you doing here -

rowIndex = Range("F65536").End(xlUp).Row + 1

Are you just getting the last row? There is a standard way to find lastRow and lastColumn. That post explains why.

Your If structure here -

    If file_extension = "pdf" Then
        file_type = "PDF"
    ElseIf Left(file_extension, 3) = "doc" Then
        file_type = "DOC"
    ElseIf Left(file_extension, 2) = "xl" Then
        file_type = "XLS"
    ElseIf Left(file_extension, 3) = "msg" Then
        file_type = "MSG"
    ElseIf Left(file_extension, 3) = "zip" Then
        file_type = "ZIP"
    ElseIf Left(file_extension, 3) = "ppt" Then
        file_type = "PPT"
    Else
        file_type = ""
    End If

Why are you doing this? First, if you need to only know those files, then you would use your Else value to filter out files that aren't what you need and then not print them. In which case a Select Case would work. But, in general, this seems unnecessary when you could just use something like
Dim fileName As String
fileName = Dir("C:\Temp" & "\*")
Do While Len(fileName) > 0
    'here fileName = filename.filetype
    fileName = Dir
Loop

You can avoid that entire if structure by just parsing your file name
    baseName = Left(fileName, Len(fileName)-4)
    extention = Right(fileName, 3)

Though in general you'd be better off parsing it like
    Dim delimiterPosition As Long
    delimiterPosition = InStr(1, fileName, ".")

But your call.

Another thing that's slow is writing to the sheet so many times. Instead, gather your data into an array, populate the array, and then write it all to the sheet. Since you're creating hyperlinks, you'd store that data in your array as well.


Clean and straightforward, very nice.

Minor suggestions:

If you do

from collections import defaultdict

...

self.data = defaultdict(list)

then you can make addResponse be just:

self.data[userInput].extend(response)

and likewise you can leave out the if block under the else clause in evaluate
The code:

f = open(self.saveFile, 'rb')
self.data = pickle.load(f)
f.close()

is slightly-better written as:

with open(self.saveFile, 'rb') as f:
    self.data = pickle.load(f)

so that if pickle.load() throws an exception, the file will still get closed.  Similar for the /SAVE code.


It is not a complete answer. Just some of my thoughts about this code.

C++

Do not compare integers of different signedness. Loop counters i and j in function strIsValid are declared as int, but they are compared with N which is unsigned int. It could lead to some problems. Make the counters unsigned.
Use strict compilation flags. The compiler would tell you about your signed/unsigned issue if you pass it -Wall key.

You should always achieve that the compiler will not display any diagnostic messages with the most strict compilation keys (-Wall, -Wextra, -pedantic, etc).

But you probably would not want to use Clang's -Weverything.
What happened with your main? Your main function looks very unnatural:

int main(int, char**)

If you do not need argc and argv, write just

int main()

About std::endl. You should avoid globally using std::endl. It is not the same as just \n. There is a good answer on SO about this topic.

And why are you printing std::endl twice?

std::cout << sudokuInstance.strIsValid() << std::endl << std::endl;

You do not have to explicitly return from main. You don't have to explicitly return 0; at the end of main.

Programming

Minimize the scope of local variables. You should always minimize the scope of local variables. In your case, for example, scope of the readnum variable can be reduced. Some reading about this topic.
The predicative function should return boolean. Your strIsValid is a predicative function. It means that this function checks something and returns either true or false. But you return string "YES" (true) or "NO" (false). You should return bool instead.
What the strIsValid function does? The name of this function doesn't answer the question.

Architecture

Validate user's input. At this time you do not validate user's input in ReadRows. What if I'll input a number which is greater than 9? Or less than 0? If I'll input too many numbers?..

In this case, you store invalid data into m_matrix. Then this invalid data will be used as arguments of std::bitset's flip() which will cause std::out_of_range.
Split row and cols validating and reading user's input. The Sudoku class should know nothing about reading user's input. The only thing that it should do is validate Sudoku columns and rows! This is called the Single Responsibility Principle (SRP).


Combining two indexOf and regex in to one

You were almost there. You can use pipe (a|b) to designate the regex to look for both a and b. With that knowledge your split is as easy as:

var name = 'Ron & Peggy Sue and Darin Douglass';
names = name.split(/\s(?:and|&)\s/ig);

EDIT: The syntax (?:...) is whats called non-capturing parens. These match the regex provided as '...' but it does not remember the matches. The problem with the simple /\s(and|&)\s/ig/ was that the words and and & would be matched. This new syntax 'matches' them but does not remember (i.e. report) them. Thanks to @cbojar for the pointer.

Also, there is no need to check for either delimiter in name. If none exist it will simply return a single-element array with name as its element.


Code Refactoring for Dynamic List in Angular 8

To handle such dynamic cases, you need to have dynamic code in both ts and html side.Take a look at this demo code which can be refactored furthur.

Here we have changed HTML

        <ng-container *ngFor="let page of pages">

                    {{page.title}}

        </ng-container>

and similarly we created a dynamic array

pages = [
  {
    id: 'menuPage',
    routing: '#',
    title: 'Menu Pages',
    showDOM: true
  },
  {
    id: 'aboutusPage',
    routing: '#',
    title: 'About US Pages',
    showDOM: true
  },
  {
    id: 'linkedInPage',
    routing: '#',
    title: 'LinkedIn Pages',
    showDOM: true
  }
]

It's still in a very crude format because your case will surely require more things from it. But this would help you to get the idea on how you should proceed.


ASP.NET Web API HTTP GET with optional parameters

Good layout and white space.

Although the logic works, I think it is very confusing, and not overly obvious.  At first glance, it the if statements are very confusing.  I would also rename the variables to have an Id or Code to the end of them to keep naming consistent.

I think this is a good place where you could incorporate the Specification Pattern.

public class StylesController : ApiController
{
    private Entities db = new Entities();

    public IEnumerable<Style> GetStyles(int divisionId = 0, int familyId = 0, int modelId = 0, int year = 0, string marketCode = "ANY")
    {
        var divisionIsAMatch = new DivisionIsAMatchSpecification(divisionId);
        var familyIsAMatch = new FamilyIsAMatchSpecification(familyId);
        var modelIsAMatch = new ModelIsAMatchSpecification(modelId);
        var yearIsAMatch = new YearIsAMatchSpecification(year);
        var marketIsAMatch = new MarketIsAMatchSpecification(marketCode);

        var q = db.Styles

        return q.Where(
                divisionIsAMatch
                .And(familyIsAMatch)
                .And(modelIsAMatch)
                .And(yearIsAMatch)
                .And(marketIsAMatch).IsSatisfiedBy
            ).Distinct()
           .OrderBy(s => s.Id);
    }
}

Where

internal class DivisionIsAMatchSpecification : Specification<Style>
{
    private readonly int _divisionId;

    public DivisionIsAMatchSpecification(int divisionId)
    {
        _divisionId = divisionId;
    }

    public bool IsSatisfiedBy(Style style)
    {
        if (_divisionId == 0)
        {
            return true;
        }

        return style.DivisionId == _divisionId;
    }
}

Just rinse and repeat for each of the specifications you need.  Of course, you will have to create the base classes for them too.

I haven't tested this, but I have used this pattern before, and it works really nicely.


Verify credit card number with Luhn's algorithm

the cs50.h that I have does not have a function: get_long_long(), so, for me, the code does not compile.  My compiler suggested: getlonglong()

which credit card company is, normally, contained in the left digits of the card number, not in the right digits. so the posted code logic is (probably) not correct.

The posted code fails to take into account the security code found on the back of the credit card.

Not all credit cards use 16 digits, but rather varies by which vendor is producing the card. So that assumption should not be in the code logic.

Suggest reading the digits as a string rather than as a long long int.  Remember that a character digit - '0' results in a value 0...9, so the conversion, digit by digit is easy.

OT: when compiling, always enable the warnings, then fix those warnings. ( for gcc, at a minimum use: -Wall -Wextra -Wconversion -pedantic -std=gnu11 ) Note other compilers use different options to produce the same results.

the posted code, when run through the compiler, results in the following:

gcc   -O1  -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11  -c "untitled1.c"  -I.

untitled1.c: In function ‘main’:

untitled1.c:17:17: warning: implicit declaration of function ‘get_long_long’; did you mean ‘GetLongLong’? [-Wimplicit-function-declaration]
      get_card = get_long_long(" Enter credit card: ");
                 ^~~~~~~~~~~~~
                 GetLongLong

untitled1.c:26:23: warning: conversion to ‘int’ from ‘long long int’ may alter its value [-Wconversion]
        sumofothers += card % 10;
                       ^~~~

untitled1.c:29:20: warning: conversion to ‘int’ from ‘long long int’ may alter its value [-Wconversion]
        otherdigs = card % 10;
                    ^~~~

untitled1.c:14:10: warning: unused variable ‘card_length’ [-Wunused-variable]
      int card_length;
          ^~~~~~~~~~~

Compilation finished successfully.

regarding: Compilation finished successfully  This only means the compiler provided some workaround for each of the problems it found in the code.  It does NOT mean the correct/expected code was produced.

Regarding you question about your suitability to become a programmer.

All programmers started some where, usually fumbling through many many programs before they started thinking of problems in terms of the needed code to solve the problem, so your doing quite well and will get better and better as you gain experience.

regarding:

I even don't know half of c syntax yet.

the C language is not that big.  besides what you have in the posted code, there are pointers and the while() and switch() statement.  Note: learning pointers can be a real pain.  After that there are many many standard C library functions. In Linux, in a 'terminal' window, type man functionName to learn all about a function.  The 'man' command is your best friend, After some 40+ years of programming, I still use that function regularly.


Encrypting a binary stream with RSA + AES in counter mode

Is there anything wrong with how I'm using RSA/OAEP or AES-256-CTR?

I wish I could answer that but I don't know enough crypto.
I hope somebody else can address this point for you.

  Is there anything I can optimize with the file format?

Nothing pops to mind. Same note as previous point.

  Any mistakes I'm not seeing?

Not really "mistakes", but I see a few minor things that could be improved.

Magic numbers

The chuck size 0xFFFF appears twice.
It would be better to put that in a variable,
perhaps CHUNK_SIZE at the package level.
That way if you ever change the value,
you only have to change in one place.

Duplicated logic

You do len(something).to_bytes(2, "big") twice.
I suppose both uses need to have consistent logic,
just like with magic numbers,
the best way to ensure consistency is to define things in one place,
rather than duplicating at two or more,
which risks inconsistent parallel edits in the future.

The approach

Once again, I'm no expert on this, but anyway...

  I'm using the SSH identity so that there's no passwords to worry about.

Makes perfect sense to me.
That is, the default private key should be protected by a passphrase,
normally managed by a key-chain manager,
and you can piggy-back on that.

  If the user's ssh private key is compromised, the data being encrypted is compromised as well.

That seems acceptable, because it's inevitable.


Best C# implementation of IndexOfAny(string, params string[])

Review

Don't use abbreviated variable names s, curAns and posAns; use self describing names: value, index and targetIndex instead.
The nullable int could be replaced with -1. This reads cleaner and allows you to bypass the final ?? operator in curAns ?? -1.
You can optimize the count curAns.Value + target.Length with adding -1 because we don't care about finding another match on the currently best found index.
You should exit early if no targets are specified

Refactored

public static int IndexOfAny2(this string value, params string[] targets)
{
    var index = -1;
    if (targets == null || targets.Length == 0) return index;

    foreach (var target in targets)
    {
        var targetIndex = value.IndexOf(target, 0,
            index > -1 ? index + target.Length - 1 : value.Length);

        if (targetIndex >= 0 && (index == -1 || targetIndex < index))
        {
            index = targetIndex;
            if (index == 0)
            {
                break;
            }
        }
    }

    return index;
}


Better Way to Show and Hide Items in Project

Assuming OPTION STRICT OFF (since I don't know the type of Grid.Cols.Item):

Private Sub ShowAlternateRows(show As Boolean)
    Dim grpShow =
    {
        splitter, lblAlternateActualPercent,
        lblAltEstimated, lblStaticAltEstimated,
        Grid.Cols.Item("Alternate Type"), Grid.Cols.Item("Alternate Start"),
        Grid.Cols.Item("Alternate End"),  Grid.Cols.Item("Alternate Hours"),
        Grid.Cols.Item("Alternate Burn")
    }
    Dim grpHide =
    {
        Grid.Cols.Item("Start Estimated"), Grid.Cols.Item("End Estimated"),
        Grid.Cols.Item("Start Actual"),    Grid.Cols.Item("End Actual"),
        Grid.Cols.Item("Estimated Hours"), Grid.Cols.Item("Actual Hours"),
        Grid.Cols.Item("Burn Estimated"),  Grid.Cols.Item("Object Count"),
        Grid.Cols.Item("Request Count"),   Grid.Cols.Item("Resource Count"),
        lblStaticActual,  lblActual,
        lblActualPercent, lblStaticEstimated,
        lblEstimated, lblStaticFiltered,
        lblFiltered,  lblFilteredPercent
    }
    For Each ctrl in grpShow
        ctrl.Visible = show
    Next
    For Each ctrl in grpHide
        ctrl.Visible = Not show
    Next
End Sub


few suggestions...

I would lose the jQuery part and stick to vanilla js for several reasons

jQuery's getScript doesn't add a script to the page like your vanilla example does, getScript actually uses eval to execute the code, which means any safe mode scripts will not be able to change any global state.
$ is used by lots of libraries, not just jQuery. There's a real high chance you're going to get a false positive if you're only checking for $ rather than jQuery.
The jQuery code is just unnessecary. Your vanilla code will always work, there is no benefit to using jQuery.

Don't forget to add your onload callback so scripts that use this to include other scripts can use those other scripts after they have loaded.
Declare your function. There is no benefit to doing window.whatever = function(){};. when you use function whatever(){} the function does not need to be defined at the top of the script, plus it's less bits.

Here's a function I wrote to include jQuery and stuff in userscripts, feel free to take it or parts of it.

function loadScripts(scripts, appendTo) {
  appendTo = appendTo || "body";
  return new Promise((done) => {
    (function recurse(i) {
      if (undefined === scripts[i]) return done();
      let src = scripts[i];
      let script = document.createElement('script');
      script.type = 'text/javascript';
      if (script.readyState) { //IE
        script.onreadystatechange = () => {
          if (script.readyState == 'loaded' || script.readyState == 'complete') {
            script.onreadystatechange = null;
            setTimeout(() => {
              recurse(++i);
            }, 1);
          }
        };
      } else { //Others
        script.onload = () => {
          setTimeout(() => {
            recurse(++i);
          }, 1);
        };
      }
      script.src = src;
      document.getElementsByTagName(appendTo)[0].appendChild(script);
    })(0);
  });
}

// Example usage
loadScripts(["https://code.jquery.com/jquery-2.2.4.min.js"]).then(()=>{
  $("body").append("loaded with jQuery");
});


I like the suggestions to let SQL do the foreign key cascading for you. Also, have you considered generating the id's outside the system (e.g. Guid.NewGuid()) and pushing them in?

Whatever the constraints and limitations you're working under, here's my take on a class hierarchy to handle your use case (via inheritance rather than encapsulation).

While it might be a bit over-designed for just handling Id's, the idea here is to create an object model upon which you can expand the application to arbitrary size.  The example also aims to minimize code repetition.

using System;
using System.Collections.Generic;
using System.Diagnostics;

class App_DosageSchedule
{
    public void Run()
    {
        var regimens = new List<Regimen>();
        var schedule = new Schedule(regimens);
        schedule.PreserveIds();
        schedule.Save();
    }
}

public abstract class Component
{
    public Guid Id { get; protected set; }
    public Guid OriginaId { get; protected set; }
    public void PreserveId()
    {
        OriginaId = Id;
        Debug.Write($"{GetType().Name} {Id}");
    }
}

public abstract class ComponentWithChildren : Component
{
    public void PreserveIds()
    {
        PreserveId();
        preserveChildIds();
    }

    protected abstract void preserveChildIds();
}

public class Schedule
{
    public List<Regimen> Regimens { get; private set; }
    public Schedule(List<Regimen> regimens) => Regimens = regimens;

    public void PreserveIds() => Regimens.ForEach(r => r.PreserveIds());

    public void Save()
    {
        ///write to SQL
    }
}

public class Regimen: ComponentWithChildren
{
    public List<RegimenPart> Parts { get; private set; }
    protected override void preserveChildIds() => Parts.ForEach(p => p.PreserveIds());
}

public class RegimenPart : ComponentWithChildren
{
    public List<DosageInstruction> Dosages{ get; private set; }
    protected override void preserveChildIds() => Dosages.ForEach(d => d.PreserveId());
}

public class DosageInstruction : Component
{
}


There is no need to store the entries in a vector. There is also no need for a nested loop.  This solution will run in O(n) time and O(1) space.

Technically, int is only guaranteed to hold up to 16 bits. Use long to ensure that you can accommodate the limits.

Also, please avoid using namespace std;. You can drop the useless cout<<"".

#include <algorithm>
#include <iostream>

int main() {
    long n, a, seq_len = 0, longest = 0;
    std::cin >> n;
    for (long prev_a = 0; n--; prev_a = a) {
        std::cin >> a;
        if (a <= 2 * prev_a) {
            seq_len++;
        } else {
            seq_len = 1;
        }
        longest = std::max(longest, seq_len);
    }
    std::cout << longest << '\n';
}


I have a problem with your code, in that the code seems unrelated to the problem statement you give at the top.

You say you are "working on a REST API, where I currently create python objects from the JSON data returned by the server. Though not all attributes of the created objects will be called upon in user code."

None of your code involves REST, or JSON. So while it's an interesting demonstration of certain parts of Python, it doesn't much address your issue.

IMO, the feasibility of what you are discussing is going to be determined by the nature and character of the JSON data, and the REST API. Parsing JSON is generally a one-shot deal. If you get JSON data like this:

'{ "name":"John", "age":31, "city":"New York" }'

how would it benefit you to "defer" the evaluation or construction of the age and city attributes? It would make far more sense to just parse and assign them all.

On the other hand, if your API returns a list of 1,000's of, say, homes with lat/long coordinates, and part of the object initialization process involves computing the distance from a given origin address, then perhaps delaying the computation or delaying object instantiation makes sense.

Please share with us the nature of the problem you're really trying to solve, and we'll be able to comment effectively on whether your proposed solution is a good idea.

EDIT:

I had a look at your linked code. The key was, I think, in the helpers.py:get_attribute() function.

You appear to be re-implementing the behavior of the __getattr__ or __getattribute__ dundermethods. I suggest that you look at implementing a simpler approach, where you store (say) '_attrname' as the lazy-evaluating function, and use __getattr__ to expand that value into 'attrname' when you fetch it the first time.

Since Python will check for obj.attrname and only call obj.__getattr__() if not found, this would provide the advantage of doing the subsequent lookups in C code rather than Python.


You are locking on a public field message which might cause a deadlock. If locking is needed, then do it on a private field.

private final Object SYNC_OBJECT = new Object();
...
synchronized(SYNC_OBJECT){
}

Your class extends Thread apparently, and the rule is : favor composition over inheritance.

  private Runnable runnable;

  public void startListening(){
    // use the runnable
  }

Moreover, you barely need to use threads, use Executors instead


Refactoring coordinates for Minecraft Pi buildings written in Python

You can put the different parts of the building in a list and then iterate through this list, using the values in the list.

I would propose this structure:

parts = [
    # x0  y0  z0    x1  y1  z1    block id          meta data
    (( 1,  0,  1), (19,  4, 19), (block.STONE_BRICK, 0)), # Main structure
    (( 2,  1,  2), (18,  3,  5), (block.AIR        , 0)), # Hollowing out main structure interior
    # ... the other parts
]

You can then use this loop to build the parts:

for (x0, y0, z0), (x1, y1, z1), (block, meta) in parts:
    mc.setBlocks(p.x + x0, p.y + y0, p.z + z0,
                 p.x + x1, p.y + y1, p.z + z1,
                 block, meta)

I would also advice you to follow a few style suggestions from PEP8, in this case I specifically mean that you should add empty lines after the imports:

import mcpi.minecraft as minecraft
import mcpi.block as block

mc = minecraft.Minecraft.create()
p = mc.player.getTilePos()

and that you should always add spaces around operators and after #:

mc.setBlocks(p.x+1, p.y, p.z+1 #...

to:

mc.setBlocks(p.x + 1, p.y, p.z + 1 # ...

This simply eases the reading process.


Project Euler Problem 8 - Largest product in a series

The easiest (but not computationally most efficient) way to solve this challenge is to use a brute-force algorithm, like you did. However you can write it a lot more succinctly when using more of the tools available in the Python standard library.

Use a generator expression to get all slices:

s = "..."
n = 13
slices = (s[i:i+n] for i in range(len(s) - n))
next(slices)
# '7316717653133'

map this string to an iterable of integers:

slices = (s[i:i+n] for i in range(len(s) - n))
list(map(int, next(slices)))
# [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3]

Use functools.reduce and operator.mul to get the product of this iterable:

from functools import reduce
from operator import mul

slices = (s[i:i+n] for i in range(len(s) - n))
reduce(mul, map(int, next(slices)))
# 5000940

Use max to...get the maximum of those:

slices = (s[i:i+n] for i in range(len(s) - n))
max(reduce(mul, map(int, slice)) for slice in slices)

Finally, wrap the code in functions and the calling code in a if __name__ == "__main__": guard:

from functools import reduce
from operator import mul

def prod(x):
    return reduce(mul, x)

def maximum_product(s, n):
    return max(prod(map(int, s[i:i+n])) for i in range(len(s) - n))

if __name__ == "__main__":
    s = "..."
    n = 13
    print(max_product(s, n))


Game of Life with Scala and Functional Programming

You're doing a lot of indexing, which is efficient in an Array, but indicates that you're thinking in small steps. As you get to know the Scala Standard Library you start thinking in larger chunks because it offers many ways to process data collections all at once.

I'll start at the bottom and work my way up.

*prettyPrint() - Testing for value 0 means that the prettyPrint() method knows about the underlying representation. If you test for CELL_DEAD and/or CELL_ALIVE then prettyPrint() should still work even if the grid implementation changes.

Here I chose to turn each row into a String and then println() it.

def prettyPrint(board: Board): Unit =
  board.grid
       .map(_.map(c => if (c == CELL_DEAD) " - " else " * ").mkString)
       .foreach(println)

*random() - Most Scala collections offer many different "builder" methods on the companion object. Here I use fill() to populate a 2-dimensional Array.

def random(rows:Int = DEFAULT_ROWS, columns:Int = DEFAULT_COLUMNS): Board =
  Board(Array.fill(rows,columns)(Random.nextInt(2)))

*isValid() - The Standard Library doesn't offer many collection methods with early termination, but forall() is one of them. It stops after the first false encountered.

Here I use -2 as a bit-mask to test the value of all bits except for the lowest.

private def isValid(grid: Array[Array[Int]]): Boolean =
  grid.forall(_.forall(n => (n & -2)==0))

*isJagged() - The exists() method is the compliment of forall(). It stops after the first true encountered.

private def isJagged(grid: Array[Array[Int]]): Boolean =
  grid.exists(_.length != grid.head.length)

*liveCount - Idiomatic Scala avoids mutable variables. In order to calculate the value of liveCount once, without any post-evaluation adjustments, we'll want a way to get all valid neighbor-cell indexes, also without any post-evaluation adjustments.

val liveCount = (for {
  x <- (0 max i-1) to (i+1 min rows-1)
  y <- (0 max j-1) to (j+1 min columns-1)
} yield grid(x)(y)).sum - cellValue

*evolve() - tabulate() is another one of those "builder" methods that appears to do everything you need, in this situation, all at once. In this case, because we're building a 2-D Array, tabulate() passes two arguments, the row index and the column index, to its lambda argument. And because the getNextCellState() method takes those same two arguments in the same order, they don't need to be explicitly specified.

def evolve(): Board = Board(Array.tabulate(rows,columns)(getNextCellState))

It's worth noting that you test if grid is null but you don't test to see if it's empty. Board.random(0,0) will throw a run-time error.


Naming for unit tests for controller to edit posts

Let me start out by saying that your test names are actually decent. You have already come to the conclusion that a good test name is one that can convey what is being tested without requiring someone to actually read the test.

As with many things, there are three important pieces of information about what a test is doing:

What is the thing being tested?
What is the input to the thing being tested? / In what context is the thing being tested?
What is the expected result?

If I see a test is failing and the name provides all this information, I can start formulating an idea of what the issue might be without doing more than seeing the test report.

There are a few different theories about how these three things should be ordered based on what the person feels is the focal point. But I prefer the order introduced by Roy Osherove, which matches the order I listed above. This provides us with:

[Test]
public void UnitOfWork_StateUnderTest_ExpectedBehavior()
{
  // ...
}

You don't have to be concerned with the name becoming very wordy. These are test cases and don't need to follow the same naming conventions you would use for methods in your production code. Artificially restricting yourself to HTTP verbs is preventing you from accurately describing the context that is being tested.

Additionally, try to stay away for using "correct value" as the description of the expected result. If I didn't write the code or tests, I likely don't know what the expected result is. More importantly, I won't know why that is the expected value.

Bellow are a few examples of your test case names converted into this style:

Edit_ReturnsCorrectView -> Edit_SomeSlugName_ViewNameEdit
Edit_Post_ReturnsCorrectView -> Edit_SomePost_ViewNameEdit
Edit_EditsPostContent -> Edit_PostWithAlteredContent_PostsContentUpdated

The use of Some is also taken from Roy. It is meant to indicate that there is nothing special about this value and a different arbitrary value should have the same result.

Other notes:

var actual = controller.Edit(model) as HttpNotFoundResult;
Assert.NotNull(actual);

and

var actual = controller.Edit(model);
Assert.NotNull(actual);

Are two very different things. The second case uniquely states that the result must not be null. However, the first case can fail the null check for two different reasons (the result is null or the result is of the wrong type). I suspect you are using this just ensure that the correct type is returned. If that is the case, you should be able to use the testing framework to verify the result is the correct type instead of potentially introducing a null.

Most of your tests are checking that some text field contains an expected sentence. This type of test can be very fragile. If the message displayed to the user is reworded or translated to a different language, the test would start failing. Do you actually care about the wording of the error message or is knowing that a HttpNotFoundResult instance was returned sufficient? Is there an IsError property you could test instead?

Your tests are using a mock repository that is filled with some sample data. There is nothing wrong with this. The one thing I would change would be to move all of the hard coded strings from the tests into the class that produces the mock as constants. This way, all of the data, is defined in one places and you don't have to edit this test class if a different test class requires the repository to contain something slightly different.


Is catching 'expected' exceptions that bad?

There are some exceptions I classify as "exogenous" exceptions. That is, they are exceptions that state "the world is not how you assumed it would be, and we can't do the thing you asked". The problem with exogenous exceptions is that the world is constantly changing. You think you're going to be able to access that file, and then someone changes its permissions from another process, or the tape drive catches on fire, or someone unplugs the router, or whatever, and oops, you can't access the file after all.

Exogenous exceptions are precisely the ones you should be catching; they indicate situations that are rare enough and dangerous enough to reasonably be exceptions, but common enough that you can have some clue ahead of time as to what they are, and reasonably recover from them.

The other class of exceptions you need to catch are the "vexing" exceptions. That is, the exceptions where someone wrote you a library that communicates with you via exceptions in non-exceptional circumstances. Ideally you should never write a library that requires the developer to catch a vexing exception; rather, expose tools that allow them to prevent the exception.

For example, suppose you write a method that turns a string into an int. You might say

public static int Parse(string s) { ... }

And if the string is malformed, it throws an exception. That is vexing! The developer might have a string where they don't know whether it is well-formed or not, because a user typed it in. The work they have to do to avoid the exception is equivalent to simply not calling the method in the first place. A better way to do it is:

public static bool IsWellFormedIntString(string s) { ... }
public static int Parse(string s) { ... }

or

public static int? Parse(string s) { ... }

or

public static bool TryParse(string s, out int result) { ... }

Or whatever; there are lots of ways to avoid the vexing exception situation.

More thoughts on this topic here:

http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx


You don't really need the EventHandler you can just replace
boardButtons[x, y].Click += click; withboardButtons[x, y].Click += btn_Click;. The += already works with delegates and kinda does that for you.
The only time you want to have this is when your method parameters have the same names as your class variables it appears that's not case for you, because I don't see any of the variables used without it.

Overall I really don't see what you can improve, you are simply assigning some values to some variables which really cant be speed up. Windows forms isn't really good for many controls at once that's it.


Here's a rewrite that clarifies and shortens the code.  A few of its advantages:

Removes nested if... else statements
Replaces vague variable name data with something more descriptive.
Names the concepts you are implicitly using in your code (eg, "checkedSave" means "check if it's valid to save the tag, then save it").  We also name the various conditions we are interested in: noSavedTags and tagAlreadyExists.
Avoid unnecessary indendation by not defining our callback saveOrRemoveTag inline.
Avoid verbose, unsightly for loop by using using map and indexOf to check if the tag already exists.
User ternary operator instead of if... else to express simple conditional expressions.

The new code:

function processTag(total, tag, associatedTicker) {

    TagFactory.retrieveTickerTags('onlyTags').then(saveOrRemoveTag);

    function saveOrRemoveTag(savedTags) {

        var noSavedTags = savedTags.length == 0;
        if (noSavedTags) { checkedSave(); return; }

        tagAlreadyExists() ? removeTag(tag, associatedTicker) : checkedSave();

        // the 3 lines above are really the entire function
        // everything below is just helper functions

        function checkedSave() {
            total < 3 ? saveTag(tag, associatedTicker)
                      : displayAlert('failure', 'Only 3 tags can be monitored at a time.');
        }

        function tagAlreadyExists() {
            var existingTermIds = savedTags.map(function(t) { return t.term_id });
            return existingTermIds.indexOf(tag.term_id) > -1;
        }
    }
}


Largest Palindrome Product - Project Euler #4

How about this small modification that could potentially make it faster if the answer is large enough.

function problem4(){
    let product = 1;
    let largest = 1;
    for(let i = 999; i>=100; i--){
        for(let j = 999; j>=i && i*j>largest; j--){
            product = i*j;
            if(("" + product) == ("" + product).split("").reverse().join("")){
                largest = Math.max(largest, product);}
}
    }
    return largest;
}
console.log(problem4());


Parsing a string as fast as possible that is using comma delimiters

There is no way to go under \$O(N)\$, just because you need to inspect the whole string.
The test if (stringToBeParsed.size() > 0) does not speed up the execution; you may safely omit it.
quoteTriggered = quoteTriggered ? false : true; is a long way to say quoteTriggered = !quoteTriggered.
In

    if (quoteTriggered) {
        temporary.push_back(stringToBeParsed[i]);
    }
    else {
        //place quote in to the temporary string and store it.
        temporary.push_back(stringToBeParsed[i]);
    }

the character is pushed anyway, so testing for quoteTriggered is pointless.
The remaining flow in the loop can be streamlined as:

    if quoteIsTriggered or char_is_not_separator
        push_to_temporary
    else
        substring is parsed

Upon the loop termination, you don't need to inspect the last character - if it was comma, temporary will be conveniently empty. Just push temporary and be done.

Putting it all together:

    void parse(vector<string>& inboundVector, const string& stringToBeParsed, bool quotesUsed, const char& charToSepBy)
    {
        string temporary = "";
        bool quoteTriggered = false;
        for (size_t i = 0; i < stringToBeParsed.size(); i++) {
            if (stringToBeParsed[i] == '\"' && quotesUsed) {
                quoteTriggered = !quoteTriggered;
                temporary.push_back(stringToBeParsed[i]);
                continue;
            }

            if (quoteTriggered || stringToBeParsed[i] != charToSepBy) {
                temporary.push_back(stringToBeParsed[i]);
            } else {
                inboundVector.push_back(temporary);
                temporary = "";
            }
        }

        inboundVector.push_back(temporary);
    }


Advent of Code 2019 Day 6 - Beginner Rust solution

Disclaimer: I don't know Rust.

I only have comments on performance.

To compute the number of orbits, it's unnecessary to compute paths, you could compute just the length of paths. That would reduce the space complexity to constant.

When computing the number of orbits, instead of going from each planet until the root, you could go from the root, traversing paths to every planet exactly once. That would reduce the time complexity to linear.

When computing the common ancestor from SAN and YOU, you only need to track part of the path segments, until a common point.


If you are going to distribute this assembly, you are effectively distributing that password.  Tools such as ILSpy can decompile the assembly and the database will be compromised.

The Windows Forms application shouldn't directly connect to a remote SQL server, there should be a service or API layer on the web sever to handle that.

If you need to authenticate / authorize a user, they will need to each have their own logins.

WinForms should act like a thin client, just sending requests to the server and receiving responses.

The web server should receive, authenticate, authorize and execute those requests on the database, and then send a response.


Time and Space Complexity of Leetcode Problem #31. Next Permutation

The number of calls indeed grows slower than \$n*n!\$. Its growth is only \$O(n!)\$. However, number of calls is not the only source of complexity.

Constructing arguments for the recursive call also takes time, and rem[:i] + rem[i + 1:] is on average linear in terms of n. The total complexity therefore is \$O(n*n!)\$, just as some people say.


Calculate the number of days passed from a given year

Your code scales poorly if there are many years between STARTING_YEAR and localDate.

Worse, if localDate occurs before the STARTING_YEAR, then your code behaves as if STARTING_YEAR is the same year as localDate, which is weird behavior.

To calculate the number of days between two dates, use DAYS.between().

import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;

…
long jdn = 1 + DAYS.between(LocalDate.ofYearDay(STARTING_YEAR, 1), localDate);

The 1 + is necessary because the convention when subtracting dates is inclusive-exclusive, whereas your code uses an inclusive-inclusive range.


Expressing multiple AND conditions in ruby

if [first_name, last_name, email, phone].all?(&:blank?)
  #do something
end

Caveat: While and/&& short-circuit the expression (that's it, only the needed operands are evaluated), an array evaluates all its items in advance. In your case it does not seem something to worry about (they seem cheap attributes to get), but if you ever need lazy evaluation and still want to use this approach, it's possible using procs, just slightly more verbose:

p = proc
if [p{first_name}, p{last_name}, p{email}, p{phone}].all? { |p| p.call.blank? }
  #do something
end


Network arithmetic, finding the next host for the given

I think what you've missed is the Enum instance for the IPv4 datatype from iproute. Using methods from Enum and Bounded you can eliminate the use of Data.Bits in your code.

Because IPv4 is Enum, your toInt method is just fromEnum :: (Enum a) => a -> Int. And similarly your fromInt is toEnum.

addressesInNetwork is largely the same logic, you just let someone else do all the work.

addressesInNetwork :: AddrRange IPv4 -> [IPv4]
addressesInNetwork range = takeWhile (`isMatchedTo` range) [low..]
    where
        (low, _) = addrRangePair range

I would use addrRangePair instead of the addr field accessor for two reasons. First, addr doesn't show up in the Haddock documentation for Data.IP which is a bit confusing. Second, on the off-chance that the author of iproute begins hiding the constructors of AddrRange from export (which is very common practice in Haskell so that library authors can change implementations without breaking users' code) you'll be safe from breaking changes.

Knowing the Enum instance and available Data.IP functions, you can now write a clearer version of successor. Unfortunately we have to be a bit cautious of bounds, Enum throws an exception if you try to get the successor of maxBound, but it's not too bad.

successor :: AddrRange IPv4 -> IPv4 -> Maybe IPv4
successor range ip | ip == maxBound              = Nothing
                   | succ ip `isMatchedTo` range = Just $ succ ip
                   | otherwise                   = Nothing

Notice I changed the type signature of your function to take an AddrRange instead of a mask length. This is kind of a separation of concerns issue, successor doesn't care about the mask length, what matters is whether an IP falls within the range it defines. So net24 would be implemented as—

net24 :: IPv4 -> Maybe IPv4
net24 ip = successor (makeAddrRange ip 24) ip

(That's kind of a strange name though, maybe successorMask24 instead?)


Ok, first, you've gone overboard. :D

You have a lot of regular expressions, but on first glance, I don't even know what they're for. What are they matching? It's best if you name them by putting them in const.

I see you have some personal touch on the code, like the ending parens being on the very last line. Makes the code look like CoffeeScript at first look. Anyways, code is for humans. Put some whitespace, break code into logically grouped lines, add some comments why you do things this way. One cannot really comprehend without tracing through (which is a sign of bad things to come).

Also, you're running this through Node, size doesn't matter there. If you run JS on a browser, there's what they call a minifier.

Also, variable names. Some make sense, some don't. l, v1, v0, pv, i80, they don't really tell me what they are. One terrible mistake devs often do is they assume the reader knows the context. Sure, pv means "previous value", but I only knew that because I know how reduce works. For someone that doesn't, that's a different story.

80% and 20% are hardcoded.


What's the right granularity for test-driven development?

Assuming you are speaking of Unit test driven development there are two things you need to get your head around first (or should I say, things I had to get my head around).
Both of them are actually about writing unit testable code (as compared to actually writing test first, etc)

Dependency injection: Avoid constucting objects inside other objects; instead, pass already constructed ones in through the constructor, or properties if appropriate. Look out for the new keyword and avoid it (exceptions apply, such as for classes that are pure data). Of course at some point objects need to be constructed. This should be done at high level classes (say somewhere near your console app's main()) at such a point that is simple enough to need no (unit) testing (since you won't be able to unit test it).
Dependency injection will allow you to inject mock or fake versions of the other classes you are dependent on.
Mocking/Stubbing/Faking/Test Doubles: Your unit tests should test only one thing, not all the things that one this is dependent on (they have their own tests). This allows you to localise (as in know the location of) any errors that show up. You can write your own stubs, but there are great libraries out there, and using them introduces a bit more consistency about how your tests work/look. NSubstitute is a good choice becuase it uses extension methods to be really easy to read.

As to the granularity for Unit Tests, it is as granular as you can go. That way you can localise errors (also the less granular/more integration test like, the harder is it to write tests, they become long). There is some argument about whether private methods should be tested or not. I would say it comes down to whether the private method is just a part of some public method (no) or it has its own well defined purpose (yes).

However, Unit tests driven development isn't the only kind: BDD (behavour driven development) focuses on Functional tests.


Splitting two ObservableCollections lightning fast

NotifyCollectionChangedEventArgs

You receive a NotifyCollectionChangedEventArgs, wich holds interesting data about the items that got added NewItems and removed OldItems from the collection. There is also an Action that defines how the collection got modified. Your changed handler is implemented as a NotifyCollectionChangedAction.Reset handler. It doesn't take into account the information from the event e.

var markers = ((IEnumerable<XfxMarker>) sender).ToList();

This means, you are checking all elements against the previously cached elements by the handler container class and manually verify which ones are added and which ones removed. Let's say filter is m => _map.MapBounds.Contains(m.CenterPoint):

 var markersToAdd = markers
    .Where(m => filter(m), out offScreen).Except(_oldMarkers,comparer);

and

var markersToRemove = _oldMarkers.Except(markers, comparer).Union(offScreen);

However, in most cases I presume the action to be Add or Remove. If this is the case, you already have the new and/or old elements. For instance, on Add:

var markersAddedInSource = e.NewItems.OfType<XfxMarker>();
var markersToAdd = markersAddedInSource.Where(filter);
var markersToRemove = markersAddedInSource.Except(markersToAdd);

Or using your own extension method:

var markersAddedInSource = e.NewItems.OfType<XfxMarker>();
var markersToAdd = markersAddedInSource.Where(filter, out var markersToRemove);

This saves you a couple of iterations on the source collection and allows you to only iterate on the changed elements.

MapMarkerComparer

I don't know the type of Latitude and Longitude, but consider checking equality on their source type rather than their ToString outcome.

x.CenterPoint.Latitude.ToString() == y.CenterPoint.Latitude.ToString()

In case you have issues with rounding or truncation (likely with float or double) you could round the values in the check.

x.CenterPoint.Latitude == y.CenterPoint.Latitude

Or you could use rounding:

Math.Round(x.CenterPoint.Latitude, precision)
    == Math.Round(y.CenterPoint.Latitude, precision)

Or you could guard against a tolerance threshold:

Math.Abs(x.CenterPoint.Latitude - y.CenterPoint.Latitude) < tolerance

IEnumerable<T> Where<T>

Consider changing the method signature to

public static ILookup<bool, T> Where<T>(this IEnumerable<T> input, Func<T, bool> predicate);

Or returning a Dictionary:

public static IDictionary<bool, IEnumerable<T>> Where<T>(
    this IEnumerable<T> input, Func<T, bool> predicate);

So you don't need to worry about a return value and an out-parameter. This pattern isn't used that much anymore and is mostly used to Try* operations.

You can get the items that matched the predicate:

var results = markers.Where(filter);
var matched = results[true];
var unmatched = results[false];

Considering renaming Where to avoid confusion with LINQ's Where method.


Generally "template vs polymorphism" is a complex topic. A simple rule of thumb: if it is high level (e.g., service you instantiate a few times) go virtual, if it is low level (you need to create a array of million these objects) then go template.

In your case... honestly your interface makes little sense to me - it is difficult to make any advices.

Say, is there any point in Bar class? It simply holds an int and serves no other purpose. Just having a common function and variable doesn't imply that you need to have a shared basic class. If it had virtual destructor then I could understand to a certain degree.

Why OpampBar is a class? It just holds two integers. Why not make it a struct with public members? Why make it unnecessarily complicated?

What is this BasicBar and what is this pins raw pointer? Is it a pointer to an array? A pointer to data that doesn't belong to it? Why not use std::vector<int>? There are lots of well made classes and functions in STL, why not utilize them?

What is the point of BarService? It is an interface class. I know of two purposes of interface classes: (1) To allow your program to switch between different derived classes easily. (2) Hide implementation. Is this the case? (Well, it can also serve as poor man's concept substitude... but I doubt that you use any SFINAE).

You need to watch and read tutorials on C++. There are plenty for free - just google it. There are lots of CppCon videos on YouTube where they explain additions to C++ (you gotta learn what was added in C++11/14 as well as what STL already had for 20 years).


Given that on some file systems a directory is simply a File with special attributes (or to put it another way a specialized file), does it really matter?  Unlink it if it can be unlinked if that is what you want to do.  If it can't be unlinked, why would you bother?  And why would you care what it is?  If you care what it is, then use is_a?  If the inode can be unlinked, unlink it.


Getting the distance between various classes of shapes

Quick Comments

Your Distance Interface is weird. It does not represent a distance, but an object having the ability to provide the distance between it, and some other object sharing the same interface.

The Shape interface is weird. The distance(int) and distance(int, int) are hacky and should go. They rely on implementation details of Point and Line.

The Shape should be an interface. It is currently a void Abstract class with no added value, it just prevents proper inheritance.

It looks weird to me to return ints for distances, given the propension of most metrics to return doubles due to frequent square roots being applied. However, I don't know your metrics so I'll stick with it.

Implementation using double-dispatch

If the number of classes is rather low, you could implement double-dispatch. Make the Shape interface have a distance(Shape) and every distanceTo(Foo), distanceTo(Bar), distanceTo(Fuzz) etc. like so:

public interface Shape {
    int distance(Shape shape);
    int distanceTo(Foo foo);
    int distanceTo(Bar bar);
    int distanceTo(Fuzz fuzz);
}

This way all Shape implementations will look like the following:

public class Foo implements Shape {
    public int distanceTo(Shape shape) {
        // You can copy-paste this method body on all other classes
        return shape.distanceTo(this); // This will call the strongly-typed methods below
    }
    public int distanceTo(Foo foo){
        // Specific implementation
    }
    public int distanceTo(Bar bar){
        // Specific implementation
    }
    public int distanceTo(Fuzz fuzz){
        // Specific implementation
    }
}

Here's how to use it:

Foo foo = new Foo();
Bar bar = new Bar();
int foobar = foo.distance(bar);
int foofoo = foo.distance(foo);

Very simple with just 3 classes. Can become a nightmare with 10+ classes.

You have to realize, that for every pair of Shapes, you'll need a dedicated distance method implementation. This means the number of distance(T t, U u) methods will grow rapidly.

From here on I will assume your network of Shape objects is sufficiently complex to warrant a dedicated structure to handle this in an externalized way.

The Problem

Basically, this boils down to the following:

  Given miscelaneous Objects, how to make it possible for any pair of Objects to interact (the interaction depends on the nature & implementation of those objects, and is not known in advance) and return something.

Obviously the interaction between two entities cannot be entirely contained in the entities themselves.

If it was, each Entity would have to know its distance to any other entity type (including unknown & unforeseen future Shape implementations), which means it would know every other Entity existence, and implementation details, and would have a dedicated distance implementation for each. That would:

Break Encapsulation - one Entity would have to know the detailed implementation of the other to perform the calculation)
Break extensibility - Adding an Foo entity would require adding a distance(Foo)method to every other Object

All those sins were commited in the double-dispatch implementation above.
So now we know the interaction implementation has to be externalized.

How to build an extensible externalized interaction function

Let's have a centralized distance functor (I'll make it a Singleton using an Enum, I assume you only have one set of interacting Shape implementations):

public enum DistanceEvaluator {
    INSTANCE;
    public final int distance(Shape shape1, Shape shape2){
         // Do something magic here
    }
}

Is this usable enough? I think you could very easily add the following default method (thanks, Java 8) to your Shape Interface:

public interface Shape {
    default int distance (Shape other){
        return DistanceEvaluator.INSTANCE.distance(this, other);
    }
}

Now aShape can calculate its distance to an other... provided the DistanceEvaluator holds an implementation for that particular pair of classes.

Enriching the DistanceEvaluator with implementations

A) You could implement everything in the DistanceEvaluator.

Then you just distribute the implementation using ìnstanceof and casting.
Advantages: The class combines all implementations, so can make good reuse of helper intermediate functions.
Disadvantage: the class could become enormous.

This should be used if the number of pairs is rather small with synergies (points, lines, segments, polygons).

B) You could use instanceofand cast the first argument (of type Foo)

Then simply forward the second argument (type Bar) to a FooDistanceCalculator class that knows how to compute distance to any Bar class.
Advantage: Implementations are grouped in a package, yet distributed between several classes.
Disadvantage: how to tell if distance(Foo, Bar) or distance(Bar, Foo) exists?

This should be used if the number of pairs becomes important and requires a (simple) structure.

C) You could make a completely dynamic mapping of distance functions.

Such mapping could be enriched at runtime, as a bonus.

Use the following Evaluator :

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public enum DistanceEvaluator {

    INSTANCE;

    /** Holds distance implementations */
    private final Map<Class<? extends  Shape>, Map<Class<? extends Shape>, BiFunction<? extends Shape, ? extends Shape, Integer>>> MAP = new HashMap<>();

    /** When a class has no matching map of distance functions */
    private final Map<Class<? extends Shape>, BiFunction<? extends  Shape, ? extends  Shape, Integer>> MISSING = new HashMap<>();

    /** When a pair has no matching distance function */
    private final BiFunction<? extends  Shape, ? extends  Shape, Integer> NO_FUNCTION = new BiFunction<Shape,Shape, Integer>() {
        @Override
        public Integer apply(Shape t, Shape u) {
            throw new IllegalArgumentException("Shapes " + t + " and " + u + " cannot calculate their respective distance");
        }
    };

    /**
     * Computes the distance between any pair of Shapes.
     * @param shape1 a shape
     * @param shape2 another shape
     * @throws IllegalArgumentException if the pair has no matching distance implementation
     * @return the distance between the two shapes
     */
    public <T extends Shape, U extends Shape> int distance(T shape1, U shape2) {
        @SuppressWarnings("unchecked")
        Class<T> shape1class = (Class<T>) shape1.getClass();
        @SuppressWarnings("unchecked")
        Class<U> shape2class = (Class<U>) shape2.getClass();
        @SuppressWarnings("unchecked")
        BiFunction<T,  U, Integer> func = (BiFunction<T, U, Integer>) MAP.getOrDefault(shape1class, MISSING).getOrDefault(shape2class, NO_FUNCTION);
        return func.apply(shape1, shape2);
    }

    /** Register a distance function for a pair of {@link Shape} sub-classes.
     * Note the function will be registered for both class pairs (a, b) and (b, a)
     * @param class1 first {@link Shape} Class
     * @param class2 second {@link Shape} Class
     * @param biFunction distance {@link BiFunction}
     */
    public <T extends Shape, U extends Shape> void register(Class<T> class1, Class<U> class2, BiFunction<T, U, Integer> biFunction) {
        Map<Class<? extends Shape>, BiFunction<? extends Shape, ? extends Shape, Integer>> intermediate1 = MAP.get(class1);
        if(intermediate1 == null){
            intermediate1 = new HashMap<>();
            MAP.put(class1, intermediate1);
        }
        intermediate1.put(class2, biFunction);

        // Symmetric
        Map<Class<? extends Shape>, BiFunction<? extends Shape, ? extends Shape, Integer>> intermediate2 = MAP.get(class2);
        if(intermediate2 == null){
            intermediate2 = new HashMap<>();
            MAP.put(class2, intermediate2);
        }
        intermediate2.put(class1, biFunction);
    }
}

Here are a few Shape implementations. Note those implementations inject their required distance evaluators when their classes are loaded.

A Point class:

public class Point implements Shape{
    static {
        DistanceEvaluator.INSTANCE.register(Point.class, Point.class, new BiFunction<Point, Point, Integer>() {
            @Override
            public Integer apply(Point t, Point u) {
                return 0; // Calculations here
            }
        });
        DistanceEvaluator.INSTANCE.register(Point.class, Line.class, new BiFunction<Point, Line, Integer>() {
            @Override
            public Integer apply(Point t, Line u) {
                return 0; // Calculations here
            }
        });
    }
    // Class implementation details, up to you
}

A Line class:

public class Line implements Shape {
    static {
        DistanceEvaluator.INSTANCE.register(Line.class, Line.class, new BiFunction<Line, Line, Integer>() {
            @Override
            public Integer apply(Line t, Line u) {
                return 0; // Calculations here
            }
        });
    }
    // Class implementation details, up to you
}

With this scheme, it becomes possible to not implement all distance functions. This might or might not be a good feature for you.


I'd greatly appreciate all sorts of tips for improving not only the
  solution itself but also the style to be more Go-ish.

For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.

Writing code is a process of stepwise refinement.

Go was designed for simplicity, readability, and performance.

I ran your benchmark on your complicated code:

$ go version
go version devel +4d5bb9c609 Fri Dec 20 23:07:52 2019 +0000 linux/amd64
$

$ go test *.go -bench=. -benchmem -run=!
BenchmarkScore-4        9438        126800 ns/op   67275 B/op   512 allocs/op

It seems very slow.

I ran your benchmark on leaf bebop's complicated code:

$ go test *.go -bench=. -benchmem -run=!
BenchmarkScore-4     1263572           936 ns/op      16 B/op     2 allocs/op

It is much better, but still slow.

I ran your benchmark on my simpler, "Go-ish" code:

$ go test *.go -bench=. -benchmem -run=!
BenchmarkScore-4    16844323            69.5 ns/op     0 B/op     0 allocs/op

// Score returns the sum of the Scrabble tile points
// for the letters in a word.
func Score(word string) int {
    var score int
    for i := 0; i < len(word); i++ {
        score += int(points[word[i]])
    }
    return score
}

var points = [256]byte{
    'A': 1, 'a': 1,
        ...
    'Z': 10, 'z': 10,
}

My code is around 1,819 times faster than your code and it makes no allocations.

My code is around 13 times faster than leaf bebop's code and it makes no allocations.

An array is a simple, fast, random access data structure. The points array is constructed once at compile time.

scrabble.go:

/*
Package scrabble deals with proper word score counting

Scrabble Rules | Official Word Game Rules | Board Games
https://scrabble.hasbro.com/en-us/rules
*/

package scrabble

// Score returns the sum of the Scrabble tile points
// for the letters in a word.
func Score(word string) int {
    var score int
    for i := 0; i < len(word); i++ {
        score += int(points[word[i]])
    }
    return score
}

var points = [256]byte{
    ' ': 0, // blank
    'A': 1, 'a': 1,
    'E': 1, 'e': 1,
    'I': 1, 'i': 1,
    'O': 1, 'o': 1,
    'U': 1, 'u': 1,
    'L': 1, 'l': 1,
    'N': 1, 'n': 1,
    'R': 1, 'r': 1,
    'S': 1, 's': 1,
    'T': 1, 't': 1,
    'D': 2, 'd': 2,
    'G': 2, 'g': 2,
    'B': 3, 'b': 3,
    'C': 3, 'c': 3,
    'M': 3, 'm': 3,
    'P': 3, 'p': 3,
    'F': 4, 'f': 4,
    'H': 4, 'h': 4,
    'V': 4, 'v': 4,
    'W': 4, 'w': 4,
    'Y': 4, 'y': 4,
    'K': 5, 'k': 5,
    'J': 8, 'j': 8,
    'X': 8, 'x': 8,
    'Q': 10, 'q': 10,
    'Z': 10, 'z': 10,
}

  Program testing can be a very effective way to show the presence of
  bugs, but it is hopelessly inadequate for showing their absence.

  A convincing demonstration of correctness being impossible as long as
  the mechanism is regarded as a black box, our only hope lies in not
  regarding the mechanism as a black box.

  Edsger W. Dijkstra

Your tests don't test for control characters, punctuation, numbers, and non-ASCII characters.

Your complex code and data structures look like a black box to your tests.

Locate a definitive description of the Scrabble tile points and scoring system:

Scrabble Rules | Official Word Game Rules | Board Games

Encode the tile points system in readable, array form. Like the definition, uppercase and lowercase letters and their points are on the same line. The lines are in the same order as the definition. Carefully match the array to the definition and the definition to the array, left-to-right then right-to-left and top-to-bottom then bottom-to-top. The Go compiler will check that the keys are unique.

Consider some automated tests, which can also serve as regression tests.

For the points array, compute sum and count verification totals, listing the elements in the same order as the definition, matching array to definition and definition to array, right-to-left, and left-to right.

We are now be able to conclude, if not prove, that the points array is correct.

The Score function, by design is simple and readable.

// Score returns the sum of the Scrabble tile points
// for the letters in a word.
func Score(word string) int {
    var score int
    for i := 0; i < len(word); i++ {
        score += int(points[word[i]])
    }
    return score
}

For a comprehensive Score function test, use the definition of points encoding, with the tests in the same form as the definition for easy comparison.

Add the test written while developing the algorithm for the Score function. It includes special, unusual, and error cases.

peterso_test.go:

package scrabble

import (
    "strings"
    "testing"
)

/*
Scrabble Rules | Official Word Game Rules | Board Games
https://scrabble.hasbro.com/en-us/rules
    (0 point)-blank
    (1 point)-A, E, I, O, U, L, N, S, T, R
    (2 points)-D, G
    (3 points)-B, C, M, P
    (4 points)-F, H, V, W, Y
    (5 points)-K
    (8 points)- J, X
    (10 points)-Q, Z
*/

func TestScores(t *testing.T) {
    var (
        sum   = 2 * (0*1 + 1*10 + 2*2 + 3*4 + 4*5 + 5*1 + 8*2 + 10*2)
        count = int(('z' - 'a' + 1) + ('Z' - 'A' + 1))
    )

    as, ac := 0, 0 // all
    us, uc := 0, 0 // upper
    ls, lc := 0, 0 // lower
    for i := 0; i < len(points); i++ {
        score := int(points[i])
        if score != 0 {
            as += score
            ac++
            if 'A' <= i && i <= 'Z' {
                us += score
                uc++
            }
            if 'a' <= i && i <= 'z' {
                ls += score
                lc++
            }
        }
    }
    if as != sum {
        t.Errorf("all sum: got %d; want %d", as, sum)
    }
    if ac != count {
        t.Errorf("all count: got %d; want %d", ac, count)
    }
    if 2*ls != sum {
        t.Errorf("lower sum: got %d; want %d", 2*ls, sum)
    }
    if 2*lc != count {
        t.Errorf("lower count: got %d; want %d", 2*lc, count)
    }
    if 2*us != sum {
        t.Errorf("upper sum: got %d; want %d", 2*us, sum)
    }
    if 2*uc != count {
        t.Errorf("upper count: got %d; want %d", 2*uc, count)
    }
}

func TestScore2(t *testing.T) {
    var tests1 = []struct {
        word   string
        points int
    }{
        {" ", 0},          // (0 point)-blank
        {"AEIOULNSTR", 1}, // (1 point)-A, E, I, O, U, L, N, S, T, R
        {"DG", 2},         // (2 points)-D, G
        {"BCMP", 3},       // (3 points)-B, C, M, P
        {"FHVWY", 4},      // (4 points)-F, H, V, W, Y
        {"K", 5},          // (5 points)-K
        {"JX", 8},         // (8 points)- J, X
        {"QZ", 10},        // (10 points)-Q, Z
    }
    for _, tt := range tests1 {
        word := tt.word
        word += strings.ToUpper(tt.word)
        word += strings.ToLower(tt.word)
        got := Score(word)
        score := 3 * (len(tt.word) * tt.points)
        if got != score {
            t.Errorf("Score(%s) : got %d; want %d", word, got, score)
        }
    }

    var tests2 = []struct {
        word  string
        score int
    }{
        {"", 0},
        {"Go", 3},
        {"Scrabble", 14},
        {"09\t\r\n.?!", 0},
        {"Français", 10},
        {"羅生門", 0}, // Rashōmon
    }
    for _, tt := range tests2 {
        got := Score(tt.word)
        if got != tt.score {
            t.Errorf("Score(%s) : got %d; want %d", tt.word, got, tt.score)
        }
    }
}

  with gofmt I'm not sure I use it correctly, as it simply prints out
  the code to stdout.

For most purposes, use the go fmt command.

  Gofmt (reformat) package sources

Usage:

go fmt [-n] [-x] [packages]

  Fmt runs the command 'gofmt -l -w' on the packages named by the import
  paths. It prints the names of the files that are modified.


Your code is correct - it should work nicely.

The first thing that I would improve on is the // runtime-safe get calls. This is an anti-pattern in Scala and is generally discouraged. In this case you can use pattern matchings powerful extractors to get the value the Option is storing:

case (Some(a), Some(b)) => Some(f(a, b))

But instead of pattern matching the most elegant way to solve this problem is to use for comprehensions. It is functionally the same as your code:

override def map2[A, B, C](fa: Option[A], fb: Option[B])(f: (A, B) => C): Option[C] = {
  for {
    a <- fa
    b <- fb
  } yield f(a, b)
}

Since Option is essentially a collection with either zero or one element it can be used in for-comprehensions. The variable a will only be populated if fa is a Some. If either is None then nothing will be yielded and the result is None.


How skinny should controllers be, how fat should models be in CakePHP?

It's totally egilable to write shorthand-find functions. This way the controller is not depended of the model's parameters. I tend to go that far, that I don't use any fields directly in my controllers (and thus, not using find in controllers at all).
You could save a variable by defining the array in your find-call aswell ;).


I would do this by iterating through the tokens and keeping a stack of the current state (signStack) as parenthesis are opened.

function newSign(current, prev) {
  //treat blank as positive
  const currentNegative = current[0] == '-';
  const prevNegative    = prev[0]    == '-';
  return currentNegative == prevNegative ? '+' : '-';
}

function solve(input) {
  let signStack   = ['+']; // start by assuming positive
  let currentSign = '';

  const result = input.replace(/(\+|\-)\(?|\)|\w/g, (match) => {
    if (match==')') { // close parenthesis
      signStack.shift();
      currentSign = signStack[0];
      return '';
    }

    if (match[0] != '+' && match[0] != '-') { // variable
      const  sign = currentSign;
      currentSign = signStack[0];;
      return sign + match;
    }

    const sign     = newSign(match, currentSign);
    currentSign    = sign;
    if (match.length > 1) {// open parenthesis
      signStack.unshift(sign);
    }
    return '';
  });

  if (signStack.length != 1)
    throw 'unbalanced parenthesis';

  return result;
}

function test(input, expected) {
  const result = solve(input);
  if (result != expected)
    console.log(`Failed: input=${input}, result=${result}, expected=${expected}`);
}

test("x-(y+z)",        "x-y-z");
test("x-(y-z)",        "x-y+z");
test("u-(v-w-(x+y))-z", "u-v+w+x+y-z");
test("x-(-y-z)",        "x+y+z");


A toy example of the concurrent stack via atomic variables and CAS pattern

Naming
My immediate reaction is that without a pop (or something equivalent) it's not really a stack. Especially given the item below about exposing the implementation details, from a client's viewpoint it's really a linked list that supports only a couple of operations: adding nodes to the beginning, getting the length, and (by knowing the implementation) traversing the list.
Exposing Internal Details
As it stands now, it seems to rely on client code to realize that it's implemented as a linked-list, so access to elements other than the top require client code to use peek to get a pointer to the top element, and then traverse the nodes of the linked list to get to the rest of the elements.
Avoiding Race Conditions
I'd also question (to at least some degree) inclusion of length in the interface. In a multi-threaded environment, almost all possible uses of length are practically guaranteed to introduce race conditions--by the time you actually try to use a length you've read, the length may have changed, so you're using obsolete information.
It can (at least sort of) make some sense to use a length for things like logging, simply to give the user at least some notion of whether the stack is (for example) growing constantly (but in this case, that's pretty much a given, since you've omitted a pop from its interface).
Side Note
It's not immediately apparent whether you're thinking of Runner as part of the Stack itself, or an ancillary class you included to demonstrate/test the actual Stack. At least for now, I've treated it as ancillary, so it shows how the Stack is used, but I haven't really tried to review it in itself.


There are a few things that can be improved here.

In Python, using a _ before a class variable denotes a protected member of the class, I don't think that was your intention so you can just make it the following without the preceding _'s in __init__ like this, and throughout the program.

self.mass = mass
self.radius = radius
self.position = position
self.velocity = velocity
self.vafter = np.copy(velocity) # temp storage for velocity of next step

Your compute_coil method is mostly just naming variables.

Since we have alot of lines like this,

m1 = self.mass
m2 = ball.mass

we can re-write them on one line like this,

m1, m2 = self.mass, ball.mass

That would change the first part of your compute_coll method to,

m1, m2 = self.mass, ball.mass
r1, r2 = self.radius, ball.radius
v1, v2 = self.velocity, ball.velocity
x1, x2 = self.position, ball.position
di = x2-x1

which I feel reduces a lot of unnecessary clutter.
In your compute_coll method you have a little more tidying that can be done.

According to PEP 8,

v1-v2,di

should be,

v1-v2, di

with whitespace after the ,. You also do this in a few of your other methods.
You miss some more whitespace in your step1 function around the != operator.

if i!=j:

should be,

if i != j:

In your function init_list(N), your argument N is uppercase. According to PEP 8 argument names should be lowercase.


You are on the right track in several respects -- for example, putting all
behavior/actions inside of functions. That said, constants are fine at the top
level, and one advantage of putting them there is allowing the reader to
focus on the algorithm without the visual heaviness of a big data structure.
Don't force your user to worry about capitalization: lowercase the data and
then use Python's built-in string methods to capitalize geographic names for
presentation to the user.
Opinions vary on this, but I recommend using natural language as the primary
(not sole) guide when picking variables: in most contexts, for example,
capitals is a better name than stateDict; states better than
statesList. Sometimes a data-type suffix can disambiguate names, but
don't make that your first impulse.
The random library includes a choice() function, so you do not
need MIN, MAX.
I recommend less chatty messages to users in interactive programs. Once
the user understands the basics (computer prints state, user types capital),
they do not require verbose instructions. Ruthless text cutting is
a virtue in these situations.
Nest the main() call under the conditional shown below. This mechanism will
make your scripts amenable to importing, easier debugging, and
automated testing should you ever need it.
Whenever you find yourself creating multiple closely related variables
(correct and incorrect), consider whether you can unify them under a data
structure. Sometimes taking that approach will suggest further refactoring to
simplify code (for example, by reducing if-else branching). In the illustration
below, I started just by focusing on unifying the correct/incorrect tallies,
but that inspired other simplifications in the reporting of overall results.
import random

# Your dict, but lowercase.
capitals = {
    'alabama': 'montgomery',
    'alaska': 'juneau',
    ...
}

def main():
    # Setup.
    states = tuple(capitals)
    tally = {True: 0, False: 0}
    results = {True: 'Correct', False: 'Incorrect'}
    result = ''

    # Quiz loop.
    print('State capitals quiz:')
    while True:

        # Get user reply.
        state = random.choice(states)
        ans = input(f'{result}{state.title()}? ').lower()
        if ans in ('', 'q', 'quit'):
            break

        # Tally result.
        res = ans == capitals[state]
        tally[res] += 1
        result = results[res] + '. '

    # Print overall results.
    fmt = 'Results:\n- {}: {}\n- {}: {}'
    args = (results[True], tally[True], results[False], tally[False])
    print(fmt.format(*args))

if __name__ == '__main__':
    main()

Finally, people who take quizzes generally want to see the right answers.
You could print the correct result immediately in response to a wrong reply. Or
you could keep track of all states with bad replies and print correct answers
at the end.


Which class should have code for caching?

I recommend a separate Cache class that handles storing and retrieving from the cache.  The argument for a separate class is simple: you want each class to have a narrow purpose. If you choose a particular cache driver/server today, but change your mind in a year, you should be able to change just one class -- the one that interacts with the driver -- to update your code. Start with this basic framework for a Cache class:

//reference to the only allowed instance of this class. It's private so
//outside scripts and objects cannot see it
private static $instance=null;

//private constructor will prevent outside code from instantiating objects.
private function __construct(){/*connect to the cache driver*/}
private function __destruct(){/*disconnect from cache driver*/}

//only way to get an instance (since constructor is private). We return
//the previously created instance instead of making a new one. As a result
//there is at most one instance of the class in memory.  This is a singleton.
public static function getInstance(){
    if(!self::$instance) self::$instance = new Cache();
    return self::$instance;
}

//takes key, returns cached object, or FALSE if not found
public function get(string $cache_key){}

//saves $value to the cache under $cache_key. Overwrite previous value
public function set(string $cache_key, mixed $value){}

//deletes whatever is stored under $cache_key, if it exists
public function delete(string $cache_key)

//connect to and disconnect from the cache server
private function connect(){}
private function disconnect(){}

Notice that this is a singleton . There can never be more than one Cache object in memory. This is to ensure that all your scripts are storing and retrieving data to and from the same cache.  You would use the static method getInstance to grab a reference to the cache. Since the method is static, you call it on the class itself (Cache::getInstance()).

Once you have this in place, when you need a value that may be cached, you check for it in the cache first. For instance, suppose you previously saved the sport type data under cache key "sportsType_123". In your controller's edit function,  change your code from:

$SportsType = $this->sportstype->Get($SportsTypeID);

To:

$SportsType = Cache::getInstance()->get('sportsType_'.$SportsTypeID)? :
              $this->sportstype->Get($SportsTypeID);

Likewise when you're saving data that you want cached, cache it after you've successfully saved to the DB. I've been using Memcache as my PHP cache driver with no problem, but Memcached may be even more feature rich. Because I have a Cache class as I described above, it wouldn't be too hard to switch. The rest of my scripts don't care because they interact with my Cache class, never directly with the cache driver.

  Am I writing bad or very bad code? Can you please suggest good ways to
  improve it?

I have a couple of concerns with your code:

From what you posted, I cannot tell whether you're sanitizing the data before saving it to the database. Hopefully you're not just inserting strings you received from the client into your DB queries (this would expose you to SQL Injection attacks), but are instead using parameterized queries.
How do you handle a SELECT query not returning any result? For instance when I look at SportsTypeDb::Get, you call ->first() on your results without checking whether there is such a result. I'm not familiar with Laravel so maybe it handles this for you? Be sure to test how your script handles getting a non-existent resource.
In your SportsTypeBL class, you create a new instance of SportsTypeDb every time a method is called. This is a waste because you will have a lot of parallel connections to your database that you never close and all those objects must be kept in memory. A better approach would be to instantiate a new SportsTypeDb() in the constructor of SportsTypeBL, assign it to a class variable, and use it for all DB queries. Then in the __destruct() function of SportsTypeBL, disconnect from the DB.


PHP/MySQL to delete data from 4 different tables at once

Basically there are three vectors of improvement:

of course you can make your queries optimal, avoiding a loop
also, I would suggest to optimize the the process of executing the query, as it is evident that each query takes too much code to write
you should never put a single variable directly in the query, but always use a prepared statement instead.

To solve the first problem, you can always use a JOIN. Yes, DELETE queries support JOINs as well as SELECT ones. So it goes:

DELETE c.* FROM classes c, schedules s WHERE c.scheduleid=s.id AND s.userid = ?

To solve the second one would propose to use PDO (which can solve the third one as well) as it lets you to run a query in one line:

$pdo->prepare("DELETE FROM users WHERE userid = ?")->execute([$userid]);

So the overall code would be

$sql = "DELETE c.* FROM classes c, schedules s WHERE c.scheduleid=s.scheduleid AND s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE c.* FROM schools sc, schedules s WHERE sc.scheduleid=s.scheduleid AND s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE FROM schedules WHERE s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE FROM users WHERE s.userid = ?";
$pdo->prepare($sql)->execute([$userid]);

As long as you are connecting to PDO properly, this code will report errors automatically, without a single extra line of code!

  Should I add the userid field to the other tables?

Quite contrary, you should NOT add such a field, keeping your database structure as normalized as possible


As suggested by @JoeWallis in the comments, you could use the "fast" TColor constructor. This let you simplify the color creation by not having to manually deal with the color number:

import ROOT

class Color(int):
    """Create a new ROOT.TColor object with an associated index"""
    __slots__ = ["object"]

    def __new__(cls, r, g, b, a=1.0):
        """Constructor. r, g, b and a are in [0, 1]"""
        # Explicitly use floats here to disambiguate
        # between the two TColor constructors
        color = ROOT.TColor(float(r), float(g), float(b), float(a))
        self = int.__new__(cls, color.GetNumber())
        self.object = color
        return self

Or you could use plain ROOT.TColor and use color.GetNumber() whenever you need an int instead of a TColor. An other, untested (and probably not working), would be to define an __int__ method:

class Color(ROOT.TColor):
    def __int__(self):
        return self.GetNumber()

If SetLineColor and others accept that, this would be the best alternative.

Depending on the need, it may also be a good idea to define properties to get/set color components, such as:

    @property
    def red(self):
        return self.GetRed()

    @red.setter
    def red(self, red_value):
        self.SetRGB(red_value, self.green, self.blue)

Change self to self.object if you use the int subclass.

Now, as regard to style, you define a bunch of constants whose names should be UPPER_SNAKE_CASE. And I would probably use red, green, blue and alpha instead of one letter variable names, even though in "color" context, these letters are pretty obvious.


Stack implementation using vectors with no overflow version 1.0

What is A?  You shouldn't use single-character variables as they're very ambiguous.  You may know what it's for, but it doesn't mean anyone else does.
Any member function that doesn't modify any data members should be const.

One example is topElement():

int Mystack::topElement() const
{
    std::cout << "The top element is : " << A[top];
    return A[top];
}

This class performs memory allocation, but you never deallocate it, making it one big memory leak for anyone using it.

You should have a destructor that uses delete to free this memory:

Mystack::~Mystack()
{
    delete[] A;
}

With a destructor in place, you should also have a copy constructor and assignment operator defined, as per the Rule of Three.  It is especially important to define your own since the default ones perform a shallow copy, which shouldn't be done when you have pointers as data members. Those will instead be copied instead of the data they point to, which will mess up your data.
Although pop() "reports" underflows, it can still break since it doesn't handle errors properly.  Specifically, it'll return 0 if the stack is already empty.  Since 0 is a value, the calling code can store it like normal.  So, pop() can be called repeatedly and it will always return this value.

What you should do is have the function return void so that it won't have to return anything if the stack is empty.  This is also how it's done in the standard library, in case you weren't aware.
Something like this shouldn't be displaying simple output, though it may be okay if you're just testing the functions.  Otherwise, it should be done in main(), while the bool values should determine which messages should be displayed.
One case where output is really not needed is in isEmpty().  A simple function like this can just be done in one line:

return (top == -1);

It's important to know that main() should return int.  Some compilers allow it to return void, but this isn't allowed by the standard.  Regardless, you should change it to return int.
Be aware that system("PAUSE") is Windows-specific thus non-portable.  If you'd like to do a similar pause that is portable, use something like std::cin.get().
If you'd like for this stack class to handle types other than int, then consider using templates.  There are many resources on this, and it should be worthwhile to learn about this.


Change your connection string from host=localhost to host=127.0.0.1, for some reason PDO is slow at resolving the host name, just when using PDO always use the IP address of the server.

Also why are you fetching one row at a time when you need 50?


Displaying an item from an array on page load

It's a good start, but there are some improvements that can be made.

For instance, this chunk:

if($scope.favourites === undefined) {
  $scope.favourites = [];
  favouriteToggle(exercise)
} else {
  favouriteToggle(exercise);
};

Could be written as:

if($scope.favourites === undefined) {
  $scope.favourites = [];
}

favouriteToggle(exercise);

Since you always want to call the favouriteToggle function.

But you can go further, and treat undefined as simply another false'y value like false, null, empty string, and numeric zero:

if(!$scope.favourites) {
  $scope.favourites = [];
}
// ...

Which is synonymous with a common set-default-value-if-false'y idiom:

$scope.favourites = $scope.favourites || [];
// ...

You might also see it written as:

$scope.favourites || ($scope.favourites = []);
// ...

The three code blocks above are all equivalent: If $scope.favourites is false'y, set it to [].

Since it's a simple one-liner, you can just move it out of the function entirely, and then just skip the entire function:

$scope.favourites = $localStorage.favourites || [];

function $scope.favouriteToggle(exercise) {
  if($scope.favourites.indexOf(exercise.exerciseName) == -1) {
      $scope.favourites.push(exercise.exerciseName);
  } else {
      $scope.favourites.splice($scope.favourites.indexOf(exercise.exerciseName),1);
  };
   $localStorage.favourites = $scope.favourites;
};

As for favouriteToggle, I'd name it toggleFavourite instead, just because it sounds more natural. But let's make it little more descriptive, and call it toggleExerciseFavourite.

Secondly, instead of finding the index twice with indexOf, it'd be easier to find it once, and store the result:

$scope.toggleExerciseFavourite = function(exercise) {
  var index = $scope.favourites.indexOf(exercise.exerciseName);

  if(index === -1) {
    $scope.favourites.push(exercise);
  } else {
    $scope.favourites.splice(index, 1);
  }

  $localStorage.favourites = $scope.favourites;
};

Lastly, I don't know Angular, I'm afraid, so I don't know how manipulating the $localStorage object works. But if $scope.favourites is just a reference to it, we can skip the last line, since we're manipulating the same object already:

$scope.toggleExerciseFavourite = function(exercise) {
  var index = $scope.favourites.indexOf(exercise.exerciseName);

  if(index === -1) {
    $scope.favourites.push(exercise);
  } else {
    $scope.favourites.splice(index, 1);
  }
};


Use size_t consistently
You use both size_t and unsigned for counting. Stick with size_t.
Use default member initialization
You can use default member initialization to ensure arr[] is initialized, without having to call memset():
class bitarr
{
    static const unsigned NumBytes = (NumBits + CHAR_BIT - 1) / CHAR_BIT;
    unsigned char arr[NumBytes] = {};
    ...
};

You can then also remove the constructor completely.
Unnecessary if-statement in set()
You don't need to check whether val is true in set(). If it is false, the body of the if-statement will still do the right thing. While it might look like that would do a lot of work for nothing, the processor might easily mispredict this condition, making it less efficient than not having the if at all.
Make all functions that do not modify arr[] const
You made the function test() const, but to_string() also does not modify the bit array, so you can make that function const as well.
Optimize to_string()
Your function to_string() is very inefficient. The caller provides you with the characters to use for the representation of one and zero bits, but you first ignore that and build a string of '0' and '1', and then replace those characters one by one. Why not build the string directly using c1 and c2? Also, since you know how long the string will be, you should reserve space for all the characters up front.
std::string to_string(char c1, char c2) const
{
    std::string str;
    str.reserve(NumBits);

    for (size_t i = NumBits; i-- > 0;)
        str.push_back(test(i) ? c2 : c1);

    return str;
}

You implementation also has bugs: to_string('0', '1') results in an infinite loop, and to_string('1', '0') always results in a string with all zeroes.


First off, I think it's worth thinking carefully about whether C++ is the best tool for this task.  It certainly can be done, but you may find better documentation/more support for COM/interop from C# or VBA.  Particularly for such a simple task.

HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

You need to check the result of CoInitializeEx and every other API call you make.  Think of each API call as a polite request.  Windows may (and frequently does) decline requests.  In your program, these errors will be really hard to diagnose because you will simply not see your desired result.  A better idea is to use a function/macro to check the result is correct.  In this case, it should look something like:

assert(S_OK == CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));

You may want to get fancier with the macro.  This way you will know where (and where not) to spend time debugging.

Quoting MSDN:

  To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx, including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize.

You forgot to call CoUninitialize.  Your program (well, actually your thread) is supposed to tell Windows when it will start using COM and when it is done.

This is a great place to use RAII:

struct COMThread {
    COMThread() {
        assert(S_OK == CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));
    }

    ~ COMThread() {
        CoUninitialize(); // returns void, no need to check return value
    }
};

In general you should read MSDN for every function you call and probably write a few comments summarizing your findings (and maybe even a URL... sometimes the docs are hard to re-find IMO).

vTemplate.bstrVal = SysAllocString(L"")

Did you forget to deallocate this BSTR?  This could be another RAII wrapper.

VARIANT vTemplate;
VariantInit(&vTemplate);
vTemplate.vt = VT_BSTR;

Once again, there is a free function VariantClear which could be RAII.  A wrapper around variant is not a bad idea -- most of your code creates/clears variants.

I could not find docs for the specific Word functions you are calling, but I suspect there is a way to achieve this without using so many variants (based on some experience using other parts of the COM API).  I know this is not as helpful as it could be.

Despite a few things to clean up, I think you're off to a good start.  You have the general procedure down which is the most important thing.


Modularized JavaScript event handler to increment counters

disclaimer: "bad" is simply a way of saying it's not the best way.

If we were in the early 2000s this would probably be relatively clean code, however javascript has advanced a lot since then (current version: es6)

Take some time to check what's new.

Best practices today is to completely separate HTML / JS / CSS (unless you're using vue, react, angular)

Cleaner code
Logic separation
Reusability
Easier to maintain

So the following should not appear in your HTML.

/// bad
onclick="double_increment()"

/// good
const button = document.getElementById("some_id");
button.addEventListener("click", double_increment);

There is always a better alternative than
 and it's not semantic

Don't use it.

const before let and let before var

Always declare your variables with const by default. If you're ok with the variable mutating then use let. Don't use var unless you know what you're doing and you actually need it.

note: pushing an element to an array (declared with const) does not mutate the variable, just the array. Thus no error.

Do not hardcode your html element id in your function.

function Incrementer(name, value) {
   /// bad
   let mydiv = document.getElementById('mydiv');
}

It either needs to be sent via the parameter or accessed statically using class

class Incrementer {
   /// still bad though
   static target = "mydiv"
}

Object methods should do what their name infers.

Here, the increment function is supposed to increment the variable, but it does more than that.

Gets the text value of the span
Parses the text value
Increases by one
Updates the UI

(1) is hacky
(2) completely unneeded
(3) the actual thing your function is supposed to do
(4) updates UI ? not what your function says it does

/// bad
that.increment = function() {
        var i = parseInt(that.span.textContent) + 1;
        that.span.innerHTML = i;
}

/// better
that.i = value;

//increments value
that.increment = function() {
        that.i++;
}

//updates UI
that.update = function(){
        that.span.innerHTML = that.i;
}

// Method that should be called on button click
that.handleOnClick = function(){
   that.increment();
   that.update();
}

A double_increment function doesn't need to exist. Each Incrementer should add an event listener to the button click.

/// bad
function double_increment() {
    incrementer1.increment();
    incrementer2.increment();
}

See next section add event listener for solution

Using class and working example

es6 has introduced class

  JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

Thus your Incremental function should be a class instead.

class Incrementer {

  constructor(incrementId, options) {

    const {
      name  = "N/A",
      value = 0,
      target
    } = options;

    this.name     = name;
    this.counter  = value;
    this.view     = document.createElement("span");

    this.view.id = `#num_${name}`

    const button = document.getElementById(incrementId);
    button.addEventListener("click", ()=>this.handleOnClick())

    this.update();

    const container = document.getElementById(target);
    container.appendChild(this.view);
  }

  handleOnClick(){
    this.increment();
    this.update();
  }

  increment() {
    this.counter++;
  }

  update() {
    this.view.innerText = this.counter;
  }
}

const incrementer1 = new Incrementer(
  "increment",
  {name: "Hello World", value: 3, target: "container"}
);

const incrementer2 = new Incrementer(
  "increment",
  {name: "Hello World", value: 0, target: "container"}
)
#container {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  align-items: center;
  background-color: darkblue;
}

#container > span {
  padding: 10px;
  background-color: lightblue;
}
<button id="increment">Increment</button>