First, why are you using querySelectorAll when you use jQuery? Use jQuery's $(SELECTOR_STRING_HERE) instead.
I believe you're using querySelectorAll because you're trying to use forEach. Unfortunately, forEach is slower than your regular loops. Internally, jQuery uses a for-in and for in their each implementation, which may be faster than forEach.
Again, you use jQuery but you use window.onscroll. Use jQuery's event mechanism instead.

I believe you're trying to go native in your code assuming things would go faster. But you're trying to solve the wrong problem. The real problem is the scroll event. Just scrolling a notch of your mouse wheel will fire the scroll event a dozen times, more or less. Now in your handler, you have this:

[].slice.call(parallaxTop)

What this code does is:

Create an array (the [] part)
Create a copy of that array (the call to slice)
It appears 3 times in your handler

That means if the handler fired a dozen times, this means you created 6 arrays per fire. A dozen would mean 72 arrays. Note that when the garbage collector runs, it "stops the world" (stops everything, scripting and rendering), causing freezes every now and then.

Additionally, forEach is synchronous. Nothing else happens when it's running, and doing something that takes too long inside each iteration will hurt performance. That and the GC, you'll eventually leave a very small gap for rendering.

What I suggest is to move your logic in a separate function and throttle your handler. That is, you only call your logic once the scroll has fired for at least some time, or at least a number of times. Only then will you update your element positions.

Now you'd wonder if you scrolled for a second and you scrolled 500px, wouldn't the background just jump? Yes, but that's where CSS transitions come in. You transition the background-position property so that the background will slide (depending on the easing function) to the updated position instead of jumping to it.

But, if I were you, I'd save my time and effort and instead, use a plugin for parallax effects.


Disclaimer: I work with MSSQL most of the time, so my syntax might be a bit off.

Looking at your code : as you do GROUP BY c.id you will get 1 record per comment. (**) Each line will get the total sum of cr.vote values found for each comment. So far so good.

But then it gets a bit muddy. It seems you want to add the author-information too, but you use a LEFT OUTER JOIN, meaning that you expect/prepare for some comments to have an author id that is not present in the users table?! Is this by design? If not I'd suggest to change the OUTER JOIN into an inner JOIN and additionally to put a FOREIGN KEY from the author field towards the users-id field. This way you prevent 'bad data' and it also tells the RDBMS that there always will be a matching record.

In MSSQL, a SUM() or MAX() on purely NULLs (= what will get returned from the LEFT OUTER JOIN in case no matching comments_ratings records exist) will return a NULL. You seem to try to catch this by using the IF() construction but I'd rather suggest to a 'COALESCE()` with some default value, probably zero.

As such you'd get:

SELECT c.id,
       c.text,
       c.time,
       c.author,
       u.email AS author_name,
       COALESCE(SUM(cr.vote), 0) AS rating,
       COALESCE(MAX(cr.vote), 0) AS voted

  FROM comments c
 JOIN users u ON u.id = c.author
 LEFT OUTER JOIN comments_ratings cr ON c.id = cr.comment
GROUP BY c.id, c.text, c.time, c.author, u.email

**: As you can see I've added all fields that are not aggregated to the GROUP BY clause, in MSSQL this is a requirement for the syntax to be valid; I believe this is not the case for mysql, but I see it as a good habit in all cases. (YMMV =)


Validate that a given string (name) meets certain requirements

As you wanted to use RegEx I have a recommendation for you:

public static bool IsValidName(string Name)
{
    if(String.IsNullOrEmpty(Name))
        return new ArgumentNullException();

    string pattern = @"^[0-9]{4} [0-9]{2} [0-9]{2} abjwg kelk\\.exe$";
    return Regex.IsMatch(Name, pattern);
}


for a starter I see tree aspects which you could upgrade:

Improve code readability
Make code reusable
Improve validation / error handling.

From main_page() extract 4 functions:

get_user_height()
get_user_weight()
calculate_bmi(height, weight)
print_bmi_description(bmi)

In get_user_height() and get_user_weight() user input. What is min and max value which are correct in your model? e.g. nobody has weight of -1.0.
Make sure that you can trust this functions i.e. they return only valid values.

calculate_bmi(height, weight) - extracting calculation code to distinct function makes it easy to reuse and test (unit tests or even simpler in interactive console).

print_bmi_description(bmi) - make sure your logic covers all possible values. By covers I mean it returns correct description or throws an error (ie. for negative BMIs).

You should remove redundant code eg. BMI < 18.5 or BMI <25 -
check only for BMI <25.
Validate your logic. BMI < 30 or BMI < 40 seems incorrect. I think it should be BMI > 30 or BMI < 40 or in more pythonic way 30 < BMI < 40

I think it is enough for know. If you make this changes we could make next step :-)


Stable radix sort in-place using O(1) space

Yes, your radix sort appears to be correct, and runs in O(k n) time.

bucket_max_index is written to, but otherwise never used.  You can eliminate it completely.

Before the creation of the temp vector, you set index = 0.  It would be clearer to change that to assert(index == 0), since that should have been the result of v.size() - Σ bucket[i] in the previous loop.


main() doesn't need to be indented out as such, same with the global arrays.
main() should have a void parameter since it's not taking command-line arguments.
You're using "Yoda conditions" in some places:

if (0 != getifaddrs(&ifaddrp))

NULL != ifap

and rest elsewhere in most places. Stay consistent with one of these types.
It looks like netip could be const since it's not being modified and is only used as a const parameter in strlcpy().
You can simplify this:

if (g_szPublicIP[0] != '0')
{
    return true;
}
else
{
    return false;
}

to this:

return g_szPublicIP[0] != '0';

It'll automatically return the outcome of the function call.

However, if you still prefer to see true and false, you can use a ternary:

return (g_szPublicIP[0] != '0') ? true : false;


Auto-throttling extension may cause high download delays. Either turn the extension off to see what would the resulting time be, or limit the maximum delay via AUTOTHROTTLE_MAX_DELAY.

Also, you may issue multiple requests from the after_login() method instead of keeping the queue of references:

def after_login(self, response):
    for ref in references:
        yield scrapy.Request(url="url" + ref, callback=self.parse_stock)

Also, instead of writing to the file from a spider directly, you can use a CSV output pipeline:

import csv

class CSVWriterPipeline(object):
    def __init__(self):
        self.writer = csv.writer(open('file.txt', 'wb'))

    def process_item(self, item, spider):
        self.writer.writerow([item["field1"], item["field2"], item["field3"])
        return item

Where field1, field2, field3 are your item fields:

class MyItem(Item):
    field1 = Field()
    field2 = Field()
    field3 = Field()

Which should be set in the parse_stock() callback:

def parse_stock(self, response):
    item = MyItem()
    item["field1"] = response.xpath('//*[@id="priceDetails"]/form/div[2]/text()').extract_first()
    item["field2"] = response.xpath('//*[@id="priceDetails"]/form/div[8]/div[1]/span/span[2]/text()').extract_first()
    item["field3"] = response.xpath('//*[@id="priceDetails"]/form/div[8]/div[1]/span/span[1]/i/@style').extract_first()
    return item

Then, you would need to enable the pipeline:

process = CrawlerProcess({
    'ITEM_PIPELINES', {
         '__main__.CSVWriterPipeline': 100
    },
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
    'LOG_LEVEL': 'INFO',
    'AUTOTHROTTLE_ENABLED': 'True',
    'AUTOTHROTTLE_START_DELAY': '0.1',
    'AUTOTHROTTLE_TARGET_CONCURRENCY': '100'
})

Or course, improve the "field" and "item" class names to be more meaningful.

There are other things, like using local DNS cache, you may try to speed up your spider:

Speed up web scraper

And, as a "running Scrapy from script" reference topic, please see this post.


Returning the length of the File in B/KB/MB

Logic

You can simplify your logic by testing for the biggest known extension, for example

if (fileSize > 1024 * 1024)
    doMiB();
} else if (fileSize > 1024) {
    doKiB();
} else {
    doByte();
}

Rounding

Don't use Math.round(x / 100.0) * 100. for rounding to two decimal places use the appropriate library function

Argument checking

Don't use default values ("Unknown") for invalid input. If the input to your getFileSize method is not a file, throw an exception

if (!file.isFile()) {
    throw new IllegalArgumentException("Expected argument to be a file");
}

Fast return

This is more personal taste but I prefer to return as soon as possible. If you know the result will be "100.31 KiB" why save it into a local variable instead of returning it immediately?

Conclusion

I would improve the code as followed

private static final DecimalFormat format = new DecimalFormat("#.##");
private static final long MiB = 1024 * 1024;
private static final long KiB = 1024;

public String getFileSize(File file) {

    if (!file.isFile()) {
        throw new IllegalArgumentException("Expected a file");
    }
    final double length = file.length();

    if (length > MiB) {
        return format.format(length / MiB) + " MiB";
    }
    if (length > KiB) {
        return format.format(length / KiB) + " KiB";
    }
    return format.format(length) + " B";
}


Fun question,

I am not sure why you think you need a special treatment for Safari, I could not find any reference to that on the webs. So if you only need the browser code for that part, then I would drop it and simply go for

/*
 * Get window height and width
 *
 * Usage:
 * windowDimensions.height();
 * windowDimensions.width();
 *
 */
app.factory('windowDimensions', ['$window',
  function($window) {
    return {
      height: function() {
        return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
      },
      width: function() {
        return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
      }
    };
  }
]);

From a naming perspective I would suggest these changes:

getDimensions -> broadcastDimensions (since that is really what you are doing there)
$scope.resizing -> $scope.resizingTimer (to reduce potential confusion, resizing is a verb so one would expect resizing to do something instead of merely being a timer)
300 -> var delayTime = 300; //Broadcast 300ms after the last resize to avoid flood

Other than that, all is well besides a few missing semicolons.
You can test my fork on Safari if you wish, it worked for me:
http://plnkr.co/edit/SY8pnX3ae4YtWErno5f0?p=preview


Looking For a More Efficient/Elegant Way To Write a MySQL Query

Try something like this:

$sql = "SELECT * FROM user ORDER BY timestamp DESC LIMIT 1";
$result = $mysqli->query($sql);
$row_lastone = mysqli_fetch_array($result);

$date = date("M Y", strtotime($row_lastone['timestamp']));

echo "<h1>".$date."</h1>";


Take a result set and organize it into a dictionary

Naming

The C# standard for publicly-visible properties is to use PascalCase:

public double TakenCompHours { get; private set; }
public double TakenBereavementHours { get; private set; }
public double TakenJuryDutyHours { get; private set; }

Additionally, db is not a very descriptive name for your entities.  It seems something like personnel would better indicate what it is.

Similarly, dayType is a dictionary storing the types of time-off requests, and it is a field, so I would call it something like _timeRequestTypes.

Finally, the class name itself, OtherTimeTypes reads more like the type contains a list of possible time types that fall outside a standard set of types.

However, it's telling you the aggregate number of comp, bereavement, and jury duty hours requested for a particular user over the current year.  I'm pretty bad at naming myself, though, so perhaps someone else can come up with some good alternatives.

Design

The first thing I see is that the dayType dictionary only seems to exist as a way of identifying the int values the database uses.  This would actually be much simpler as an enum value:

public enum TimeRequestType
{
    BereavementHours = 3,
    JuryDutyHours = 4,
    CompHours = 7,
}

The next thing I see is that you have several discrete properties to store different types of hours, but you are using a dictionary to do the same thing.  You could just as easily add directly to the properties, or with some method extraction, you could perform a Sum in your LINQ.

Another thing I see is that you are hard-coding the year to be the current year.  I would instead pass that as a parameter.  Sure, the 99% case is that you are going to ask for the current year, but it is trivial to parameterize that, and you'll be glad you did if you ever have to get the values for not-this-year.

The last major thing I see is two-fold:

OtherTimeTypes both stores the data values returned for a user as well as performs the entity look-ups required to retrieve that data
All work is being done in a constructor

For this, I would first extract a data object class to store the values we are interested in:

public class UserTakenHours
{
    public UserTakenHours(double compHours, double bereavementHours, double juryDutyHours)
    {
        TakenCompHours = compHours;
        TakenBereavementHours = bereavementHours;
        TakenJuryDutyHours = juryDutyHours;
    }

    public double TakenCompHours { get; }
    public double TakenBereavementHours { get; }
    public double TakenJuryDutyHours { get; }
}

Then, I would move the logic for retrieving the data and aggregating it into a static method that returned the data object, along with some helper functions.

First, you can extract a method for calculating the hours in a particular TimeRequest:

private static double GetRequestedTime(TimeRequest request)
{
    return (((request.eDateTime - request.sDateTime).TotalDays + 1) * (int)request.HoursRequested);
}

With that, you can condense the foreach loop on your requests into a single-line LINQ statement:

result.Select(GetRequestedTime).Sum();

I would then extract the body of your loop on dayType into its own method, taking in arguments for the entities, username, year, and type:

private static double CalculateRequestedTime(PersonnelManagementEntities personnel, string user, int year, TimeRequestType type)
{
    var requests = personnel.TimeRequests
                            .Include(t => t.User)
                            .Where(t => t.DayTypeID == (int)type)
                            .Where(t => t.User.ADUserName == user)
                            .Where(t => t.UserSubmitDate.Year == year)
                            .ToList();

    return requests.Select(GetRequestedTime).Sum();
}

And finally, you can change the constructor into a static method that returns the data object:

public static UserTakenHours GetRequestedHours(string user, int year)
{
    var personnel = new PersonnelManagementEntities();
    var compHours = CalculateRequestedTime(personnel, user, year, TimeRequestType.CompHours);
    var bereavementHours = CalculateRequestedTime(personnel, user, year, TimeRequestType.BereavementHours);
    var juryDutyHours = CalculateRequestedTime(personnel, user, year, TimeRequestType.JuryDutyHours);

    return new UserTakenHours(compHours, bereavementHours, juryDutyHours);
}


Cyclic "dependency detection" in JavaScript

HashMap of visited nodes is more efficient than array lookup

First of I'd like to acknowledge that I think you've done a fantastic job so far. Your code is thought out really well and from my tests appears to be rock solid. My biggest concern is that using Array.indexOf() isn't as efficient as storing a map of visited nodes:

var visited= {};

if (visited[node]) {
  return;
}
visited[node] = true;
definitions[node].some(internalSearch);

Not only does the map have O(1) lookup--which is nice--but it also would prevent some redundant searches. For example, take a look at the following case:

definitions = {
  'A': ['B', 'C'],
  'B': ['D'],
  'C': ['D'],
  'D': []
}

Here's a JSFiddle that shows how node D is checked twice. That doesn't seem like a lot, but the more the dependency tree's branches weave the more redundancy that's introduced:

definitions = {
  'A': ['B', 'C'],
  'B': ['D'],
  'C': ['D'],
  'D': ['E', 'F']
  'E': ['G']
  'F': ['G']
  'G': ['H', 'I'],
  'H': ['J'],
  'I': ['J'],
  'J': ['K', 'L'],
  'K': ['M'],
  'L': ['M'],
  'M': []
}

Here's the JSFiddle for this case. Note how M is checked 16 times!

Of course, your module loader may never run into such test cases, but IMO, the time it would take to implement the map is well worth the increase in your algorithm's efficiency.

Redundant comments

I'm not sure if you're just trying to help explain what your code does for code review, but comments like:

// Internal search function.
var internalSearch = function(currentIdentifier) {

don't really contribute to understanding; the code is self explanatory. Your code could be much shorter without the comments, so consider which of your comments actually adds value to the code. Anything else may just be clutter.

No faulty case

As of your concern, I'm pretty confident that currentIdentifier, will always be in the stack when you call for it to be removed. My reasoning is as follows:

Proof - First, you check to see if a node, A is on the stack:

A is on the stack:

return, the stack is unaffected

A is not yet on the stack:

A is pushed onto the stack [ ..., A]
Call internalSearch on each child, C, consider the three cases of children:

If C === A then C is found on the stack because A is on the stack:

return, the stack is unaffected

If C !== A and C is not found the stack:

Add C to the stack `[ ..., A, C, ... ]
Call internalSearch on each of C's children
Remove C from the stack [ ..., `A, ... ]
return

If C !== A and is found on the stack:

return, the stack is unaffected

Remove A from the stack [ ... ]

The only way for the stack to have the currentIdentifier removed would be if one of it's decedents were equal to it, but because you check the stack at the top of each call to internalSearch, you never deal with a duplicate node, so this will never happen.


Creating a secure and efficient DB connection and queries (using one class)

You say that you use prepared statements, but your code doesn't actually reflect that.

sql just executes any query, without binding or escaping anything. You really need to use prepared statements though. Your current sql function isn't usable in practice and it's pure existence will likely lead to vulnerabilities (other programmers will likely use it as it exists, and it can't be used securely).

Apart from that:

don't mix different APIs. Currently, you use mysqli and mysql.
don't use mysql, it's been deprecated for years and has finally been removed in PHP7.
your formatting is off. Use correct indentation, always use curly brackets, use newlines for statements (eg after an if), and use spaces around =. Any IDE can fix these things for you.
be consistent with your naming. Your functions should all start with a lower-case character.
Also, same things should be named the same. So if you have a field called connection, the method retrieving it should be getConnection, not getLink.
Also try to be more explicit with your variable names and don't shorten names. val should be value (but really, it should be user or username), res should be result, n should be queryCount, and so on.
It's very unclear to me what n is used for. I would remove it, or document it.
sql isn't really useful. It's just a wrapper around mysql_query which automatically echoes errors (meaning that the calling code has no possibility to recover or show a different error message; throw an exception instead), and provides the possibility to execute multiple queries, which doesn't actually seem needed.
You don't want to create a new database connection for each method (for performance reasons), so instead, create it once and then pass the db object to methods that need it.


C# How to check if we've 'had' values from a method without having to re-call the method

I don't understand why you don't want to use a variable. However, one way is to provide an extension method for this:

public static void ForEachDo<T>(this IEnumerable<T> seq, Action<T> doWithEveryItem, Action doIfEmpty = null)
{
    bool isEmpty = true;
    foreach (T item in seq)
    {
        isEmpty = false;
        doWithEveryItem(item);
    }
    if (isEmpty && doIfEmpty != null)
        doIfEmpty();
}

Now you can use it with everything that implements IEnumerable<T> like a string:

"".ForEachDo(Console.WriteLine, () => Console.WriteLine("No Events")); // prints "No Events"


Aside from RobAu's comment, I think the addMarker method can be simplified into:

board[n].setMarker(s);

By delegating the checking the availability of the cell to the Cell class. I think it would be best to define your own exception extending from IllegalArgumentException.

public void setMarker(String marker) {
    if(!marker.equals(" "))
        throw new CellIsNotAvailableException();
    this.marker = marker;
}

Another thing I want to point out is the way you name your methods and variables. One should always name their methods and variables properly such that it won't be neccessary to add a comment explaining what these things do (It's fine to write comments explaining why they exist though). As much as possible, Express yourself in code! Take addMarker for example. I think addMarker would be better written as markCellWithMarker(int cellNumber, String marker) (I consider X's and O's as tokens to be used in the game), and getCellValue as getMarkerAt(int cellNumber).

Applying these changes, here's my refactored version of the GameBoard Class:

public class GameBoard {

    private Cell[] board;

    public GameBoard(int numberOfCells) {
        board = new Cell[numberOfCells];
        for (int i = 0; i < numberOfCells; i++) {
            board[i] = new Cell();
        }
    }

    public void markCellWithMarker(int cellNumber, String token) {
        board[cellNumber].setMarker(token);
    }

    public String getMarkerAt(int cellNumber) {
        return board[cellNumber].getMarker();
    }
}

As for the Game class, it doesn't really justify its existence as it is right now. It contains only one method that is supposed to run a game (if I read your code right). Refactoring it into this might justify its existence:

public class Game {
    private GameBoard gameBoard;
    private Player[] players;
    private int turnNumber;

    //In case you want a two player game.
    public Game(int numberOfCells, Player player1, player player2){
        gameBoard = new GameBoard(numberOfCells);
        setFirstTurnPlayer(player1, player2);
    }

    //In case you want a single player game against the computer.
    public Game(int numberOfCells, Player player){
        gameBoard = new GameBoard(numberOfCells);
        Player computer = new Player("computer");
        setFirstTurnPlayer(player1, computer);
    }

    private void setFirstTurnPlayer(Player player1, Player player2){
        //It's up to you how you decide the turnorder: die roll, coin toss or something.
        //The first one in the player array is considered as the turn player.
    }

    public String getTurnPlayer(){
        return players[turnNumber%2].getName();
    }

    public void markCellWithMarker(int cellNumber){
        String markerToPlace = players[turnNumber%2].getPlayerMarker()
        gameBoard.markCellWithMarker(cellNumber, markerToPlace)
        checkIfTurnPlayerWinsTheGame()
        turnNumber++;
    }

    //GameStateChecker code moved here. I think this one can be made shorter and more readable.
    public void checkIfTurnPlayerWinsTheGame(){
        //Rename currentPlayer as turnPlayer
        Player currentPlayer = players[turnNumber%2]
        if ((board[0].getMarker().equals(currentPlayer.getMarker()) && board[1].getMarker().equals(currentPlayer.getMarker()) && board[2].getMarker().equals(currentPlayer.getMarker())) ||
            (board[3].getMarker().equals(currentPlayer.getMarker()) && board[4].getMarker().equals(currentPlayer.getMarker()) && board[5].getMarker().equals(currentPlayer.getMarker())) ||
            (board[6].getMarker().equals(currentPlayer.getMarker()) && board[7].getMarker().equals(currentPlayer.getMarker()) && board[8].getMarker().equals(currentPlayer.getMarker())) ||
            (board[0].getMarker().equals(currentPlayer.getMarker()) && board[3].getMarker().equals(currentPlayer.getMarker()) && board[6].getMarker().equals(currentPlayer.getMarker())) ||
            (board[1].getMarker().equals(currentPlayer.getMarker()) && board[4].getMarker().equals(currentPlayer.getMarker()) && board[5].getMarker().equals(currentPlayer.getMarker())) ||
            (board[2].getMarker().equals(currentPlayer.getMarker()) && board[5].getMarker().equals(currentPlayer.getMarker()) && board[8].getMarker().equals(currentPlayer.getMarker())) ||
            (board[0].getMarker().equals(currentPlayer.getMarker()) && board[4].getMarker().equals(currentPlayer.getMarker()) && board[8].getMarker().equals(currentPlayer.getMarker())) ||
            (board[2].getMarker().equals(currentPlayer.getMarker()) && board[4].getMarker().equals(currentPlayer.getMarker()) && board[6].getMarker().equals(currentPlayer.getMarker())))
        throw new GameIsOverException(currentPlayer.getName() + " wins!")
}

Here's the code I wrote for a game called ConnectFour which I think is a bit similar to tic-tac-toe. This may help you see some of the things I mentioned here on proper naming and stuff.


Which is a better optmized CSS for a button design?

I like the second option, it is easy to read if you just reformat it a little bit (also corrected your :active selector and fixed the shadow in IE9):

a.btn_link {
    background: #4468b2; /* Old browsers */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#4468b2), color-stop(100%,#3b5a9b)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  #4468b2 0%, #3b5a9b 100%); /* Chrome10+,Safari5.1+ */
    background:    -moz-linear-gradient(top,  #4468b2 0%, #3b5a9b 100%); /* FF3.6+ */
    background:     -ms-linear-gradient(top,  #4468b2 0%, #3b5a9b 100%); /* IE10+ */
    background:      -o-linear-gradient(top,  #4468b2 0%, #3b5a9b 100%); /* Opera 11.10+ */
    background:         linear-gradient(top,  #4468b2 0%, #3b5a9b 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4468b2', endColorstr='#3b5a9b',GradientType=0 ); /* IE6-9 */

    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;

    -webkit-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);
       -moz-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);
            box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);
    border-collapse: separate; /* http://stackoverflow.com/questions/5617455/issue-with-box-shadow-on-ie9/5617540#5617540 */

    color: #FFFFFF;
    text-decoration: none;
    padding: 5px 25px 5px 25px;
}
a.btn_link:active {
    margin: 2px -2px 0 2px;
    -webkit-box-shadow: none;
       -moz-box-shadow: none;
            box-shadow: none;
}

I would also add a simple hover affect like this:

a.btn_link:hover {
    background: #4468b2;
    filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}

If you can, consider using a css preprocessor like LESS

.rounded-corners (@radius: 4px) {
    -webkit-border-radius: @radius;
       -moz-border-radius: @radius;
            border-radius: @radius;
}

.gradient-box (@baseColor) {
    @darker = darken(@baseColor, 6%);
    background: @baseColor; /* Old browsers */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,@baseColor), color-stop(100%,@darker)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  @baseColor 0%, @darker 100%); /* Chrome10+,Safari5.1+ */
    background:    -moz-linear-gradient(top,  @baseColor 0%, @darker 100%); /* FF3.6+ */
    background:     -ms-linear-gradient(top,  @baseColor 0%, @darker 100%); /* IE10+ */
    background:      -o-linear-gradient(top,  @baseColor 0%, @darker 100%); /* Opera 11.10+ */
    background:         linear-gradient(top,  @baseColor 0%, @darker 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='@baseColor', endColorstr='@darker',GradientType=0 ); /* IE6-9 */

    color: white;
    text-decoration: none;
    padding: 5px 25px 5px 25px;

    &:hover {
        background: @baseColor;
        filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
    }
}

.pressable-floating-box (@distance: 2px, @blur: 2px, @spread: 0px) {
    -webkit-box-shadow: @distance @distance @distance 0 rgba(0, 0, 0, .4);
       -moz-box-shadow: @distance @distance @distance 0 rgba(0, 0, 0, .4);
            box-shadow: @distance @distance @distance 0 rgba(0, 0, 0, .4);

    border-collapse: separate; // http://stackoverflow.com/questions/5617455/issue-with-box-shadow-on-ie9/5617540#5617540

    &:active {
        margin-right: -@distance;
        margin-left: @distance;
        -webkit-box-shadow: none;
           -moz-box-shadow: none;
                box-shadow: none;
    }
}

a.btn_link {
    .rounded-corners;
    .gradient-box(#3b5a9b);
    .pressable-floating-box;
}

I really wouldn't be too worried about css efficiency, yes this does take a little more effort on the browser's part to render than a simple css background image, but the paths are all highly optimized already and this way you have defined the style instead of giving the browser a limited example (try a two line button with each, or zooming the document, or any other of the many ways to mess the button up in one or more browsers).

Comparing the http transfer efficiency of these two probably comes out in favor of the latter as well. The image version comes in 2 requests, while the pure css version is only one. I'd bet they both are fairly minimal on the total bandwidth compared to your page as a whole, but if you were really concerned about this you could always inline the image. If you want to go that route, here is a useful tool: http://www.greywyvern.com/code/php./binary2base64


Least significant digit (LSD) radix sort of strings

This macro name is misleading:

#define ALPHABET 36

The alphabet consists of 26 letters, not 36.  But in a CS context, this can be implied (in this case, it appears to include A-Z and 0-9).

However, this macro is storing the alphabet's size, not the alphabet itself.  The name should clearly specify that.  A more appropriate name could be ALPHABET_LENGTH.

On another note, the other macro should be renamed to PLATE_LENGTH.  Underscores are commonly used to separate each word in a macro.
Avoid single-character variable names:

int R = ALPHABET;
int W = string_size;

Based on the context (fortunately), I can tell that these hold sizes.  Other than that, they are very unclear and could lead to maintenance problems at some point.  Always give variables descriptive names, unless they're simple loop counters.
You have the list-displaying code in main() twice.  Why not make it a function?  This will reduce the amount of code in main() and maintain DRY, making it clearer to read and to maintain.

void display(char list[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%s\n", plates[i]);
}

You could keep the label outputs in main(), right before the function calls.


$(".tabs-content").find(cssClass).show().siblings().hide(); is confusing and not easy to read.

Otherwise it seems to be working. As for best practices:

Make sure your content is accessible to non JS users, such as search engines or browsers without JS.
Consider using the Bootstrap tab plugin or jQuery UI tab functionality. Of course if you don't already use one of those, keep your simple jQuery function.


I can see repetitive code which you can fix easily..

Before

//Remove old tokens:
var oldRefreshToken = user.Claims.Single(c => c.Type == AuthenticationValues.RefreshTokenKey);
var oldAccessToken = user.Claims.Single(c => c.Type == AuthenticationValues.AccessTokenKey);
var oldExpiresAt = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtKey);
var oldEpoch = user.Claims.Single(c => c.Type == AuthenticationValues.ExpiresAtEpochKey);
identity.RemoveClaim(oldRefreshToken);
identity.RemoveClaim(oldAccessToken);
identity.RemoveClaim(oldExpiresAt);
identity.RemoveClaim(oldEpoch);

After

var tokens = user.Claims
    .Where(c =>
        c.Type == AuthenticationValues.RefreshTokenKey ||
        c.Type == AuthenticationValues.AccessTokenKey ||
        c.Type == AuthenticationValues.ExpiresAtKey ||
        c.Type == AuthenticationValues.ExpiresAtEpochKey);

foreach (var token in tokens)
{
    identity.RemoveClaim(token);
}

You have filter claims by its type many times, which is similar code. You can get rid of duplicate code by introducing a method. I am not sure about the return or parameter type but it look somehow like below.

public static string GetClaimsType(string type)
{
    return ClaimsPrincipal.Current.Claims.Where(c => c.Type == type).Select(c => c.Value).SingleOrDefault();
}

Now your code will be much cleaner and shorter..

Before

var claims = ClaimsPrincipal.Current.Claims;
var refreshToken = claims.Where(c => c.Type == AuthenticationValues.RefreshTokenKey).Select(c => c.Value).SingleOrDefault();
long epoch = Convert.ToInt64((claims.Where(c => c.Type == AuthenticationValues.ExpiresAtEpochKey).Select(c => c.Value).SingleOrDefault()));

After

var refreshToken = GetClaimsType(AuthenticationValues.RefreshTokenKey);
long epoch = Convert.ToInt64(GetClaimsType(AuthenticationValues.ExpiresAtEpochKey));


Finding the max error of a set of training data

Current approach
Right now, you train on randomly selected inputs from the set of all possible inputs and keep track of the highest error per input using a map.  There are a couple of things I don't like about this:

By randomly selecting inputs, you might fail to cover all inputs.  Then you might think the net is finished training when it actually might fail to handle an input that was never randomly picked.
Keeping track of the highest error per input is slow.

New approach - training in rounds
I suggest changing your approach in the following way:

When you train, you must train in "rounds".
At the beginning of each round, you shuffle the order of the possible inputs.
One round consists of training on each input one by one in the shuffled order.
During training, the highest error is tracked for the round.  This is now just a single variable instead of a map.
At the end of each round, training either stops if the highest error is good enough, or continues to the next round if the error is too high.


Lightweight flexible observer framework using weak references

I have some "readability-issues". It usually helps to name your methods with a verb and a noun, so, post would be postMessage, for instance.

listen and ignore are not named correctly, in my opinion. If I call listen(listener, consumer), I do not know what this method will do with the two parameters, it feels like, the method adds the listener to the consumer. I also have no idea, that the listener is used for unsubscribing later. If I call ignore(listener), it feels like I pause the listener, and can activate it later. addListener and removeListener would have been more clear.

Also, since we're talking about publishers and subscribers, I'd recommend to use the terminology of this pattern. Publisher, Subscriber (well, Consumer is given by the jdk), publish, subscribe and unsubscribe.

Well, it's a bit smart-arse-y, but, since I'm here,... By definition, or at least by the definition I know/remember, one thing the publish/subscribe pattern wants to achieve is, that the subscribers have the ability to subscribe to specific messages types, e.g. : You subscribe to a news feed, but only the sports part. So, I recommend to rework the terminology, because a user of your API can have different expectations of the API. (Yes, I'm one of them :P)

StuffProcessor is missing, btw, so I can't run the code.

I had a really hard time to understand your sample code. I tried to make an easier example of the usage:

    public class BroadcasterSampleUsage {
                public static void main(String[] args) {
                           Broadcaster<Message> broadcaster = new Broadcaster<>();
                           Object someIdentifier = new Object();

                           broadcaster.listen(someIdentifier, new MessageConsumer());

                           broadcaster.post(new Message("helloes"));
                }

                private static class MessageConsumer implements Consumer<Message> {
                           @Override
                           public void accept(Message t) {
                                       System.out.println("Received message: " + t.getMessage());
                           }
                }

                private static class Message {
                           private final String message;

                           public Message(String message) {
                                       this.message = message;
                           }

                           public String getMessage() {
                                       return message;
                           }
                }
    }

I'm not 100% certain if that's the intention of your API, after I've seen the usage code, but alas, if I understood your intention correctly, that would be easier to read.

The only Reason for the Object listener is to have it as key object, right? Now, why is that confusing for me: You call that thing listener. What is it listening for? And what's the difference between listening and consuming?

In your sample code, you actually do use this as key and use a lambda expression as parameter. So what if I would actually would overwrite the accept method in the StandingLog type, change the method signature in Broadcaster from

public void listen(Object listener, Consumer<M> consumer)

to

public void listen(Consumer<M> consumer)

, and instead of putting the listener and the consumer to the map, I use the consumer as key and value, wouldn't I achieve the same thing? If yes, I think you should be able to use this one: http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#newSetFromMap(java.util.Map).

Also, check the JavaDoc about the synchronized* methods. Synchronization may not be done yet: It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views. I do think, any means keys and values.

Hope this helps,

slowy


My first-ever jQuery works, but it's not efficient. Any pointers?

I found .toggle() in the jQuery docs, and it seemed to me I could use that far better. I changed my code into:

jQuery(document).ready(function(){
    var nav = jQuery(".navigation-menu");
    var button = jQuery(".navigation-title");

    nav.toggle();

    button.click(function(event){
        event.preventDefault();
        nav.toggle('fast');
    });
});

This looks a lot leaner and better readable.


Web page that calculates results of four arithmetic operations for two numbers

One obvious simple change is to avoid making unnecessary variable assignments.  For example, just write

const a = Number(document.getElementById("first-number").value);

instead of

const firstInput = document.getElementById("first-number").value;
…
var firstNumb = Number(firstInput);

You should also be more consistent with naming (e.g. addTwoN vs. multiplNumb).  myFunction needs a better name; I suggest onInputUpdated.

The code could be simplified by treating each of the four operations as data.  Then, you apply the same transformation on each element of the operations list.

const operations = [
    {symbol: '+', callback: function(a, b) { return a + b }},
    {symbol: '-', callback: function(a, b) { return a - b }},
    {symbol: '*', callback: function(a, b) { return a * b }},
    {symbol: '/', callback: function(a, b) { return a / b }},
];

function onInputUpdated() {
    const a = Number(document.getElementById("first-number").value);
    const b = Number(document.getElementById("second-number").value);
    const result = operations.map(function(op) {
        return a + " " + op.symbol + " " + b + " = " + op.callback(a, b);
    }).join('
');
    document.getElementById("result").innerHTML = result;
}
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<form class="ml-5 mb-5 mt-5">

     What is the first number?
     <input type="number" class="form-control" name="" id="first-number" oninput="validity.valid||(value=''); onInputUpdated()" min="0" style="width: 90px">

     What is the second number?
     <input type="number" class="form-control" name="" oninput="validity.valid||(value=''); onInputUpdated()" id="second-number" min="0" style="width: 90px">

</form>


Your code could be simplified and better organized.

You seem to be expecting HTML, as evidenced by various calls that look like .replace(/(<([^>]+)>)/ig, "").  However, that is a half-assed way of interpreting HTML as text.

Consider that your getSentences() treats a newline as a possible sentence delimiter.  But all whitespace in HTML is considered equivalent, more or less.  If your input is indeed HTML, you should normalize all whitespace as spaces, and interpret tags such as
 and
 as line breaks.

Also, if the input is HTML, you ought to decode entities (&65; is A, for example).
Most of your functions have parameters named input.  Well, duh.  All parameters act as input, by definition.  But what kind of input?  Here is the most baffling example, where the input is supposed to be an array of sentences:

function countSentences(input) {
  return input.length;
}

If the input is HTML text, call it html.  If it's plain text, then call it text.
The click handler is a bit convoluted.  It should look like this:

jQuery("#lixButton").click(function() {
  var html = jQuery('#inputLix').val();
  jQuery('#notification').text(lixScore(htmlToText(html)));
});

In particular, your getText() function hard-coded the ID of the textarea, which I don't recommend.  Your outputContent(), in contrast, does take a jQuery selector as a parameter (inappropriately named id), which is good, but needlessly complicated.  I would eliminate both getText() and outputContent().
The calculateLix() function is hard to use.  Why does it need so many parameters?  Why not just feed it some text and have it do the analysis?
The helper functions are inconsistently designed: countWords(input) vs. longWordCount(input) vs. countSentences(getSentences(input)).

The implementations of countWords() and longWordCount() overlap, and they treat punctuation differently (why?).  Once you have identified the words, shouldn't counting long words be a simple matter of filtering by length?

Why does getSentences() mess around with punctuation that is irrelevant to sentence-splitting?

Suggested implementation

jQuery(document).ready(function() {
  var htmlNamedEntities = {
    "amp": "&",
    "quot": '"',
    "lt": "<",
    "gt": ">"
  };

  function htmlToText(html) {
    return html.replace(/\s+/, " ")
               .replace(/<\/?\s*(p|br|hr)[^>]*>/ig, "\n")
               .replace(/(<[^>]+>)|&(\d+);|&x([0-9a-f]+);|&([a-z]+);/ig,
      function($0, tag, decimalEntity, hexEntity, namedEntity) {
        return tag ? ""
             : decimalEntity ? String.fromCharCode(parseInt(decimalEntity))
             : hexEntity ? String.fromCharCode(parseInt(hexEntity, 16))
             : htmlNamedEntities[namedEntity];
      }
    );
  }

  function words(text) {
    return text.replace(/[-']/ig, "")  // Ignore hyphens and apostrophes.
               .split(/\W+/)           // This assumes that the text is alphanumeric English.
               .filter(Boolean);
  }

  function sentences(text) {
    return text.split(/[?!.\n]+/)
               .filter(Boolean);
  }

  function lixScore(text) {
    var textWords = words(text);
    var w = textWords.length;
    var lw = textWords.filter(function(w) { return w.length > 6 }).length;
    var s = sentences(text).length;
    return Math.round((w / s) + (100 * lw / w));
  }

  jQuery("#lixButton").click(function() {
    var html = jQuery('#inputLix').val();
    jQuery('#notification').text(lixScore(htmlToText(html)));
  });

});
.tool-wrapper {
  background: #899398;
  padding: 30px;
  border-radius: 10px;
}

textarea {
  width: 100%;
}

  <textarea id="inputLix" rows="5">This is just some basic text. Push the button to calculate the LIX value. And figure out how hard your text is to read.</textarea>

    <button id="lixButton" class="alignright" type="submit">Calculate Lix</button>

You haven't performed any calculations yet


Convert string to fishy and fishy to string

I'm not entirely sure why you are not satisfied with your code as it looks quite good. Maybe too many blank lines that seem to stretch the code length. There are also a few things on the Python side that could be changed to reduce the amount of source lines needed for the task:

string_to_fishy

string_to_fishy can be rewritten using a list comprehension:

def string_to_fishy(string: str) -> str:
    """..."""
    return ' '.join(f'><{ord(char)}>' for char in string)

fishy_to_string

The inverse function could use a similar technique in order to avoid repeated creations of new strings in string += chr(value):

def fishy_to_string(fishy: str) -> str:
    """
    Converts a fishy code to string

    Examples:
        ><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>
        Hello World!

        ><48> ><48> ><55> ><32> ><74> ><97> ><109> ><101> ><115> ><32> ><98> ><111> ><110> ><100>
        007 James bond
    """
    if not fishy:
        return ''

    def parse_fish(token):
        if not token:
            raise FishyError('Invalid syntax: Extra whitespace')

        if not (token.startswith('><') and token.endswith('>')):
            raise FishyError('Invalid syntax: ' + token)

        try:
            value = int(token[2:-1])
            string += chr(value)
        except ValueError:
            raise FishyError('Input cannot be parsed as character: ' + token)

    return ''.join(parse_fish(token) for token in fishy.split(' '))

I also allowed myself to change the variable name char to token, because I find it more appropriate in that context, and also slightly reworded the last error message to make it more expressive.


SQL trigger to log when employee records are updated

First some comments.

Usage of Deprecated Features

Currently your trigger does a SELECT that returns a resultset from a trigger. That was at one time supported but has been since deprecated since at least 2012. I would remove them.

Audit requirement

I very much agree with @Austin Hasting that it's generally better to not transform the data into a concatenated string here. You lose the ability to query or filter. The user-friendly formatting should be left to the application or at least the stored procedures used by the application. It doesn't belong in the trigger.

Bad assumptions

Your trigger assumes that you will have only one row in inserted and deleted. That is not how T-SQL triggers will work. It works on the statement level, not row level. Therefore you should code your trigger as if it could contain 10 rows in both virtual tables. The way the code is, it may not necessarily error out but it may miss out on other rows because the assignments only operate on the last row being assigned. Please, don't do this row by agonizing row.

Lack of two-part naming

It's a very good habit to always reference to your objects with two-part names, <schema>.<object> and not just <object>, because an object can exist in several schema with same names, and everyone has their default schema which takes precedence over the schema you actually meant to. I'm assuming you are using the default dbo schema. At least qualify that.

Lack of statement terminator

Several features have been added to the T-SQL language to a point where the ; terminator are no longer totally optional. T-SQL has been an aberrant in the SQL standard in making it optional. Some hack their way by putting a ; in front of statement whenever it's required, which is very weird. The best reason to use one everywhere is because it makes for more readable code, and makes your intention explicit.

Lack of block

I really do not like triggers or stored procedure without an explicit BEGIN...END block. It is valid T-SQL to write without one but this has problems and can make for confusing scripting.

Usage of + operator

You are concatenating strings with the + operator. Without knowing the version of your SQL Server, it might be the only choice but I should point out that since 2012, you now have a CONCAT() function which is much better because it will handle the nulls whereas + will propagate nulls and thus leave you with.... a null.

Lack of explicit insert list

When doing an INSERT, and especially when you do have an explicit SELECT list, it's usually good to have an explicit list. Otherwise, schema change could break the query.

With the commentary out of the way, this is how I'd rewrite this.

ALTER TRIGGER tr_tblEmployee_ForUpdate
ON dbo.tblEmployee
FOR UPDATE AS
BEGIN
  WITH Updated AS (
    SELECT
      i.Name,
      i....
      d.Name AS OldName,
      d.... AS Old...
    FROM inserted AS i
    INNER JOIN deleted AS d
      ON i.<primary key> = d.<primary key>
  )
  INSERT INTO dbo.tblEmployeeAudit2 (<Name of column>)
  SELECT CONCAT(
    'Employee with ID = ',
    u.ID,
    ' changed Name from ', u.Name ' to ', u.OldName
    ...
  ) AS AuditDescription
  FROM Updated AS u;
END;


Covering what others suggested (e.g. @Srivaths), please follow at least PEP8 Python PEP8

Then, put your code in some function.
Give meaningful names to variables. (What's a, c, x, z ... why are you not using b? )

You don't need import math -- instead of f=row/2
f=math.ceil(f), you can do f = row // 2 (assuming you use python 3).

Note that you can solve the problem more generally, for m x n matrix, which you can initialize as:
matrix = [[0 for col in range(nCols)] for row in range(nRows)]
(see the answer from StackOverflow, provided by @OK).
This
 matrix = [[0] * m] * n, as pointed in the comments, won't work because of list references.

Now, we can also observe that you can fill the "outer rectangle", i.e. matrix[0][:] = range(1, nCols + 1); then, you can fill the rightmost column

cnt += nCols
for row in range(1, nRows):
  matrix[row][rightIdx] = cnt
  cnt += 1
# Bottom row:
matrix[bottomIdx][leftIdx:] = reversed(range(cnt, cnt + nCols - 1) # might be off by 1;
# Complete first column

# Put this in a while loop;

This problem is similar -- once you have the matrix, print it in a spiral order:
Geeks for geeks website.

Also, you can check the solution of LeetCode Prob 54, but I would encourage you to try solving the problem yourself first.
Problem 54 Solution for Problem 54

And here is my solution to Problem 54, similar to Solution 2 (Leetcode Solution link above): My solution :)


Regex.Matches(solutionText, "([^\"]*csproj)")
|> Seq.cast<Match>
|> Seq.map (fun m -> Path.Combine(solutionDirPath, m.Groups.[1].Value))

Why are you using groups? Since the whole match is a single group, you can remove the parentheses from the expression and then directly use m.Value.

Also, you should probably check that the name ends in .csproj, not just csproj and that it's actually the end of the file name.

let codeFilePaths =
    projectPaths
    |> Seq.map (fun projPath ->
        let projectDirPath = Path.GetDirectoryName(projPath)
        let document = XDocument.Load(projPath)
        document.Descendants()
            |> Seq.where (fun desc -> desc.Name.LocalName = "Compile")
            |> Seq.map (fun desc -> Path.Combine(projectDirPath, desc.FirstAttribute.Value)))
        |> Seq.concat

I think the complicated map lambda makes this hard to read, I would instead write it as a local named function. If you don't want to do that, at least make sure to indent your code properly (the first |> Seq.map and the |> Seq.concat should be on the same level).
Instead of the where, you can use the overload of Descendants that accepts a node name (but this means you have to use XML namespaces).
Instead of relying on the first attribute being the right one, I would access the attribute by name.

With all these changes and John Palmer's suggestion about Seq.collect, the code becomes:

let codeFilePaths =
    let codeFilesForProject projPath =
        let projectDirPath = Path.GetDirectoryName(projPath)
        let document = XDocument.Load(projPath)
        let ns = XNamespace.Get "http://schemas.microsoft.com/developer/msbuild/2003"
        document.Descendants(ns + "Compile")
            |> Seq.map (fun desc -> Path.Combine(projectDirPath, desc.Attribute(XName.Get "Include").Value))
    projectPaths |> Seq.collect codeFilesForProject


Possible solutions to remove the use of a Hashtable

It look spretty good to me, but there are a couple of things I would likely change, none of which have to do with the use (or non-use) of a hashtable data structure as it is perfectly suited for this sort of thing.

I would probably change the LoadSettings method a bit as it doesn't actually load settings each time it is called, and then definitely use the generic Dictionary<K,V> instead of the antiquated Hashtable class, thereby removing the need for all that nasty casting.  You could also avoid two lookups when attempting to retrieve a value from the cache by using TryGetValue instead of Contains and then performing another lookup, something like:

public static string GetCacheSetting(string settingName, string defaultValue)
{
    string ret;
    Settings.TryGetValue( settingName, out ret );
    return ret ?? defaultValue;
}

// you may even want to make this private as a caller could
// edit the contents of the cache directly.  You could leave
// GetCacheSetting as the only access point, adding a
// SetCacheSetting method if needed.
private static Dictionary<string, string> _settings;
public static Dictionary<string, string> Settings
{
    get
    {
        if( _settings == null )
        {
            _settings = LoadSettings();
        }

        return _settings;
    }
}

private static Dictionary<string, string> LoadSettings()
{
    HttpRuntime.Cache.Remove( _settings );
    _settings = new Dictionary<string,string>();
    DataAccess da = new DataAccess(); //My DAL
    foreach (DataRow row in da.GetSiteSettings().Tables[0].Rows)
    {
        Settings oSetting = new Settings();
        oSetting.SettingsInitFromRow(row);
        _settings.Add(oSetting.Name, oSetting.Value);
    }

    HttpRuntime.Cache.Insert("SiteSettings",
                             _settings,
                             null,
                             DateTime.Now.AddMinutes(120),
                             Cache.NoSlidingExpiration);

    return _settings;
}


Promise-based fixed delay poller with timeout

Polling is not good.

I'm curious if there is a more idiomatic or flexible way for this to be written.

Generally polling for a state change is not considered best practice so there is no idiomatic approch.
The code

async functions are a promise you don't need to put them inside a promise, you are just doubling up.

 const fixedDelayPoller = new Promise(async () => {
     while (!predicate()) {
         await promiseTimeout(delayMS);
     }
 });

Then the same as with one less promise to negotiate.
 const fixedDelayPoller = (async () => {
     while (!predicate()) {
         await promiseTimeout(delayMS);
      }
 })(); // invoke async function

It seams that JS coders are still getting used to promises as they never name the callbacks. You name the callback resolve but that is inferred and does not describe what the function does

  return new Promise((resolve) => {
    return setTimeout(resolve, ms);
  });

would be better as
  return new Promise(timeup => setTimeout(timeup, ms))

You are creating way too many promises. When you look at the problem you only need one promise that resolves on timeout or predicate() is true. As your code stands you create 5 promises (Promise.race counts as a promise) minimum and then an extra one for each delay timeout.
A better approch is to have the poll function return only one promise. You can then resolve it without the need to create a string of promises one after another.

function poll(predicate, delayMS, timeoutMS){
    var intervalHandle;
    return new Promise(pollingOver => {
        const complete = () => {
            clearInterval(intervalHandle);
            pollingOver();
        }
        intervalHandle = setInterval(() => predicate() && complete(), delayMS);
        setTimeout(complete, timeoutMS);
    });
}

function poll(predicate, delayMS, timeoutMS){
    var intervalHandle;
    return new Promise(pollingOver => {
        const complete = (ready = false) => {
            clearInterval(intervalHandle);
            pollingOver(ready);
        }
        intervalHandle = setInterval(() => predicate() && complete(true), delayMS);
        setTimeout(complete, timeoutMS);
    });
}

// Poll waits fot state to === true or two seconds
test();
var state;
function test() {
    state = false;
    var timer = setTimeout(()=>state = true, Math.random() * 4000)
    poll(() => state, 200, 2000).then(inTime => {
        console.log(inTime ? "State in time" : "State change timed out");
        clearTimeout(timer);
        test();
    });
}

Back to your questions

I'm curious if there is a more idiomatic or flexible way for this to be written. For example, should there be parameters for a callback to be called after the timeout? Or would that be handled by the caller calling poll(x, y, z).then(onFulfilled)? Further, should this function return a boolean rather than a possible void, false in the case of timeout and true otherwise?

If you did need some event to happen on resolution then using poll(...).then( is the better approch.
Should your function return a bool? that is up to you. The predicate has access to the state so it can be used to workout the current state. However it is better to return a result via the promise callback (see snippet above, returns false on timeout)
Why are you polling?
I am having trouble understanding why you need to poll some state. There are many other ways to communicate state changes in JavaScript (TypeScript) without the need for code to run at regular intervals. But without some context it is hard to say which approch would be best.


Your code has multiple bad practices.

There is no speration of concern. Your code is handling display, logic and controlling. All in onde function.

If I look at the function, it tells me it needs nothing (no arguments need to be passed in). So the only thing it should be using are variables that are accessible inside the object scope. BUT it turns out you are using a 'Validate' class and variables from the global scope ($_POST). I only know this because I read the entire code. No really nice towards other developers or the future you demaning that one should read the entire code before knowing how to use it and what is going on. And then ofcourse the biggest problem. al those if's

So, some problems and lets fix those problems.

You sanitize a variable that is handed in by the client ($_POST). You then create an array of possible 'modes' out of the blue. And after that you construct some html with images and a lot of business logic in it. Your function really has to be all knowing!

So, let's sepperate the concerns.

the $mode is clearly something the function needs to do it's magic. So this sould be a paramter that is passed in:

public function gridMenu(String $mode);

Note that the $mode needs to be a string. (obviously)

Another thing this function absolutely needs is the $modes variable. But, this variable doesn't change with every call of the gridMenu() function. It is the same, and should be, during runtime. But it could change over time or even change depending on what user is logged in. So we place this in the constructor of the class:

class Grid {

  private $modes;

  public function __construt($modes) {
    $this->$modes = $modes;
  }

  public function gridMenu(String $mode) { }
}

Now, gridMenu doesnt really say much. I would have to guess what it does: save a menu? does it create one? does it return one? So lets change that name to something more understandable:

class Grid {

  private $modes;

  public function __construt($modes) {
    $this->$modes = $modes;
  }

  public function renderMenu(String $mode) { }
}

Other possibilities are echoMenu, printMenu... Note that i left the word grid out because we are allready in the grid class. Obviously we wouldn't print a non-grid menu out here...

Good, so now we can remove that Validate::sanitize to the outside of the code and that declaration of $modes is no longer hard-coded into the class. This gives us a lot more flexibility,...

Now let's look at what our function does. It creates html. wheut? So it doesn't provide functionality but simply prints some html? So it's is actually a template disguised as a function... the sneaky bastard. We really have to keep an eye on those templates mate. They tend to creep into functions all the time all over the code.

This makes them harder to maintain and makes you write tons of Repeat-Yourself code. For instance if we would no want it to return the data in XML, or in a list instead of divs. Or even worse, have the delete button placed somewhere else, or or.... OOh boy, beter start all over again.

Needless to say, we are doing something really wrong here and we have read all this text for nothing :( Well atleast you know about sepration of concern. And I give you an oher link: SOLID

But what has this todo with you question? Ah it's very easy. What you actually need is a template that handles the display of of those '.hex' divs (what is a hex? and why is action.delete/archive a hex?). You also need some business logic that calculates what 'actions' you can do. and then we need some controller to bring it all together.

Your template would look something like this:

  <div class="hex hex1 hex-<?php echo $mode->hasAction('edit') ? 'enabled' : 'disabled' ; ?>">
    <?php echo $mode->hasAction('edit') ? '': ''; ?>

    //zzz

  <div class="hex hex1 hex-<?php echo $mode->hasAction('delete') ? 'enabled' : 'disabled' ; ?>">
    <?php echo $mode->hasAction('edit') ? '': ''; ?>

    //xxx

  <div class="hex hex1 hex-<?php echo $mode->hasAction('archive') ? 'enabled' : 'disabled' ; ?>">
    <?php echo $mode->hasAction('edit') ? '': ''; ?>

    //zzz

Your business logic 'Mode' and 'ModeFactory' class would look something like this:

class ModeFactory {

  private $modes;

  public function __construt(array $modes) {
    $this->$modes = $modes;
  }

  public function getMode(string $mode) {
    if ( !isset($this->modes[$mode]) ) {
      throw new ModeNotFoundException();
    }
    return new Mode($this->modes[$mode]);
  }
}

class Mode {
  private $actions = $actions;
  public function __construct(array $actions) {
    $this->actions = $actions;
  }
  public function hasAction(string $action) {
    return in_array($this->actions[$action]);
  }
}

class ModeNotFoundException extends Exception {}

NOTE: I used the Factory pattern here, is this the best? not, but it is a pattern that suited my needs and I feld like using it.

Then to bring it all togeter: the controller:

include 'Validate.php'; #the Validate class
include 'Mode.php'; #Modefactory and Mode

//note that now only the controller needs to know
// how the client communicates with this program
$currentMode = Validate::sanitize($_POST['mode']);

//because we pass in the modes+Actions in the factory,
// we can easily change everything.
//For instance we could fetch these mode+actions from a database
$modeFactory = new ModeFactory(array(
  'products'  =>  array('edit', 'delete', 'archive')
));

//we need this variable in the template so lets create it
$mode = $modeFactory->getMode($currentMode);

include 'myHexTemplate.php';

//all done

To sum up: the massive amount of if's wasn't the real problem. The real problem was the seperation of concern and those sneaky template functions. By solving those issues we now not only have better to read code. It is also very flexible, very easy to test etc etc.

Say we want to test a new Mode, we simply create our Mode:

$mode new Mode(array('myTestAction'));

Is this code perfect? no, the names used are horrible. What is a hex? what is a mode? what is an action? These are all generic words and make it very hard actualyl properly reuse this code. But appart from that, I think you get the important lesson here.

Good luck and fire away at the comments. @everyone else: feel free to correct spelling, I honestly don't feel like reading this entire post again for spelling mistakes.


swordTime appears to be a constant and should therefore be:

private static final int SWORD_TIME = 250;

ImageIcon i = new ImageIcon("/Users/myName/Desktop/FarthornPics/charAttacking.png");

Creating a new ImageIcon each time it is rendered is a big fat waste of resources. Create it once, outside the render method, and only refer to it from inside - just as you have done with charImage.

Additionally, as I doubt that path exists on all computers, I would recommend using a relative path or use classpath resources (possibly with the Maven tool).

Thread.yield();

I have to admit that this is the first time ever that I have seen that method being called. When reading the documentation for this method, it seems there is a good reason for why I have never encountered it before.

  It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

I strongly doubt calling this method is any useful for you.

When doing animations, it is helpful if you know the platform you are doing them on. I have to say that Swing is not the most helpful platform to do animations on. There are a couple of tutorials out there for how to do it. What I am mostly noticing in your code is that you don't seem to call repaint or anything like it anywhere, which makes me a bit surprised that this actually works at all.

If you are developing with Java 8, I think you would benefit from using JavaFX which has better support for animations.

If you are interested in developing games with Java, I would strongly recommend using the framework LibGDX.


You can improve time complexity by doubling the space complexity. If you don't modify the input array in place (which is probably a bad idea in real code anyway), you can use System.arraycopy instead of repeatedly reversing parts of the char[]. I also think that would be easier to read. That approach might look something like:

import java.util.Arrays;

public final class Solution {

    private static final char[] INPUT =
            new char[] {
                    'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
                    'm', 'a', 'k', 'e', 's', ' ',
                    'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' };

    private static final char[] OUTPUT =
            new char[] {
                    'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
                    'm', 'a', 'k', 'e', 's', ' ',
                    'p', 'e', 'r', 'f', 'e', 'c', 't' };

    public static void main(final String[] argv) {
        System.out.println(Arrays.equals(OUTPUT, reverseWords(INPUT)));
    }

    private static char[] reverseWords(final char[] input) {
        final char[] output = new char[input.length];
        int outputIndex = 0;
        int lastSpaceIndex = input.length;
        for (int i = input.length - 1; i >= 0; i--) {
            if (input[i] == ' ') {
                final int length = lastSpaceIndex - (i + 1);
                System.arraycopy(input, i + 1, output, outputIndex, length);
                output[outputIndex + length] = ' ';
                outputIndex += length + 1;
                lastSpaceIndex = i;
            }
        }
        System.arraycopy(input, 0, output, outputIndex, lastSpaceIndex);
        return output;
    }
}


I can't say there's anything technically wrong with doing it that way, and maybe some people who are only familiar with "self" in certain languages will get the point, but I think "this" is just as readable, and it saves you some code (along with some of us wondering where in the world "self" was defined if we're looking at a lot of code where the declaration isn't obvious).

So short of adding some extra work for yourself (and raising a couple of eyebrows), I don't see a big problem with it. Do you need it? No. Will it hurt? Not likely.


C hack: replace printf to collect output and return complete string by using a line buffer

Bug

Your code in tprntNewLine() doesn't guarantee that tReturnString is large enough to hold the output string.

Suppose at entry to the function, these are the values of your variables:

sizeOfReturnBuffer = 10;
curPosOutBuffer    = 0;

And then you get an outLine whose length is 80.  After this piece of code:

if (remainingLenOutBuffer < 0) {
    newSize = sizeOfReturnBuffer + sizeof(char)*incrSizeOfReturnBuffer;
    if ((newOutBuffer = realloc(tReturnString, newSize)) != 0) {
        tReturnString = newOutBuffer;
        sizeOfReturnBuffer = newSize;
    } else {
        lenOutLine += remainingLenOutBuffer; //just write part that is still available
        remainingLenOutBuffer = 0;
    }
}

You will increase the size of your output buffer from 10 to 15 (because you only add incrSizeOfReturnBuffer to the current size).

After that, you will then try to copy 80 bytes from outLine into your 15 byte buffer:

snprintf(&tReturnString[curPosOutBuffer], lenOutLine+1, "%s\n", outLineBuffer);

You need to change your reallocation amount to ensure that it is at least enough to hold the length of the line you are trying to append.  For example:

if (remainingLenOutBuffer < 0) {
    int neededSize = -remainingLenOutBuffer;

    if (neededSize < incrSizeOfReturnBuffer)
        neededSize = incrSizeOfReturnBuffer;
    newSize = sizeOfReturnBuffer + neededSize;
    // ...

Style issues

Typically, constants that are #defined are in capital letters and in snake_case. So I would change:

#define initialSizeOfReturnBuffer 10

to

#define INITIAL_SIZE_OF_RETURN_BUFFER 10

There's no need to use sizeof(char).  It's always 1.


Is there a better way to create constants in javascript?

Class syntax should not be used for single instance (static) objects (really class should never be used). Use an Object literal and freeze it.

const AppConstants = Object.freeze({
   NAME : "iVoc",
   VERSION : "0.1B",
});


Golang implementation of Pascal's triangle

It's interesting that you chose to put the code in its own package. I think it's great - but it does make the code a little more difficult to run as an experiment, or on ideone, or something. So, I encourage you to use packages, but remember that the main function/entry point will need to be in a different directory.

Now, as a package, there should be no reason to have an exported function NextRow. Why have you capitalized it? It should be nextRow.

Then, working through your functions, the next most striking thing is the poor choice of variable names. x's that are "lines", y's that are "triangles", etc. Worse, you use the variable x in two different ways in the two different functions. Renaming some variables made it easier to read.

Finally, the go fmt tool will re-format your code to conform to go conventions. You should always do this for your code. It helps when sharing go code with others.

With those changes, I would consider your code to be reasonably good.

On the other hand, I did mess a bit with the nextRow method to use append(..) instead of direct index assignment. I feel the append helps by making the 1 at the beginning and end of the line more obvious.

I also moved the special-case of the first row outside the loop of the Triangle method. This makes it clearer, I feel.

So, your major issues are code style, and naming. The actual code is otherwise OK. Some tweaks may help readability - but that's something you should decide whether it's better.

I put those changes together in a runnable format in ideone.

package main

import (
    "fmt"
    "strings"
)

func nextRow(prevRow []int) []int {
    current := make([]int, 0, len(prevRow)+1)

    current = append(current, 1)

    for i := 1; i < len(prevRow); i++ {
        current = append(current, prevRow[i-1]+prevRow[i])
    }

    current = append(current, 1)

    return current
}

func Triangle(rows int) [][]int {
    triangle := [][]int{}
    if rows <= 0 {
        return triangle
    }
    triangle = append(triangle, []int{1})
    for i := 1; i < rows; i++ {
        triangle = append(triangle, nextRow(triangle[i-1]))
    }
    return triangle
}

func present(line []int) string {
    words := make([]string, len(line), len(line))
    for i, v := range line {
        words[i] = fmt.Sprintf("%4v ", v)
    }
    return strings.Join(words, " ")
}

func main() {
    tri := Triangle(10)
    for _, line := range tri {
        fmt.Println(present(line))
    }
}


Comparing two objects having two nullable date fields

Nullable<T> already does the hard work for you. Just override Equals on your ExpiryDates class (and GetHashCode):

public override bool Equals(object obj)
{
    var otherDates = obj as ExpiryDates;

    return otherDates != null
        && MNL_ExpiryDate.Equals(otherDates.MNL_ExpiryDate)
        && PSL_ExpiryDate.Equals(otherDates.PSL_ExpiryDate);
}

As pointed out by mjolka in a comment. It would be advisible to implement IEquatable<T> (IEquatable<ExpiryDates>) as well. See the documentation for why it's a useful thing to do.

Further edit... It does say in the comments for IEquatable<T> but you should additionally override == and != e.g.

public static bool operator ==(ExpiryDates left, ExpiryDates right)
{
    if (object.ReferenceEquals(left, null))
    {
        return object.ReferenceEquals(right, null);
    }
    return left.Equals(right);
}


Your code is wide open to SQL Injection which is the most dangerous web vulnerability. This occurs when you execute SQL queries with unsanitized user data. By placing the raw $_POST variable directly in your query you are allowing an attacker to inject their own SQL into your query and execute it. They can do anything from stealing data to deleting your database.

To combat this you must use parameterized queries. Stack Overflow covers this very well but here's what your code would like if you use mysqli with prepared statements:

$stmt = $dbConnection->prepare('SELECT * FROM users WHERE email = ?');
$stmt->bind_param('s', $email); // 's' specifies the variable type => 'string'

$stmt->execute();

$result = $stmt->get_result();
$row = $result->fetch_assoc();

You also are wide open to Cross-site scripting (XSS) attacks which is the #7 web vulnerability. This occurs because you take raw $_POST data and output it directly into your HTML. An attacker can place malicious code in this value and attack your users and site once it is rendered by the browser.

When outputting user data, always escape that data. Stack Overflow covers this as well. In PHP you can do this by using htmlspecialchars().

<?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?>

You will notice that the one $_POST variable, $_POST['email'], has left your site wide open to attack. Before you even attempt to use it you should validate it indeed is a valid email address. If it is not, you should report an error and not attempt to use it as it obviously is invalid and useless anyway.

PHP offers an easy way to validate an email addresses. filter_var() with the FILTER_VALIDATE_EMAIL flag will validate if an email address is valid.

$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // email is invalid. report error and abort.
}

On a different note, you start your script off by checking to see if a user is an admin. If they are not you use header() to do a redirect away from that page. That's usually okay but you should follow it with a call to exit() to ensure the script stops executing. If not, the code below may still execute and, combined with other vulnerabilities in the page, leave you open to attack.

if ($_SESSION['admin'] !== true) {
    header('Location: /login.php?');
    exit;
}


Set a default if key not in a dictionary, *or* value is None

for message in d.get('messages') or ():
    do_something()

get returns None by default for missing keys.
a or b evaluates to b when bool(a) == False. An empty list and None are examples of values that are false in a boolean context.
Note that you cannot use this trick if you intend to modify the possibly empty list that is already in the dict. I'm using () instead of [] to guard against such mistakes. Also, CPython caches the empty tuple, so using it is slightly faster than constructing an empty list.


You want to synchronize two parts of your iteration and parallelize the each one of them independently. A good option is splitting the code in two:

int main()
{
  const int n = 100;

  #pragma omp parallel
  {
  #pragma omp for
  for (int i=0; i<n; i++)
  {
      int thread_ID = omp_get_thread_num();
      printf("%d) work 1 %d\n", thread_ID, i);
  } // barrier (implicit, unless using 'nowait')

  #pragma omp for
  for (int i=0; i<n; i++)
  {
      printf("    %d) work 2 %d\n", thread_ID, i);
  } // barrier
  } // omp parallel
  return 0;
}


Is this an elegant/accurate simulation of the Monty Hall problem?

ok, so i ended up changing more than was strictly necessary, sorry.  as you probably know, it does pay to change doors, so your code did have a bug.  i didn't try to trace it down exactly, but i assume it was related to you having 4 doors instead of 3, which i guess was because you had

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

instead of

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

in C you always start from 0 and use < in loops.  it's the law.

[in general your code is super neat and pretty good.  you had a muddle with array indexing, which is very common, and didn't make use of enum, but apart from that, it was nice code.  edit: also, your general approach was fine.  this is a good way to test the problem.]

some other issues were:

the random number generation was strangely general, yet always picked a door.  it also started from 1, which i guess is related to the confusion over door array indexing.
it wasn't clear to me what the doors array contained at first.  when i understood i clarified it with an enum.
it wasn't clear to me what the two groups were ("control" didn't explain things).  when i understood i clarified things with another enum (note the GROUP_COUNT trick which gives the number of entries in the enum, excluding that).
given the group enum, there's no need to have two print statements - we can use an array of group names.  and there's no need for arrays of results, since we have everything in a loop now.
i clarified the logic in OpenGoatDoor - the code initialises the door to choice, which we know is "bad" so that the while is triggered and so we only need a single call to RandomDoor.
i tried to clarify the logic in OtherDoor but i am not sure i helped.
i don't think ChoiceWasCar is necessary - with the enum it's pretty clear what return doors[choice] == car means.

here's the modified code.  thanks for posting - i was bored and this was interesting to look at.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#undef DEBUG
#define DOOR_COUNT 3
#define TEST_COUNT 1000000

typedef enum {goat, car, opened} door;
door doors[DOOR_COUNT];

typedef enum {nochange, change, GROUP_COUNT} group;
char *groupName[GROUP_COUNT] = {"No Change", "Change"};

void InitRandom();
int RunTest(group g);
void RandomizeDoors();
int RandomDoor();
void OpenGoatDoor(int choice);
int OtherDoor(int choice);

int main (void)
{
  InitRandom();

  for (group g = 0; g < GROUP_COUNT; ++g) {
    int wins = 0;
    for (int i = 0; i < TEST_COUNT; ++i) {
      wins += RunTest(g);
    }
    printf("%s:\n\t%d tests run\n\t%d win car.\n\n",
           groupName[g], TEST_COUNT, wins);
  }
  return 0;
}

void InitRandom()
{
  unsigned int iseed = (unsigned int)time(NULL);
  srand (iseed);
}

int RunTest(group g)
{
  RandomizeDoors();
  int choice = RandomDoor();
  #ifdef DEBUG
  printf("Choice is: %d\n", choice);
  #endif
  OpenGoatDoor(choice);
  if (g == change) {
    choice = OtherDoor(choice);
  }
  return doors[choice] == car;
}

void RandomizeDoors()
{
  char carDoor = RandomDoor();
  for (int i = 0; i < DOOR_COUNT; i++) {
    doors[i] = carDoor == i ? car : goat;
    #ifdef DEBUG
    printf("Door %d is %d\n", i, doors[i]);
    #endif
  }
  #ifdef DEBUG
  printf("\n");
  #endif
}

int RandomDoor()
{
  // this is very slightly biased, but we don't care.
  return rand() % DOOR_COUNT;
}

void OpenGoatDoor(int choice)
{
  int randomDoor = choice;
  while ( randomDoor == choice || doors[randomDoor] != goat) {
    randomDoor = RandomDoor();
  }
  #ifdef DEBUG
  printf("Opened Door is %d\n", randomDoor);
  #endif
  doors[randomDoor] = opened;
}

int OtherDoor(int choice)
{
  int otherDoor = choice;
  while ( otherDoor == choice || doors[otherDoor] == opened ) {
    otherDoor = (otherDoor + 1) % DOOR_COUNT;
  }
  return otherDoor;
}

for anyone following along at home, gcc needs -std=c99.

output:

: gcc -std=c99 mhall.c; ./a.out
No Change:
        1000000 tests run
        333875 win car.

Change:
        1000000 tests run
        667098 win car.


Parse sentences and calculate mathematical results

The problem is that you are manipulating text without using Regular Expressions.

Regular expressions are a tool made specifically for text manipulation (search, delete, replace ... ) and are extremely good at their job.

The over-complication you experience comes from the use loops, conditionals and arithmetic to manipulate strings.

Here is a solution using regular expressions:

def text_calculation(text)
  a, b = text.split(/[^0-9]/).reject(&:empty?).map(&:to_i)
  text.include?("gains") ? a + b : a - b
end

First line explanation

text.split(/[^0-9]/)

This splits the text at every character that is not a digit (^ negates and [0-9] means from 0 to 9.

The output is this list:

["", "", "", "", "", "", "", "", "", "", "48", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "4"]

Almost what we want, we just need to remove (reject) the empty strings (empty?):

.reject(&:empty?)

So now we have ["48", "4"] that we must convert to integers before we can do arithmetic on, map applies a function to each item of a list and to_i converts to integer so .map(&:to_i)

Second line explanation

We add if we find "gains" else subtract (condition ? if_true : if_false is the Ternary operator)

.scan

We need to find the parts of the string that match a given regex, given that the regex /\d+\ matches all the subsequent strings of digits.

We must "find all regex matches in ruby", searching Google for such a task lands us on StackOverflow reveals that .scan is exactly what we can use. (The second Stack Overflow example is even about searching digits in a string!)

def text_calculation(text)
  a, b = text.scan(/\d+/).map(&:to_i)
  text.include?("gains") ? a + b : a - b
end

This code is more direct than splitting and filtering.


Okay, first up, I'm a bit rusty with C++, so I apologize if this isn't formatted correctly.

But, the first thing that leaps out is "Single Responsibility Principle".  Aka - each function should be responsible for one thing and have one reason to change.

Or in short: don't write everything in your Main().

What is your Main() doing, at a high level?  It's:

Grabbing inputs for how many people and what bills they have
It's setting up the register (with no bills in it)
It's looping through each person
It's checking how that person impacts the current register
It's outputting the success/failure of the venture.

Awesome!  So... what should your main look like in an abstract sense?

main()
{
    int patronCount = GetPatronCount();
    int[] billAmounts = GetBillAmounts();
    int[] register = SetUpRegister();
    for (i = 0; i < patronCount; i++)
    {
        bool wasAbleToMakeChange = MakeChangeForPatron(register, billAmounts[i]);
        if (!wasAbleToMakeChange)
        {
            // code to return out with failure
        }
    }
    // code to return success
}

So... why would we do this?  Well, because right now, if you need to tweak a line of code in your code?  That could have ramifications all throughout your function.  You can't exactly digest it in small bits, because everything has 'scope' with everything else.  And if you needed to change something, you'd have to consider how that change affects everything else in that function.

This is incredibly important as you grow as a programmer - you're going to be changing code a lot more than you're going to be composing it - and the simpler you can make changing it, the better off you'll be.

Also, it becomes much easier to see what the program does.  Because the function names and variable names document exactly what it's doing at a high level.  It's getting a patron count.  Imagine someone reading your code (and only your code - no explanations)... how quickly would they figure out what it's doing?  Contrast that to my version's main().  So if someone else needs to work with your code (or if you need to work with it, but don't remember it very well) it'll be able to be grok'ed a lot quicker.


Is coding to an interface with regards to PDO the right thing to do?

This feels quite over-engineered to me, when i can do the work of all three classes in one line of code.

echo new PDO('mysql:host=localhost;dbname=test', 'root', 'root');

The big question to ask here is: What do you gain?

Every class, every function, every line of code should be able to justify its existence.  More code means more cognitive load -- that's more stuff to have to think about whenever you want to change/add/fix something, so you don't want to add stuff willy-nilly.  It should either reduce overall complexity, add flexibility, or in some other way make the application better.

Here, you add two classes and an interface (adding complexity) and hard-code the connection params (reducing flexibility).  So what makes these classes an improvement over the one line above?  What do you gain from that indirection, that justifies the cost?

"Coding to an interface" doesn't necessarily mean using the interface keyword.  "Interface" here is used in the language-agnostic sense, and basically refers to an API.   When you code to an interface, you're simply using an API that doesn't make the consumer rely on implementation details.  When you use PDO, to some extent, you are already doing that.  The whole point of PDO is to hide a lot of the DBMS-specific stuff behind a common API, so all you have to know is the PDO API and general SQL stuff.

Since you're returning PDO objects, you're not really hiding much (if any) of the implementation.  I still have to know PDO, on top of how to use your API to get a usable PDO object.  You can't really use anything but PDO, because you've married your API to it.  And if i want to use a different database, i have to create a new class.

A more useful abstraction would hide the PDO objects from the user as well, so that someone using this code only needs to know two things -- your API, and general SQL stuff.  But at that point, you're starting to reinvent PDO.

As for the code itself, if you really want to keep it...

The name MySQLConnector suggests that it is a special type of Connector.  It's not -- it's a special type of DatabaseInterface.  Consider a different name.  I might suggest TestDatabase if you're going to keep the connection info hard-coded, or MySQLDatabase if you make it general enough to be used for other databases.
Never throw new \Exception.  There is never a good reason, other than laziness.  And here, even laziness wouldn't suffice -- if you're not handling an exception, you can simply not bother to catch it.  By catching it and throwing a whole new exception that's as generic as you can legally make an exception, you may be tossing out essential info -- like the previous exception's stack trace! -- that could save you days of debugging.

If you don't want the user to have to know that a PDO exception may occur, then create your own type and wrap the exception in that.

class DatabaseException extends \RuntimeException { }

...

try {
    return new \PDO ($dsn, $user, $pass);
}
catch (\PDOException $e) {
    throw new DatabaseException("Unable to connect", 0, $e);
}

Now the caller can react specifically to database exceptions, if it chooses.  It might try the connection again, for example.  When everything is an Exception, on the other hand, exceptions become all but indistinguishable, unless you resort to some ugliness like parsing the exception message (which is really meant for humans, not code).
$obj->db->connect() is a violation of what's called the Law of Demeter (LoD).  The Law basically says that the only things your code should be talking to are the things it can access without traversing more than one object other than $this*.  You should be telling $obj to connect, rather than having to know about $obj->db at all.  This keeps it easier to change one class without having to change code in dozens of different places.

* Most languages boil LoD down to "no more than one dot".  But that is a bit oversimplified -- particularly in PHP, which doesn't allow for an implicit $this.


I can't comment on variable names because I don't know your language, this will limit the scope of the review I can do and I hope you understand everything in this review / answer. The memory management is good, I don't see any memory leaks.
Test for Possible Memory Allocation Errors
In modern high level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in unknown behavior (UB).
Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).
To prevent this unknown behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL.
Example of Current Code:
        nomes = realloc(nomes, (i + 1) * sizeof(char **));
        nomes[i] = NULL;
        palavraspornome = realloc(palavraspornome, (i + 1) * sizeof(int));
        j = 0;
        do

Example of Current Code with Test:
    do
    {
        nomes = realloc(nomes, (i + 1) * sizeof(char **));
        if (nomes != NULL)
        {
            nomes[i] = NULL;
            palavraspornome = realloc(palavraspornome, (i + 1) * sizeof(int));
            if (palavraspornome == NULL)
            {
                fprintf(stderr, "Memory allocation error when allocating palavraspornome.\nUnable to recover, program exiting.\n");
                return EXIT_FAILURE;
            }
        }
        else {
            fprintf(stderr, "Memory allocation error when allocating nomes.\nUnable to recover, program exiting.\n");
            return EXIT_FAILURE;
        }
        j = 0;
        do

A good way to get rid of some of the code repetition would be to create a function that allocates memory, does the test, reports the error when it happens and exits the program.
void *safe_memory_allocation(size_t size_to_allocate)
{
    void *return_pointer = malloc(size_to_allocate);
    if (return_pointer == NULL)
    {
        fprintf(stderr, "Memory allocation error .\nUnable to recover, program exiting.\n");
        exit(EXIT_FAILURE);
    }

    return return_pointer;
}

Convention When Using Memory Allocation in C
When using malloc(), calloc() or realloc() in C a common convetion is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes.
    do
    {
        nomes = realloc(nomes, (i + 1) * sizeof(*nomes);
        if (nomes != NULL)
        {
            nomes[i] = NULL;
            palavraspornome = realloc(palavraspornome, (i + 1) * sizeof(*palavraspornome));
            if (palavraspornome == NULL)
            {
                fprintf(stderr, "Memory allocation error when allocating palavraspornome.\nUnable to recover, program exiting.\n");
                return EXIT_FAILURE;
            }
        }
        else {
            fprintf(stderr, "Memory allocation error when allocating nomes.\nUnable to recover, program exiting.\n");
            return EXIT_FAILURE;
        }
        j = 0;
        do

Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least 3 sub functions that can be extracted from main(), each of the major loops is a candidate for a function, some of the smaller loops may also be good candidates. A sample function that you could implement if you are not on a POSIX where this is a C library function is char *strdup(const char *str1) (this function was merged into the C ISO standard in 2019).
The implementation of strdup() would look something like this:
char *strdup(const char *original_string)
{
    size_t new_size = strlen(original_string) + 1;
    char *duplicate = calloc(sizeof(*original_string), new_size);
    if (duplicate != NULL)
    {
        memcpy(&duplicate[0], original_string, new_size);
    }
    return duplicate;
}

Whether you write or own or use the library version strdup() returns NULL if the memory allocation failed so the value must be tested before use.
Possible Performance Improvements
Rather than use character input (letra = getchar();) get a line of text at a time using fgets(char *buffer, size_t buffer_size, FILE *filename). This reduces the amount of code necessary and it will be faster than character input.
Instead of
        do
        {
            nomes[i] = realloc(nomes[i], (j + 1) * sizeof(char *));
            nomes[i][j] = NULL;
            k = 0;
            do
            {
                letra = getchar();
                nomes[i][j] = realloc(nomes[i][j], (k + 1) * sizeof(char));
                nomes[i][j][k] = letra;
                k++;
            } while ((letra != 10) && (letra != 32) && (letra != 36));
            nomes[i][j][k - 1] = '\0';
            j++;
        } while ((letra != 10) && (letra != 36));

Use
        do
        {
            nomes[i] = realloc(nomes[i], (j + 1) * sizeof(char *));
            nomes[i][j] = NULL;
            k = 0;
            char buffer[1024];
            if (fgets(buffer, 1024, stdin) != 0)
            {
                nomes[i] = strdup(buffer);
            }
            j++;
        } while ((letra != 10) && (letra != 36));
        palavraspornome[i] = j;

Rather than calling realloc() for every new string create an array of an arbitrary number of names and then reallocate that array when the capacity is reached.
the following code is a basic idea, it may not compile properly or run
char ***resize_nomes_array(char ***nomes, size_t *current_capacity, int i)
{
    char ***new_nomes = NULL;

    if (current_capacity == 0)
    {
        *current_capacity = 10;
    }
    else
    {
        *current_capacity = (size_t)(*current_capacity * 1.5);
    }

    if (nomes == NULL)
    {
        new_nomes = calloc(*current_capacity, sizeof(*new_nomes));
    }
    else
    {
        new_nomes = realloc(nomes, *current_capacity * sizeof(*nomes));
    }

    if (new_nomes == NULL) {
        fprintf(stderr, "Memory allocation error when allocating nomes.\nUnable to recover, program exiting.\n");
        exit(EXIT_FAILURE);
    }

    for (size_t index = i; index < *current_capacity; index++)
    {
        new_nomes[index] = NULL;
    }
    return new_nomes;
}