Firstly, to address inheritance concerns, I use a t4 template to get around the single inheritance problem. ie. for every class where I need to introduce dispose support, I generate the an abstract base class that inherits from that class. Works a treat.

Now, to your code. Here are the things that jump out at me:

Constructors should be protected because the base class is abstract. This would make the code clearer to me, but YMMV.
Lose the whole unmanaged resource tracking. It adds complexity without value. Just call SuppressFinalize() regardless - it's the recommended pattern, anyway.
Your code is not thread-safe. Consider, for example, what happens if multiple threads call Dispose() simultaneously. You're got the potential for multiple calls to DisposeManagedResources() etcetera.

FWIW, here is an example Disposable base class generated by my t4 template:

// Generated by t4 template in Utility project. DO NOT EDIT!
#pragma warning disable 1591, 0612
#region Designer generated code

namespace Foo
{
    using System;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Threading;
    using Kent.Boogaart.HelperTrinity.Extensions;

    /// <summary>
    /// A useful base class for disposable objects that inherit from <see cref="object"/>.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This base class simplifies the implementation of disposable objects by providing common functionality such as thread-safety on <see cref="Dispose"/> calls,
    /// and a <see cref="Disposing"/> event for pre-disposal notification.
    /// </para>
    /// </remarks>
    public abstract class DisposableBase : object, IDisposable
    {
        private const int DisposalNotStarted = 0;
        private const int DisposalStarted = 1;
        private const int DisposalComplete = 2;

#if DEBUG
        // very useful diagnostics when a failure to dispose is detected
        private readonly StackTrace creationStackTrace;
#endif

        // see the constants defined above for valid values
        private int disposeStage;

#if DEBUG
        /// <summary>
        /// Initializes a new instance of the DisposableBase class.
        /// </summary>
        protected DisposableBase()
        {
            this.creationStackTrace = new StackTrace(1, true);
        }

        /// <summary>
        /// Finalizes an instance of the DisposableBase class.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1063", Justification = "The enforced behavior of CA1063 is not thread-safe or full-featured enough for our purposes here.")]
        ~DisposableBase()
        {
            var message = string.Format(CultureInfo.InvariantCulture, "Failed to proactively dispose of object, so it is being finalized: {0}.{1}Object creation stack trace:{1}{2}", this.ObjectName, Environment.NewLine, this.creationStackTrace);
            Debug.Assert(false, message);
            this.Dispose(false);
        }
#endif

        /// <summary>
        /// Occurs when this object is about to be disposed.
        /// </summary>
        public event EventHandler Disposing;

        /// <summary>
        /// Gets a value indicating whether this object is in the process of disposing.
        /// </summary>
        protected bool IsDisposing
        {
            get { return Interlocked.CompareExchange(ref this.disposeStage, DisposalStarted, DisposalStarted) == DisposalStarted; }
        }

        /// <summary>
        /// Gets a value indicating whether this object has been disposed.
        /// </summary>
        protected bool IsDisposed
        {
            get { return Interlocked.CompareExchange(ref this.disposeStage, DisposalComplete, DisposalComplete) == DisposalComplete; }
        }

        /// <summary>
        /// Gets a value indicating whether this object has been disposed or is in the process of being disposed.
        /// </summary>
        protected bool IsDisposedOrDisposing
        {
            get { return Interlocked.CompareExchange(ref this.disposeStage, DisposalNotStarted, DisposalNotStarted) != DisposalNotStarted; }
        }

        /// <summary>
        /// Gets the object name, for use in any <see cref="ObjectDisposedException"/> thrown by this object.
        /// </summary>
        /// <remarks>
        /// Subclasses can override this property if they would like more control over the object name appearing in any <see cref="ObjectDisposedException"/>
        /// thrown by this <c>DisposableBase</c>. This can be particularly useful in debugging and diagnostic scenarios.
        /// </remarks>
        /// <returns>
        /// The object name, which defaults to the class name.
        /// </returns>
        protected virtual string ObjectName
        {
            get { return this.GetType().FullName; }
        }

        /// <summary>
        /// Disposes of this object, if it hasn't already been disposed.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1063", Justification = "The enforced behavior of CA1063 is not thread-safe or full-featured enough for our purposes here.")]
        [SuppressMessage("Microsoft.Usage", "CA1816", Justification = "GC.SuppressFinalize is called indirectly.")]
        public void Dispose()
        {
            if (Interlocked.CompareExchange(ref this.disposeStage, DisposalStarted, DisposalNotStarted) != DisposalNotStarted)
            {
                return;
            }

            this.OnDisposing();
            this.Disposing = null;

            this.Dispose(true);
            this.MarkAsDisposed();
        }

        /// <summary>
        /// Verifies that this object is not in the process of disposing, throwing an exception if it is.
        /// </summary>
        protected void VerifyNotDisposing()
        {
            if (this.IsDisposing)
            {
                throw new ObjectDisposedException(this.ObjectName);
            }
        }

        /// <summary>
        /// Verifies that this object has not been disposed, throwing an exception if it is.
        /// </summary>
        protected void VerifyNotDisposed()
        {
            if (this.IsDisposed)
            {
                throw new ObjectDisposedException(this.ObjectName);
            }
        }

        /// <summary>
        /// Verifies that this object is not being disposed or has been disposed, throwing an exception if either of these are true.
        /// </summary>
        protected void VerifyNotDisposedOrDisposing()
        {
            if (this.IsDisposedOrDisposing)
            {
                throw new ObjectDisposedException(this.ObjectName);
            }
        }

        /// <summary>
        /// Allows subclasses to provide dispose logic.
        /// </summary>
        /// <param name="disposing">
        /// Whether the method is being called in response to disposal, or finalization.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
        }

        /// <summary>
        /// Raises the <see cref="Disposing"/> event.
        /// </summary>
        protected virtual void OnDisposing()
        {
            this.Disposing.Raise(this);
        }

        /// <summary>
        /// Marks this object as disposed without running any other dispose logic.
        /// </summary>
        /// <remarks>
        /// Use this method with caution. It is helpful when you have an object that can be disposed in multiple fashions, such as through a <c>CloseAsync</c> method.
        /// </remarks>
        [SuppressMessage("Microsoft.Usage", "CA1816", Justification = "This is a helper method for IDisposable.Dispose.")]
        protected void MarkAsDisposed()
        {
            GC.SuppressFinalize(this);
            Interlocked.Exchange(ref this.disposeStage, DisposalComplete);
        }
    }
}

#endregion Designer generated code
#pragma warning restore 1591, 0612


LINQ query to select subjects of interest

In terms of "SQL" what you need is a "Left Outer Join". So I would suggest this:

using (var db = CreateContext())
{
    var subjectDtos = from subject in Subjects
                      join interest in Interests on subject.SubjectId equals interest.SubjectId into si
                      from interest in si.DefaultIfEmpty()
                      select new SubjectDto { Subject = subject, HasBeenAdded = interest != null };
    return subjectDtos.Distinct().ToList();
}

And here is why:

I think that LINQ query is more readable in 'SQL like' format.
With the join clause you retrieve only the "subjects" that have an "interest". But with potential duplications if more than one "interest" has the ID of the same "subject" (For this reason I introduced the "Distinct" in the query, you can remove if the duplicate results interest you).
As a matter of consistency I suggest you rather than use the constructor, initialize the property directly.
For "DefaultIfEmpty" steatment docs go here. The Left Outer Join is there.

UPDATE My first code does not work. Fixed and tested now :)


Exponentiation by squaring in x64 Linux Assembly

Testing for n == 1 before handling a negative n seems like a bug. Consider what would have happen with n == -1:

n is not 1. Branch to _notEqualsOne.
n is less than 0. Branch to _lessthan. Now n becomes 1.
The code falls through all the way to _loop1.
n is odd. Branch to _odd.
y := x * y; x := x * x; n := 0`
_condition fails; fall through the return x * y.

Now, this is bad: we are returning an inversed cube of the original x.
Postpone equality for 1 testing until the negative case is handled.

Eliminate _equalsOne label:
  cmp r9, 1
  jne _notEqualsOne

  mov rax, r8
  ret

_notEqualsOne:

cmp r9, 0 is executed twice. This is redundant (keep in mind that jne does not affect the flags):
  cmp r9, 0
  jne _notZero
  ; next two lines is what your code does at _ezero
  mov rax, 1
  ret

_notZero:
  jnl _positive
  ; handle a negative case here:
  ; x := 1/x
  ; n := -n
  ; and proceed with the _positive case
  ....

_positive:
  ; A regular case. n > 1 is guaranteed.

Again, _even and _odd lead to some code duplication.  x := x * x and n := n/2 are spelled out in both branches. Consider
  test al, 1
  jz _even

  ; n is odd here
  ; y := x * y
  ; n := n - 1

_even:
  ; x := x * x
  ; n := n / 2

Division by 2 is better be a right shift. One instruction versus four; a definite win.

while n > 1 style loop looks more natural than do ... while n > 1.


Unnecessary loop

I noticed this code:

for(int i = 1; i < 2; i++)
{
    number = 1 + (rand()%2);
}

It's a loop that loops exactly once, and it doesn't even use i inside the loop.  So you can just remove the loop part:

number = 1 + rand()%2;

Unecessary recursion

At the end of headsOrTails(), you have this code:

while((playAgain == 'Y') || (playAgain == 'y')){
    headsOrTails();
}
while((playAgain == 'N') || (playAgain == 'n')){
    exit(EXIT_FAILURE);
}

Each while here could really be an if.  Neither of the loops actually loop.
It's not a good practice use recursion for no reason.  Ideally, you would have a loop in main() that calls headsOrTails() as long as the user wants to keep playing.  That way, you wouldn't need recursion.  The only reason this even works instead of continuing indefinitely is because you call exit() eventually.
Why EXIT_FALURE?  That means your program will always return failure.  I would use EXIT_SUCCESS instead.


TL;DR: Be clear, consistent and efficient, don't assume things and verify that the output of functions is as expected

Your code doesn't just compare candidates, it also creates new records. As such your function should be appropriately named e.g. compareAndCreateCandidates.
Comments are useful. You can declare a phpdoc style comment for your method and add comments to clarify any corner case e.g. the reasoning behind the if (empty($constituency)) code block.
Searches with 'LIKE', '%'. imply that unique identifiers are not being used. The % should be removed if the fields are unique. If not, you should find a unique field or a combination of fields that is unique for each entry and use that instead.
Two candidates in different parties and constituencies cannot share the same name i.e. a John Smith will not be created if another exists in the database. The criteria should be updated as in (3) above.
Since you are using laravel you should stick to the PSR-2 coding conventions e.g. for control structures:

  There MUST be one space after the control structure keyword
  There MUST NOT be a space after the opening parenthesis
  There MUST NOT be a space before the closing parenthesis
  There MUST be one space between the closing parenthesis and the opening brace
  The structure body MUST be indented once
  The closing brace MUST be on the next line after the body

Use strpos() instead of preg_match(). From the docs:

  Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.

Use either single or double quotes consistently for plain strings:

where('ConstituencyName', 'like',"%"."kingston Eastern")
Since you are using camelCase for variables make sure this is consistent e.g. $electionparty, $electionconstituency
The line echo $electionConstituency->ConstituencyName; looks like test code and should be removed. If not, then it violates the PSR-1 requirement that files should either declare something or have a side effect e.g outputting html. The ConstituencyNames should be saved in an array or string and returned by the function instead of echoing them.
Several variables are only used once and should not be initialized e.g $electionCandidates, $result
There is no check to ensure $electionParty and $politicalParty are not null.
The code assumes each model will be saved without error. The database saves should be wrapped in a transaction with proper error handling.

The code with some issues fixed is as follows:

/**
 * This is where a description of the method's purpose goes
 */

public function compareAndSaveCandidates()
{
    foreach (ElectionCandidate::all() as $electionCandidate) {
        $candidateName = $electionCandidate->CandidateFirstname . " " . $electionCandidate->CandidateLastname;
        if (!Candidate::where([
             ['candidateName', '=', $candidateName],
             //other criteria
        ])->first()) {
            $electionconstituency = ElectionConstituency::where('ConstituencyID', '=', $electionCandidate->ConstituencyID)->first();
            $constituency = Constituency::where('ConstituencyName', '=', strtolower($electionConstituency->ConstituencyName))->first();
            //echo $electionConstituency->ConstituencyName;

            //This is a corner case and deserves a comment
            if (!$constituency) {
                if ((strpos($electionConstituency->ConstituencyName, 'KINGSTON EAST & PORT ROYAL'))) {
                    $constituency = Constituency::where('ConstituencyName', 'like', '%' . 'kingston Eastern')->first();
                }
            }

            $electionParty = ElectionParty::where('PartyID', 'like', '%' . $electionCandidate->PartyID)->first();
            $politicalParty = PoliticalParty::where('partyName', 'like', '%' . $electionParty->PartyAbbr)->first();

            $candidate = new Candidate();
            $candidate->candidateName = $candidateName;
            $candidate->constituency_Id = $constituency->id;
            $candidate->party_id = $politicalParty->id;
            $candidate->save();
        }
    }
}


Return a String containing only alphabets without spaces

char ch;

In general, we want to declare as late and at as small a scope as possible.  You never use this outside the loop, so it could just be

        char ch = string.charAt(i);

inside the loop.

Even better, use the range-based/foreach style:

    for (char character : string.toCharArray()) {

Now you don't have to worry about i or charAt at all.

If you're using Java 8, you may want to look into the streaming API.  E.g. combining this post and this post.

    return string.codePoints()
                 .filter( Character::isAlphabetic )
                 .collect( StringBuilder::new,
                           StringBuilder::appendCodePoint,
                           StringBuilder::append )
                 .toString();

I haven't tested this.  I just combined the two solutions to similar problems in a way that I believe does what you want.


I find enums are ofte easier to use then booleans. At some point you probably will want to search for users so consider this:

User FindUserByStatus(LoginStatus status)

and its usage

userSearch.FindUserByStatus(LoginStatus.LoggedIn)

vs

User FindUserByStatus(bool loginStatus)

and its usage

userSearch.FindUserByStatus(true);

but even with the enum you could do

if (login) { .. }

by adding an implicit cast to the Login

public static implicit operator bool(Login login) => login.Status == LoginStatus.LoggedIn;


Just reviewing what you've got here...

Indentation

The code would read much better with proper indentation:

Function FillInternetForm()
    Dim HWNDSrc As Long
    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    HWNDSrc = ie.HWND

    ie.Navigate "http://helppointinfo.farmersinsurance.com/OCR/Labor_Rates/laborrates.asp"
    ie.Visible = True
    While ie.Busy
        DoEvents  'wait until IE is done loading page.
    Wend
    ie.Document.getElementById("DirectZip").Value = Sheets("NAT").Range("C2").Value

    SetForegroundWindow HWNDSrc

    Application.SendKeys "{TAB 11}", True
    DoEvents
    Application.SendKeys "{NUMLOCK}", True

End Function

Public Sub RunRates()
    Call FillInternetForm
End Sub

Call Instruction

As answered in this StackOverflow question, the Call instrucation is a relic from ancient versions of VB, it's not needed and, IMO, only adds clutter.

Public Sub RunRates()
    FillInternetForm
End Sub

Coupling

The FillInternetForm function is needlessly coupled with the Excel object model - Sheets("NAT").Range("C2").Value should be passed as a String parameter to the function:

Function FillInternetForm(ByVal DirectZipValue As String)
    '...
    ie.Document.getElementById("DirectZip").Value = DirectZipValue
    '...
End Function

Public Sub RunRates()
    FillInternetForm Sheets("NAT").Range("C2").Value
End Sub

Function?

VB functions are procedures with a return value. If it's not specified, then it's returning a Variant - here FillInternetForm is never assigned a return value, and whatever it would be returning wouldn't be used. In other words, you have a procedure (Sub), not a function. The signature should be modified like this:

Public Sub FillInternetForm(ByVal DirectZipValue As String)

I like things explicit - if a member is going to be Private, it needs a Private access modifier; if it's going to be Public, I don't like relying on VB's "defaults", mostly because I code in different languages where these defaults differ (C#). Having explicit access modifiers eliminate the possible confusion, but that might be only me.

Lastly, I don't understand why FillInternetForm would have to press NUM LOCK, this looks misplaced, and has a side-effect that could be surprising to whoever is running that code.


I've got a few suggestions for you:

Wrap your entire thing in an IIFE, you don't need any external access to any of your vars.

;(function(){
   ...your code goes here
}());

Now your period to change slide isn't in the global name space.

You don't need to attach your startSlideSnow and stopSlideShow to the jQuery namespace (e.g. $.startSlideShow) you are just polluting jQuery's namespace which isn't goot.

Use setTimeout() instead of setInterval.  The setTimeout function will only run after its callback is done, setInterval runs at the interval no matter what, so you can run into some strange behavior.

Try to not repeat selectors, and use chaining:

$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active');

could become:

$(this).parent().addClass('active').siblings().removeClass('active');

You could optimize your selectors as well, remember jQuery goes right to left, so in a lot of cases you're getting all li items on the page and filtering those.  It might be a marginal speed boost doing $( 'selector' ).find( 'li' );.

There are a few more things you could do, like pluginize it, but these are the biggest things I see right away.


Count distinct records in a JOINed SQL query

I've modified the query to use a GROUP BY instead of a COUNT DISTINCT, which has sped up the execution time.

SELECT COUNT(*) AS totalDevices
FROM (
  SELECT d.id
  FROM Device AS d
  INNER JOIN TestResult AS r ON r.deviceId = d.id
  WHERE serialNumber BETWEEN '000000001000' AND '000000002020'
    AND r.createdAt BETWEEN '2020-03-27T11:54:43.100Z' AND '2020-04-01 09:21:02.362768'
  GROUP BY d.id
);

This query shows the following execution time with 1,000,000 records:

Run Time: real 3.433 user 0.953125 sys 2.484375

The COUNT DISTINCT query shows the following execution time:

Run Time: real 8.090 user 1.562500 sys 6.500000

So the GROUP BY query takes just under half of the time of the COUNT DISTINCT query.


Handling keyup events with throttle or debounce in Javascript/jQuery

I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.

 function requestAnimationTimeout(callback, delay) {
    var dateNow = Date.now;
    var requestAnimation = window.requestAnimationFrame;
    var start = dateNow();
    var stop;

    var timeoutFunc = function () {
      if (dateNow() - start < delay) {
       return stop || requestAnimation(timeoutFunc);
      } else {
       return callback();
      }
    };

    requestAnimation(timeoutFunc);

  }

And then simply use requestAnimationTimeout in place of the native setTimeout.


Read list of dictionaries with nested dictionaries

Currently you iterate over each dictionary twice. You can do it in one pass:

for v in d:
    commodities_reference = []
    for k, g in v.items():
        if isinstance(g, dict):
            commodities_reference.append(g["id"])
            commodities_reference.append(g["name"])
        else:
            commodities_reference.append(g)

Note that this appends the values when it encounters it. This means that in Python < 3.7 (cPython < 3.6) it is not guaranteed that the dictionary is actually the last item to be looked at, since dictionaries were not to guaranteed to be in insertion order.

You could even make this a generator and slightly more general:

def get_values_recursive(x):
    for value in x.values():
        if isinstance(value, dict):
            yield from get_values_recursive(value)
        else:
            yield value

for v in d:
    commodities_reference = list(get_values_recursive(v))
    # do something with it...
    print(commodities_reference)

When using the given example, this is the result:

>>> list(get_values_recursive(v))
[1, 'Explosives', 1, 294, 0, 755, 1774, 99, 18, 176, 924, 0, 128049204, 1, 'Chemicals']

When putting your code into a function, this generator is almost twice as fast with the given v:

In [13]: %timeit op(v)
5.32 µs ± 43.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit list(get_values_recursive(v))
3.64 µs ± 10.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Note that both take on the order of micro seconds, so unless you need to process more than 100000 items per second your bottleneck is probably in those SQL statements and how you execute them.


VSTO Write Dictionary To Range Extension Method

You have a lot of unnecessary vertical spacing which should be removed to improve readability.

Based on the naming guidelines input parameter should be named using camelCase casing.

Because WriteToRange() can be called also as a normal static method you need to check both input parameters for null.

The storeDictionaryData is basically a object[columns, rows] this should be reflected by the counter variables. You can just rename them valueCounter -> column, keyCounter -> row.

You don't need the checks keyCounter < storeDictionaryData.GetLength(1) and valueCounter < storeDictionaryData.GetLength(0) because at the point where you create the array you have taken care of the upper bounds of both dimensions. Both conditions won't evaluate to false.

toRange is poorly named. Consider to name it destinationRange or simply destination. Then a good pattern would be also to rename DictToRange to source.

You should allow your variables to breathe by adding spaces between variables and operators.

Taking the above points into account we can refactor the method to

public static void WriteToRange(this Dictionary<string, object[]> source, excel.Range destination)
{
   if (source == null) { throw new ArgumentNullException("source"); }
   if (destination == null) { throw new ArgumentNullException("destination"); }
   if (source.Count == 0) { throw new ArgumentOutOfRangeException("source"); }

   object[,] storeDictionaryData = new object[source.Max(maxValues => maxValues.Value.Length), source.Count];

   int column = 0;
   int row = 0;

   foreach (var key in source.Keys)
   {
       foreach (var value in source[key])
       {
           storeDictionaryData[column, row] = value;
           column++;
       }

       row++;
       column = 0;
   }

   dynamic rangeToFill = destination.get_Resize(storeDictionaryData.GetLength(0), storeDictionaryData.GetLength(1));
   rangeToFill.Value = storeDictionaryData;
}


You can do it recursively:

void func(int m,int n) {
  if (m == n) {
    System.out.println(m);
  } else {
    func(m, n - 1);
    for (int i = m; i <= n; i++) {
      System.out.print(i);
    }
    System.out.println("");
    func(m, n - 1);
  }
}


Interview Notices

Check the result of system calls

FILE* input = fopen(file, "r");      // Can return null
fread(temp, 1, sizeof temp, input);  // returns the number read (which may not be sizeof temp
fclose(input);                       // Can fail

Style

Personally don't like:

' ' != temp[i] && '\n' != temp[i]

Reads way too much like Yoda conditionals (which went out of style ten years ago). Its not the natural way to expresses a test in your brain.

temp[i] != ' ' && temp[i] != '\n'

Reads much more naturally (at least to an English speaker). Though in an interview I would not knock points off for this. If I hired you I would re-train you to do it the other way though.

Is this the correct/good interface?

void read_matrix(char* dest, char const* file)

I don't like that dest is an array of char. Are you optimizing for space? Where you asked to optimize for space? I would change that to an array of int, as that expresses intent much more clearly.

void read_matrix(int* dest, char const* file)

I think manually checking for space is making this complex. I would have used the scanf library function to do that work for me.

  for(int i = 0; i < 128; ++i){
    if(' ' != temp[i] && '\n' != temp[i]){
       dest[d++] = temp[i];
    }
 }

// note: I would have made the `dest` array integers
for(int i = 0; i < 128; ++i){
    if (sscanf(temp, " %d", dest + i) != 1) {
        // ERROR
    }
}

Functions beginning with an underscore and a lowercase letter are reserved in the global scope.

char _grid_at(char const* grid, int x, int y)
int  _surround_count(char const* grid, int x, int y)
//   ^^^ reserved identifier.

Don't change the first letter to upper case as an underscore followed by an upper case letter is reserved in all contexts.

I can see why you had an issue (all those tests).

A simple optimization for this is to place your grid inside a grid that is one square larger vertically and horizontally. So if you have an 8×8 grid, place it inside a 10×10 grid. Then mark all the cells around the side as having zero in them.

Then when you call surround_count() you can add the cost of all the squares around the cell:

int surround_count(char const* grid, int x, int y)
{
     assert ( 1 <= x && x <= 8 && 1 <= y && y <= 8);

     int count = 0;
     for(int h = -1; h <= 1; ++h) {
         for(int v = -1; v <= 1; ++v) {
             count += isBombAt(grid, x + h, y + v);
         }
     }
     return 0;
 }


void Log(Exception ex, string contextualMessage = "");

This isn't bad, but seems perhaps a bit redundant, since exceptions already have messages. A more idiomatic option might be to wrap the exception in another, with the custom message you want. However, if a "contextual message" conceptually serves a different purpose than the message on an exception, what you have may be fine.

void SetWriter(TextWriter logWriter);

You're right that this is problematic. What it means is that your class can be in a "not fully initialized" state. Like you mentioned, that means you have to remember to initialize it. It also means that if you ever pass it around, you can't rely on your configuration staying the same- some other code might change the logWriter without you realizing.

There's a pretty common solution to this- just pass it into the constructor. That way a WebJobLogger always has one TextWriter for its entire lifetime, which won't be changed. I'm not immediately sure which IoC container you're using, but any mainstream one will have support for constructors with parameters- you just need to make sure the dependencies are bound too.

await logWriter.WriteLineAsync("Start");

Shouldn't you be using the ILogger.Log method for this too? It's confusing to access the underlying writer from the same different place at two different abstraction levels.


Design for a protocol based software in C++

Preliminaries

I would decouple the data transmission + message encoding/decoding from the data connection problem. The linked Uncle Bob article also shows how to distinguish connection management differences for master and slave. You probably want this to work with any reasonable networking implementation. Since you already use boost::noncopyable, I take that as a hint that you are willing to use Boost in general.

My recommendation would be for you to study, and then modify, the simple chat_message/chat_client/chat_server example from the Boost.Asio documentation. That library -or a modified version of it- is likely to become the official networking component in a future version of the Standard Library. So it's a good investment to learn about it.

Message Interface

Compared to the simple chat_message example, your question is a little more involved. I assume that the header information is used to identify which type of message is going to follow. I would recommend to factor all the common message stuff HEADER|BODY|CHECKSUM into an abstract base class IMessage

class IMessage
{
pubic:
    virtual ~IMessage() {} // virtual destructor

    // virtual functions that can be overriden for concrete message types

    static std::string header(std::string const& input)
    {
            return input.substr(0, HeaderLength);
    }

    static std::string body(std::string const& input)
    {
            return input.substr(HeaderLength, HeaderLength + BodyLength);
    }

    enum {
        HeaderLength = /* bla */,
        BodyLength = /* bla */,
        ChecksumLength = /* bla */
    };
};

Message Implementations

You could then define a bunch of different concrete messages that inherit the general message interface IMessage, and add some stuff of their own:

class Request: public IMessage
{
    Request(std::string const& body) { /* decode the buffer */ }

    static std::unique_ptr<IMessage> create(std::string body const&)
    {
        return std::make_unique<Request>(body);
    }

    // Request specific overrides of virtual functions
    // Request unique functions
};

class Acknowledge: public IMessage
{
    Acknowledge(std::string const& body) { /* decode the buffer */ }

    static std::unique_ptr<IMessage> create(std::string const& body)
    {
         return std::make_unique<Acknowledge>(body);
    }

    // Acknowledge specific overrides of virtual functions
    // Acknowledge unique functions
};

You might find it puzzling that I have written both a constructor and a create() function. That is explained in the next section. But for now, note that the declared return type is std::unqiue_ptr<IMessage> but the function body return a unique pointer to the concrete message types. This legal C++ feature is known as covariant return types, and makes it possible to have polymorphic object construction.

Note that std::make_unique is not yet officially availabe but you can get a working version that has been accepted for the upcoming C++14 Standard.

Reading messages

If you look at the Boost.Asio example, the chat_client and chat_server read from a character buffer that is being filled from a socket. So you need to decode the header in order to distinguish which message has to be created.

Especially since you tagged this question with design-patterns, I would recommend to write a small Factory class that keeps a registry of function pointers. At startup, you fill the factory's registry with function pointers to the static member functions create() of all the message types in your application. In this case the registry would be e.g. of type

typedef std::map<std::string, std::function<std::unique_ptr<IMessage>(std::string const&)> Registry;

What this says is that every unique header (encoded in a std::string) stores a pointer to a function taking a std::string and returning a std::unique_ptr<IMessage>. Those type of function pointers are preciesly the create() functions of your messages.

Given a buffer that has been read from the socket, and converted to a std::string, your factory would do something like:

    std::unique_ptr<IMessage> Factory::create(std::string const& input) const
    {
            auto const fun = registry_.find(IMessage::header(input));
            // here you can also do your CHECKSUM validation
            return fun? (fun)(IMessage::body(input)) : nullptr;
    }

What this does is to split the message into a header and body. These functions are static functions of the message interface, so that they can be called before we have a concrete message object. Then the header is looked up in the registry.

If it is found, we simply call the corresponding create() message that was stored, taking the body as argument. This will call the constructor (now you see why we had both a constructor and a creator, because constructors cannot be stored in a factory registry). The constructor will finally create a std::unique_ptr to the concrete message type that was encoded in the header.

If we didn't find a registered message type, we return a nullptr. The caller of the factory creator would then have to check this before being able to safely use the returned pointer.

Final thoughts

The above explained how to decode messages from a stream of tokens that you get from a socket. Writing is of course much easier because then you already know the message type. I think that the data transmission and connection management part, and the semantic part of how to respond to each message type is beyond the scope of this Q&A. The Boost.Asio example does not need too much modification to allow reading your message structures from a socket.

For the above message parsing machinery, I have implemented a heavily templated version of similar protocol called DamExchange (used for letting checkers/draughts engines over a network). You can follow the header trail on a simple use case in my BitBucket repo.


Overall, this is a great start. It's easy to read and understand. Personally, I don't think that 3 procedures is a lot. You have 3 things you need to do: create the initial list, add an element to it, and print out the results. If you didn't have at least 3 procedures, I'd say you were doing something wrong. Anyway, here are some things that could be improved.
Naming
I found the naming a little confusing. Why is it a "ref" list? To what does it refer? (Or what does ref mean in this context if not "reference"?) I think that I would name the list node type a tNode instead of a tList, and I would name the thing that points to it a tList.
I notice also hat some of your variable and argument names begin with lowercase letters and some with uppercase. While Pascal is not typically a case-sensitive language, it's generally considered good practice to be consistent. Often variable names start with a lowercase letter, and types start with an uppercase letter, but it's up to you. It just makes it easier to read when it's consistent.
Types
Better yet, if you're going to keep track of the head and tail separately, I would make another record type, like this:
type
    tNodePtr = ^tNode;
    tNode = record
        info : integer;
        next : tNodePtr;
    end;

    tList = record
        head : tNodePtr;
        tail : tNodePtr;
    end;

Now you can pass a single variable around instead of passing both the head and tail to each procedure. This makes it easier to read the code and less likely that a caller of one of the procedures will accidentally pass the wrong thing for one of the arguments.
Check Your Allocations
There are 2 places where you call new(). You don't ever check the result, though, to see if the allocation succeeded. You need to make sure that the memory was actually allocated before you start writing to it. Otherwise, you'll end up writing over some other data causing a hard-to-find bug, or writing to data you don't have access to and causing a crash.
Delete Stuff When You're Done With It
The other thing you need to do with memory that you allocate from the heap is delete it when you're no longer using it. In this case, that would be at the end of the program. I would write a procedure to delete the nodes in the list. Something like this (and I'm assuming you're using the types I recommended above):
procedure DeleteList(var list : tList)
    var
        nextNode : tNodePtr;
        currNode : tNodePtr;
    begin
        nextNode = list.head;
        currNode = list.head;
        while nextNode <> nil do
        begin
            nextNode = currNode^.next;
            delete(currNode);
            currNode = nextNode;
        end;
        list.head = nil;
        list.tail = nil;
    end;

(Note: It's been a few years since I've written Pascal, so forgive me if I've made any obvious mistakes here!)
Formatting
While this won't affect the running of your program, the formatting of the code can affect how easy it is to read and understand. I would suggest adopting a consistent indentation amount. I see that you sometimes use 1 space, sometimes 2. I would recommend always using 2 or more (my preference is 4, personally), as a single space is not as easy to distinguish as 2 or more.
Also, it looks like in CreateList() the if class has one type of indenting, and the else clause has a different one. I would be consistent about what level of indentation you use for the begin and end keywords.


I think the test is reasonably well named (imho).
If you assume you write the test against a black box (meaning you don't know how the controller code is implemented) then yes you should compare all properties. Someone could have forgotten to copy a property for example. This is especially the case for later when new properties get added (as a regression test). If you find yourself writing code like that a lot then there are several ways to automate this comparison.
I prefer to use human readable strings in unit tests. Makes it easier to read. However once you start doing integrations tests like hitting a test database you want to possibly generate some more exotic strings (non latin characters) to make sure that what you put into the db is also what you get back out and not some garbled nonsense. Some databases can be nasty in that regard.
If you find yourself creating the same post over and over again then you have some options:

If it's just inside one test fixture then create the post in the Setup routine.
If it's across multiple test fixtures then yes extract it into a test utility class.


Reading numbers from a file with lazy ByteString

Here are some notes.

bytestring's documentation clearly states that:

  This module is intended to be imported qualified, to avoid name clashes with Prelude functions. eg.

  import qualified Data.ByteString.Lazy.Char8 as C

This lets you unambiguously write map without Prelude qualifier.

There are some properties of map that allow you to write map f . map g as map (f.g).
tups can be rewritten as one-liner with maybe and fst

tups = maybe 0 fst

All of this leads to following code:

import qualified Data.ByteString.Lazy.Char8 as L
main = L.getContents >>= print . sum . map (maybe 0 fst . L.readInt) . L.words


Return most recent non null field values for multiple unknown fields

Since you are using a stored procedure, it is not much of a stretch to extend that to be a trigger.

Triggers are the natural tool to use for this type of problem, and are designed to have two 'virtual' copies of the data, one copy is the value before the change, the other copy is the value after the change. In your case, you would have a trigger for insert (create), delete, and update.

Read up on triggers here: DML Triggers and the syntax here: CREATE TRIGGER (Transact-SQL)

In the trigger, you would scan the inserted and deleted virtual tables for the data that is changing, and use that to maintain the audit logs in your logging table. Note that thoese virtual tables contain only the data affected, so scanning them is fast.

For more information on those tables, see The Inserted/Deleted table documentation

Using the above mechanism, you can track the changes as they happen. Each instance will be relatively quick, though the work will happen inside the same transaction as the inserts to the main table.

Using a stored procedure like you have, is a good first step, but you should transfer the relevant logic in to the trigger instead.


Validating email confirmation and sending different emails to admins

I'm a bit confused by this:

if (account.EmailConfirmed)
    return View("ConfirmEmail"); //return page that will say the token has expired

Your comment doesn't correspond with the actual code, especially when that same view is returned elsewhere.

The if (result.Succeeded) should be inverted to avoid 30 lines of indentation. Why not do if (!result.Succeeded) and return View("Error"); immediately afterwards?

Also, result is a fairly meaningless name.

I don't know what you're doing with emailBody, but judging from its format and the comments it looks like you're using it to pass arguments in a delimiter-separated string. That's odd, to say the least.

I also don't see the point of compiling it inside if(account.Institution == null) and then not using its value.

What happens inside if (account.Institution.Licence.AllowedAccounts == 0) looks to be exactly the same as what happens if that isn't the case.

What is EmailNames? An enum? I don't think that class should have a plural name, and it doesn't look like it is an "email name".


You could use a class that would only hold the property for the active element, in our case text-decoration: underline;. Then simply toggle each of the two labels to set on and off this "active" class (here called underline).
So you don't need to know which label is which, both will toggle anyway. Just set one of the two to have the class .underline on page load.

Plain JavaScript

const toggle = () => document.querySelectorAll('#labels > div')
  .forEach(label => label.classList.toggle('underline'))

document.querySelector('#houseOrCar').addEventListener('change', toggle);
.underline {
  text-decoration: underline;
}
<input type="checkbox" id="houseOrCar">

HOUSE

CAR

Note I'm using the .forEach method of the nodeList class:

  The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.

jQuery

And here it is implemented with jQuery, which is shorter but very similar:

const toggle = () => $('#labels > div')
  .each((i,e) => $(e).toggleClass('underline'));

$('#houseOrCar').on('change', toggle);
.underline {
  text-decoration: underline;
}

<input type="checkbox" id="houseOrCar">

HOUSE

CAR

It's not worth using jQuery for this, personally, I would stick with the plain version. However, if you happen to already use jQuery in your project then go for it!


It's a pretty small and straight-forward program and not really much to improve on. ChrisWue also brings up the good point that printing to stdout for every line is costly but if you need to print it to stdout there's not much to do about it.

But one thing you can actually do is implement Java's try-with resources which will ensure your resources are closed at the end of the statement, so you can get rid of all your .close() calls and your finally block.


Parse a csv file and create a dictionary of partial results

You're on the right track, using a with block to open the file and csv.DictReader() to parse it.

Your list handling is a bit clumsy, though.  To skip a line, use next(f).  Avoid making a list of the entire file's data, if you can process the file line by line.  The dict comprehension has an unnecessary complication as well.

with open('file.csv') as f:
    _ = next(f)
    reader = csv.DictReader(f)
    counties = { line['County']: line['State'] for line in reader }

Your sample file had County as the header, whereas your code looked for line[‘county’].  I assume that the curly quotes are an artifact of copy-pasting, but you should pay attention to the capitalization.


Getting translated string using reflection and Resource Manager

public static string GetTranslatedString(string input, string culture)
{
    if (string.IsNullOrEmpty(input)) return input;
    string retInput = input;
    CultureInfo cultureInfo = new CultureInfo(culture);
    ResourceManager rm = new ResourceManager("Tesla.TSS.Globalization.SchedulingSystem", Assembly.GetExecutingAssembly());

    var entry = rm.GetResourceSet(cultureInfo, true, true)
        .OfType<DictionaryEntry>()
        .FirstOrDefault(e => e.Key.ToString().Equals(input, StringComparison.InvariantCultureIgnoreCase));
    if (entry.Value == null) return retInput;
    return entry.Value.ToString();

}

Because the resources of your application won't change during runtime, the easiest way would be to once get the whole items and store them in a dictionary. Then your application can use the dictionary to retrieve the translated strings.

I would like to suggest to make this a little bit more flexible, so you could use it in other projects too.

At first the method which will retrieve the Dictionary<string,string> from the ResourceManager

public static Dictionary<string, string> GetTranslations(CultureInfo cultureInfo, string baseName, Assembly assembly)
{
    ResourceManager rm = new ResourceManager(baseName, assembly);

    using (ResourceSet rs = rm.GetResourceSet(cultureInfo, true, true))
    {
        return rs.OfType<DictionaryEntry>()
                 .ToDictionary(r => r.Key.ToString(),
                      r => r.Value.ToString());
    }
}

as you can see, this can be called independent from your current project.

Now let us add an overloaded method which takes the culture as a string like so

public static Dictionary<string, string> GetTranslations(string culture, string baseName, Assembly assembly)
{
    CultureInfo cultureInfo = new CultureInfo(culture);
    return GetTranslations(cultureInfo, baseName, assembly);
}

In your project you can call it now like

Dictionary<string,string> translations = GetTranslations(culture, "Tesla.TSS.Globalization.SchedulingSystem", Assembly.GetExecutingAssembly());

and you could query this to get the translated strings.

You could have a method ChangeLanguage(string culture) like so

private string currentCultureName = "en-Us";
private void ChangeLanguage(string culture)
{
    if (string.IsNullOrWhiteSpace(culture))
    {
        currentCultureName = CultureInfo.CurrentUICulture.Name;
    }
    else
    {
        currentCultureName = culture;
    }

    translations = GetTranslations(culture, "Tesla.TSS.Globalization.SchedulingSystem", Assembly.GetExecutingAssembly());
}

to change the current dictionary.

Your former GetTranslatedString() method should then live as a class method (not static) inside your project and should look like so

public string GetTranslatedString(string input, string culture)
{

    if (input == null) { throw new ArgumentNullException("input"); }

    if (string.IsNullOrWhiteSpace(input)) { return input; }

    if (currentCultureName != culture)
    {
        ChangeLanguage(culture);
    }

    string translation;
    if (translations.TryGetValue(input, out translation))
    {
        return translation;
    }

    return input;
}

As you can see I have change quite a few things like

adding braces {} although they are optional for single line if statements, but they will make the code less error prone.
for a passed in input which is null this will throw an ArgumentNullException which is much better than just returning the null.
for the passed in culture I didn't add a null check, because if the ChangeLanguage() method will be called with a null value the name of the CurrentUICulture will be used.


Variables should be named using camelCase casing, see the NET naming guideline so Infos -> infos and Usr -> usr but as one shouldn't use abbreviation for any names you should change it to users which is much easier to read. This same rule applies to r vs reader and com vs command.

Using braces {} always although they might be optional is the way to make your code less error prone.

foreach (var user in Users)
{
    context.Infos.Add(user);
}

I don't know where these Users are coming from and what context.Infos type is, but if it is by any chance a List<T> you could use the AddRange() method to add them all at once like context.Infos.AddRange(Users);.

What sense does it have to fill a List<Info> which is not used afterwards ?

Having a static class containing the queries can be ok, but you should at least add some possibility to add custom queries as well.


Processing selected and deselected elements

Variable names:

Names like i, param, parameters, state don't have a useful meaning, not for you, nor for others who are reading/reviewing your code. Use meaningful names for your variables, this is better for readability and maintainability.

You have four different actions, based on the four different conditions regarding state and i:

i >= state
state != 1
i <= state
state != 1 && i == 1

Is there a reason why they are in separate methods? The only overlapping part is that in two conditions i can be the same as state (1 and 3). If this is a mistake, you can place all the code in one method, if the checks are correct and you want to keep both methods, also fine. I'll base my answer on the correctness of your code and keep two methods.

In both the methods you perform two foreach loops based on a check. This means that if AssetSelectorCollection has 200 items, you loop 400 times, which is not smart. Reverse the code like this:

foreach (BinaryAssetSelector item in AssetSelectorCollection)
{
    if (i >= state)
    {
        if (item.IsChecked == false)
        {
            item.IsEnable = false;
            item.IsChecked = false;
        }
    }

    if (state != 1)
    {
        if (item.IsChecked == true && item.IsEnable == false)
        {
            item.IsEnable = true;
        }
    }
}

Now you only have one loop over the collection, which will increase performance, certainly over a bigger collection. This must be applied in both methods.

Redundant checking:

Following code:

if (item.IsChecked == false)
{
    item.IsEnable = false;
    item.IsChecked = false;
}

contains redundant checks. The IsChecked property is a boolean and thus needs no evaluation against true or false in the condition, plus you un-check the item when it is already unchecked, no need to do that twice. Rewrite it as follows:

if (!item.IsChecked)
{
    item.IsEnable = false;
}

and even shorter:

item.IsEnable = item.IsChecked

Note that this last line will enable the item when it is checked, not only disable the item when it is unchecked. This logic can also be applied to all the if statements in the code.

Example of the first method, reviewed:

public void WhatSelected(object paramaters)
{
    string ElementToProcess = BASM.FindElement(paramaters, true);
    SeleсtedCurrent.Add(ElementToProcess);

    var i = (from x in AssetSelectorCollection where x.IsChecked == true select x).Count();

    foreach (BinaryAssetSelector item in AssetSelectorCollection)
    {
        if (i >= state)
        {
            if (!item.IsChecked)
            {
                item.IsEnable = false;
            }
        }

        if (state != 1)
        {
            if (item.IsChecked && !item.IsEnable)
            {
                item.IsEnable = true;
            }
        }
    }
    Messenger.Default.Send<BinarySelectorCommunicator>(new BinarySelectorCommunicator { SelectedIN = SeleсtedCurrent });
}

Edit:

Since you're not doing anything between the two if statements you can place the condition of the second statement inside the first one with an && operator:

public void WhatSelected(object paramaters)
{
    string ElementToProcess = BASM.FindElement(paramaters, true);
    SeleсtedCurrent.Add(ElementToProcess);

    var i = (from x in AssetSelectorCollection where x.IsChecked == true select x).Count();

    foreach (BinaryAssetSelector item in AssetSelectorCollection)
    {
        if (i >= state && !item.IsChecked)
        {
            item.IsEnable = false;
        }

        if (state != 1 && (item.IsChecked && !item.IsEnable))
        {
            item.IsEnable = true;
        }
    }
    Messenger.Default.Send<BinarySelectorCommunicator>(new BinarySelectorCommunicator { SelectedIN = SeleсtedCurrent });
}


Setting locale based on preferences with fallbacks

I'd say it's a code smell. Mostly because loc seems to change type. It's one thing for it to be nil or a symbol; in that case it might "only" change value. But the last to_sym would seem to suggest it could also be a string or something.

In terms of code style, you could just use the ||= assignment operator instead of x = y if x.nil?. That's the Ruby way to provide a fallback/default value in case of nil.

However, you're looking to prioritize locale selection, in which case I'd do something like:

locale = [user_locale, browser_locale, param_locale]
  .compact
  .map(&:to_sym)
  .detect { |locale| I18n.available_locales.include?(locale) }

I18n.locale = locale || I18n.default_local
cookies.permanent[:my_locale] = I18n.locale

It'll go through the list and return the first locale that's not nil and is available. If nothing's returned, it uses the default locale.

Note that I'm making an assumption here, namely that user_locale will return nil if the user isn't signed in. But you could also simply unshift the user_locale onto the array if the user is signed in, before doing the detect.

On another note: param_locale should, I think, be the first choice in all cases. If I go to a URL that has an explicit locale code in it, I'd expect to see exactly that page, in that language. URLs should be a permanent as you can make them. Sure, give me an option to view the same URL with a different locale, but don't second guess the URL itself.


Print all anagrams together in a sentence in Java

Whitespace discipline

While your indentation is good, the placement of whitespace isn't very good yet. In Java, we tend to put whitespace after keywords and before braces. A beautifier with standard settings would make your code more readable already.

Use the most common type that still does the job.

For example, your variable map should be declared as Map, not HashMap.

Smarter Use of Map API

Instead of getting the list, checking whether it's null and if it isn't null, creating it, and then always putting it, you could use Map.computeIfAbsent(), like this:

map
    .computeIfAbsent(normalizedAnagram, s -> ArrayList::new)
    .add(word);

Split your logic

Your function getAnagramsTogether is doing many things. You could split it into multiple methods. For example, you could have a separate method normalizeAnagram() which takes a String and returns a new String with the characters sorted.

Bug in your call to Arrays.sort(char[] wordArray)

It should be noted that char is NOT a character. It is a UTF-16 fragment. For the first Unicode plane, i.e. code points with values that can be represented by 16 bits, char is a character. But for code points with higher values, a char contains only part of the character, and the way how you construct the normalized anagram is tearing characters apart.

It may not matter to you, as probably all relevant words in your use cases would have code points in the 16 bit plane.

Don't use + in StringBuilder.append()

You should be consistent, either use + or append().
But using + inside StringBuilder.append() doesn't make sense.
We use StringBuilder in order to have String-concatenation which is faster and uses less memory than using +. Using + in an argument to StringBuilder.append() is completely contrary to the intention of using StringBuilder in the first place.

Don't construct the same object twice.

You're calling new String(wordArray) twice for no good reason.
You could just create a single String normalizedAnagram and use that.

Consider a smarter way of String concatenation.

The following code concatenates your final Map into a String in a smarter way:

map
    .entrySet()
    .stream()
    .flatMap(entry -> entry.getValue().stream())
    .collect(Collectors.joining(" "))


Modify Caching Strategy

It seems every image that is subject to caching is ending up both in memory and on disk. Depending on the number of images and caching aggressiveness, this could be more expensive (in terms of resource usage) than the network request used to retrieve the image.

From my perspective, using both NSCache and the Cache directory together doesn’t add any value. They are both volatile and unpredictable (to different extents). The system could reclaim space from either when it deems it necessary.

From Apples File System Programming Guide:

  "Note that the system may delete the Caches/ directory to free up disk space, so your app must be able to re-create or download these files as needed.”

Therefore its either a choice between caching in memory and caching on disk or an emphasis of one over the other. This inevitably leads to additional questions about how your app will be used and the what kind of images you are working with.

Some basic guidelines:

You don’t want to store a large number of full resolution images in memory
You don’t want to have too many file system I/O operations (spread over time)
You don’t want to have images in memory that are not going to be seen by the user
You don’t want to go to disk every time for frequently seen images

What is a large number? How much is too many? You will have to test and measure.

Test & Measure (and then measure again)

I would definitely recommend testing and measuring your caching strategy to see how much of an impact it has. Xcode instruments provides tools to accomplish this.

One way to go about this is:

Test with no cache (this will be your baseline)
Test with a simple caching strategy (maybe just using NSCache or the Cache directory)
Compare the results of step 2 to your baseline obtained from step 1
Not satisfied, then apply a different caching strategy. Repeat step 3. Otherwise, if you are satisfied with the resource usage and responsiveness of the app then you can stop here until there are significant changes to either your codebase, data or the iOS frameworks.


Extension to BindingList that allows for cancelable notifications of changing and deleting

ListChangedType.Reset

AddItems is nothing more than a glorified wrapper method for calling Add multiple times. However, guidelines suggest that ListChangedType.Reset could and probably should also be called here. Since Reset should be called when..

  Much of the list has changed. Any listening controls should refresh
  all their data from the list.

To give this method some purpose other than looping elements and call Add, consider using the same deferral strategy as you did with SetItems.


Temperature converter that seems to violate SRP

class Numeric

  def fahrenheit_to_celsius
    (self - 32) * 5 / 9
  end

  def celsius_to_fahrenheit
    self * 9 / 5 + 32
  end

end

p -7.5.celsius_to_fahrenheit #=> 18.5

Classes are open for a reason in ruby. A temperature is just a number, converting it is just a method. The accuracy thing disappears by itself - an integer results in an integer, a float will give a float.


Print all permutations with repetition of characters

In case you ever want to just display the string (if you have something like "AAA"):

// if a different character from the first is not found
// std::string::npos corresponds to "not found" (or -1)

if (s.find_first_not_of(s.front()) == std::string::npos)
{
    // inform user that only one permutation exists
}

This is a potential loss of data:

int len = s.size();

size() returns std::size_type, not int.  Do not use int for std::string or other STL container sizes.  They have their own size types that prevents this very issue.  This would be the proper initialization of len:

std::string::size_type len = s.size();

This is needless and potentially dangerous:

int* index = new int[len];

The "dangerous" part refers to the fact that delete is never used to free the allocated memory.  Always use delete with new where appropriate.

In order to free the memory properly, you would use delete in this way:

delete [] index;

But since you're utilizing the STL, instead consider an std::vector:

std::vector<int> index(s.size());

As the memory management is already properly done in std::vector's implementation, new/delete is not needed here at all.  Always try to avoid doing this manually in C++.
No need to pass the string's size; it's already part of the implementation.  Just use s.size().
With the utilization of the aforementioned std::vector and size(), you should now make depth and the loop counters of std::size_t.  This will avoid type-mismatch warnings from comparing size() with an int.  Make sure your compiler's warning flags are high.
Avoid using system("PAUSE") as it is platform-specific and can be imitated by better alternatives such as std::cin.get().  This will ask the user for a console input instead of a keystroke, but that difference shouldn't matter if it means maintaining portability.

Final code with applied changes (also tested on Ideone):

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>

void permutate(const std::string& s, std::vector<int>& index, std::size_t depth, int& count)
{
    if (depth == s.size())
    {
        ++count;
        for (std::size_t i = 0; i < s.size(); ++i)
        {
            std::cout << s[index[i]];
        }
        std::cout << "\n";
        return;
    }

    for (std::size_t i = 0; i < s.size(); ++i)
    {
        index[depth] = i;
        permutate(s, index, depth+1, count);
    }
}

int main()
{
    std::string s("CBA");

    if (s.find_first_not_of(s.front()) == std::string::npos)
    {
        std::cout << "Only 1 permutation exists";
        return 0;
    }

    std::sort(s.begin(), s.end());

    std::cout << s << "\n**********\n";

    std::vector<int> index(s.size());
    int count = 0;

    permutate(s, index, 0, count);

    std::cout << "\nTotal permutations with repetitions: " << count;
}


You can use the LockBits method and pointers to access the image data directly.

Example for 24 bpp images:

bool equals = true;
Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);
BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);
BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp2.PixelFormat);
unsafe {
  byte* ptr1 = (byte*)bmpData1.Scan0.ToPointer();
  byte* ptr2 = (byte*)bmpData2.Scan0.ToPointer();
  int width = rect.Width * 3; // for 24bpp pixel data
  for (int y = 0; equals && y < rect.Height; y++) {
    for (int x = 0; x < width; x++) {
      if (*ptr1 != *ptr2) {
        equals = false;
        break;
      }
      ptr1++;
      ptr2++;
    }
    ptr1 += bmpData1.Stride - width;
    ptr2 += bmpData2.Stride - width;
  }
}
bmp1.UnlockBits(bmpData1);
bmp2.UnlockBits(bmpData2);


Correcting coordinates of an image with polynomial root in python

This is more of a suggestion as I don't have the time to code it, but it is perhaps too long for a comment.
From your code it seems that it is assumed that this fifth degree polynomial has only a single real root. It must have one, because the complex ones must come in conjugate pairs, but I don't see why it has only one.
I will assume it has an unique real root. Here's the idea:

Calculate abs_ru in a fast, vectorized manner.
Order these real values.
Take the smallest, use numpy.roots to find the corresponding unique real root.
Starting from this, consider the next abs_ru value and the corresponding polynomial. If this next abs_ru is far, then consider using numpy.roots again, else a few iteration steps using a root finding iteration should suffice. Consider a gradient descent on the square of the polynomial, or a Newton iteration.

A few things on the code as it is.
Root finding is generally done numerically, therefore it is perhaps better to consider the numeric roots that have a real value of an absolute value below say 1e-5 instead of ~np.iscomplex(abs_rd).
Root finding is expensive, and it is redundant if i == yc and j == xc. Move it to the else branch.


Remarks

What's the point of using an interface and a generic collection if you're only going to call type-specific methods? Instead of having a ManagerMethod, RepresentativeMethod, and so on, add a single EmployeeMethod to that interface and let each class provide their own implementation. Doing type checks all over the place doesn't scale very well, and makes it difficult to add more types.
Why does ObjectNode<T> implement IEnumerable<ObjectNode<T>>? It already exposes its children via the Children property.
ICollection<T> provides modification methods, so other code can add nodes without going through your AddChild/AddChildren methods, so you can't guarantee that all parents are set properly. You'll want to use IReadOnlyCollection<T> or IReadOnlyList<T> here.
Related: the Parent property's setter is public, but it doesn't do anything to inform the previous and new parents about the change. Other code could easily mess up a tree.
Do you have a particular reason for using a linked list instead of a 'normal' list?
That object _obj field should be of type T.
There is no need to explicitly store the type of the given data. Just call its GetType() method when you need to (if at all).
obj.GetType() == typeof(Class) can also be written as obj is Class (with the added benefit that it won't throw an exception when obj is null).
Why does ObjectNode<T> override the GetType() method to return the type of its content instead of its own type? That sort of surprising behavior makes code harder to understand and maintain, and could cause subtle bugs.
That AddChildren method could use a foreach loop instead of a for loop.
Don't ignore warning 0693, use meaningful type parameter names instead. T is used a lot when there's only one type parameter, but when there are multiple it's often used as a prefix instead (for example: IDictionary<TKey, TValue>, Func<T1, T2, TResult>).

Alternative approach

A generic tree class doesn't seem to suit this particular example. You end up with less than ideal names (Subordinates and Superior make a lot more sense here than Children and Parent). It's also cumbersome to use, with lots of type checking and casting required.

I don't know what specific requirements you're working with (if any), but I'd probably go for something like this:

interface IEmployee
{
    // Assuming each employee only has a single boss:
    IEmployee Superior { get; }

    // Employees without subordinates just return an empty collection:
    IEnumerable<IEmployee> Subordinates { get; }

    // Anything else that's common to employees goes here
}

together with an (abstract) base class that implements superior/subordinate storage. Just keep things clean and simple, there's no need for wrapping things in a separate tree node class. Note that this interface is essentially a tree node, and can easily be traversed with a recursive method.

Also, rather than doing lots of type checks and calling type-specific methods, I'd make as much use of that interface as possible. What's the point of an interface if you're not going to treat those objects similarly anyway?

Finally, it looks like this was just an example, and that you're actually looking for a general solution to a broader problem. I get the impression that you're either trying to generalize too soon (a rule of thumb I once heard recommended to generalize only after seeing a similar problem trice) or that you're trying to over-engineer this. Is there a concrete problem that you want to solve?


Generic code review
This is know as a busy loop:
    while(socket == null) {

    }

Not a good idea in any language.
Do you hear your fans spin up when your threads start executing this loop?
You should probably block the thread until the condition becomes true: See is there a 'block until condition becomes true' function in java?
Recursively calling your own function is not a good idea:
 public void serve() {
    .. DO WORK ITEM 1
    serve();
}

That would not explode immediately. But in a production system that is running a long time that will eventually fill up the stack and cause the application to crash. People will spend years trying to work out why it crashed (because its not obvious that this is a slow and steady memory leak that is undetectable).
Why not put that in a loop?
public synchronized void run() {
    while(!finished) {
        serve();
    }
     // remove the recursive call inside serve()
}

This is another hidden busy loop:
        while (currentNumberOfConnections < 2) {
            Socket accept = serverSocket.accept();
            MySocketThread mySocketThread = mySocketThreads.pop();
            mySocketThread.setSocket(accept);
            currentNumberOfConnections++;
        }

When you have two active connections then this will spin like mad and just eat CPU resources. Put another block in there so that the thread is paused until your worker threads can keep going
Design Review:
I think your socket and your threads are to tightly coupled. I would rather separate them and make them independent of each other.
Have your socket class accepts incoming requests and for each request create a work item in a queue. That way it keeps accepting requests and does not need to drop any. If the threads get there two slowly then the client will close the connection and your thread will see this when it tries to service the client rquest.
One the other side make your threads collect work items from the queue (mentioned above). You then can add more threads without the socket class knowing about any of the threads (they just know about the queue).


Laravel 4 clean code review of users controller and model, trying to maintain MVC structure

I didn't used PHP in the last few years, so just some generic notes:

The $input parameter of insertUserIntoDatabase($input) is unused. I guess you wanted to use the parameter instead of direct Input:: calls inside the function.
You could use a guard clause in insertUserIntoDatabase to make the code flatten:

public function insertUserIntoDatabase($input)
{
    $validation = new Services\Validators\Users;

    if (!$validation->passes()) {
        $this->errors = $validation->errors;
        throw new ValidationError($validation->errors);
    }

    $user = new User;
    $user->firstname = Input::get('firstname');
    $user->lastname = Input::get('lastname');
    $user->email = Input::get('email');
    $user->password = Hash::make(Input::get('password'));
    $user->save();
}

The fields in the User class are protected. You might want to use private instead. See: Should I always use the private access modifier for class fields?; Item 13 of Effective Java 2nd Edition: Minimize the accessibility of classes and members.
In postRegister() you could move the return inside the try block. I guess Redirect::to doesn't throw any ValidationError exceptions, so the following is the same:

public function postRegister()
{
    try
    {
        $this->user->insertUserIntoDatabase(Input::all());
        return Redirect::to('admin/login')
            ->with('message', 'Thank you for creating a new account');
    }
    catch (ValidationError $e)
    {
        return Redirect::to('admin/register')
        ->with('message', 'Something went wrong')
        ->withInput()
        ->withErrors($e->getErrors());
    }
}

if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password') ))){
    return Redirect::to('admin/dashboard')->with('message', 'Thanks for logging in');
}

I would create an explanatory local variable for the array for better readability:

$credentials = array(
    'email' => Input::get('email'),
    'password' => Input::get('password')
);
if (Auth::attempt($credentials)) {
    return Redirect::to('admin/dashboard')->with('message', 'Thanks for logging in');
}

(Clean Code by Robert C. Martin, G19: Use Explanatory Variables;  Refactoring: Improving the Design of Existing Code by Martin Fowler, Introduce Explaining Variable)


Calculating the posterior distribution in multivariate Gaussian processes

Assuming model.KuyDinv{k,q} and model.Kyu{q,r} are a matrices (as the name would imply), there is little you can do. You can move the initialization of KuyDinvKyu outside the loop, and eliminate the branch to compute the diagonals:

% define it once -- saves many calls to 'zeros'
KuyDinvKyu_0 = zeros(model.k);

for k = 1:model.nlf
    for r = 1:model.nlf

        KuyDinvKyu = KuyDinvKyu_0;

        for q = 1:model.nout
            KuyDinvKyu = KuyDinvKyu + model.KuyDinv{k,q}*model.Kyu{q,r};
        end

        % removed IF
        model.A{k,r} = KuyDinvKyu;

    end
end

% without IF
for c = 1:model.nlf
    model.A{c,c} = model.A{c,c} + model.Kuu{c};
end

If model.KuyDinv{k,q} and/or model.Kyu{q,r} contain scalars, well then we can optimize this much further for sure. So I need to know the size and type of data that model.Kyu{q,r} and  model.KuyDinv{k,q} will contain.

It might also be that your overall data design (e.g., the choice to use cells) is flawed and causes inefficiencies. So it could also be helpful to see some more surrounding code, so I can determine if there is some improvement to be made in that respect.


Building nested dictionaries to dump it to .json later

Some suggestions:

Do not use mutable default arguments, they will mess with your subsequent calls. There are some very rare cases where mutable default arguments make sense, but this does not look like one of those.
Split generation of data from saving that data to a file. That way either method can be reused. If you also pull out the file handle to a main method you can dependency inject the file handle and test the whole functionality.
details have the same pattern everywhere, so they should also be a class or should be part of Exercise.
Like most Python code this could benefit from type annotations using MyPy.


Searching for a binary tree for a vehicle with a given name

The if (n == null) return null;statement in find() is the only base case that you need. Checking for n.hasLeft() is redundant, and it doesn't even reduce the total number of function calls, since n.hasLeft() is itself a function call.


Pick out excel cells from a long horizontal list based on an adjacent numerical value

Using a Select will definitely shorten up your code.

While i <= 300
    Set Rng = Range("J" & i)
    Select Case Rng.Value
        Case 0, 1, vbNullString
            i = i + 1
        Case 2
            Rng.Offset(, -9).Resize(, 125).Copy
            Rng.Offset(, -9).Insert Shift:=xlDown
            i = i + 2
        Case 3
            Rng.Offset(, -9).Resize(, 125).Copy
            Rng.Offset(, -9).Insert Shift:=xlDown
            Rng.Offset(, -9).Resize(, 125).Copy
            Rng.Offset(, -9).Insert Shift:=xlDown
            i = i + 3

        ' etc.

    End Select
Wend

The next step would be to extract a method to eliminate all of the duplication. It should take in a Range parameter and perform your copy/insert. Basically anytime you hit Ctrl + C you should stop and write a method instead.


Generate voxel terrain with Perlin Noise

For your:

            if (colorR >= colorMaxCap)
                colorR = colorMaxCap;
            if (colorG >= colorMaxCap)
                colorG = colorMaxCap;
            if (colorB >= colorMaxCap)
                colorB = colorMaxCap;
            if (colorR <= colorMinCap)
                colorR = colorMinCap;
            if (colorG <= colorMinCap)
                colorG = colorMinCap;
            if (colorB <= colorMinCap)
                colorB = colorMinCap;

This can be reduced using a suggestion from here:

inline float clip(float n, float lower, float upper) {
  return std::max(lower, std::min(n, upper));
}

And then do:

clip(colorR, colorMinCap, colorMaxCap);
clip(colorG, colorMinCap, colorMaxCap);
clip(colorB, colorMinCap, colorMaxCap);

I don't believe you will lose any performance from that.

Also, try adding OpenMP to your project and right before the first for loop add:

#pragma omp parallel for

This should parallelize the first loop (don't nest pragmas), and make your code run faster. Although, I am assuming (after a not too thorough review) that the any particular iteration does not depend on a previous iteration. Although it should, as Perlin Noise is "embarrassingly parallel".


Merging and summing multi-dimensional arrays

Presuming that the format will be consistent, you could remove one foreach loop and extract the domain to use as the key of the merged array, and also only either set the sub array (with keys X1, Y1 and Y2) or add to the sub array items.

foreach($array as $subArray) {
    if (isset($subArray['INFO']) && isset($subArray['INFO']['DOMAIN'])) {
        $domainKey = $subArray['INFO']['DOMAIN'];
        if (!isset($merged[$domainKey])) {
            $merged[$domainKey] = $subArray;
        }
        else { // could add conditionals to ensure X1 is set on $subArray
            foreach($subArray['X1'] as $key => $value) {
                $merged[$domainKey]['X1'][$key] += $value;
            }
        }
    }
}

See it in action in this playground example.

A functional approach could also be employed by using array_reduce():

$merged = array_reduce($array, function($cumulative, $subArray) {
    if (isset($subArray['INFO']) && isset($subArray['INFO']['DOMAIN'])) {
        $domainKey = $subArray['INFO']['DOMAIN'];
        if (!isset($cumulative[$domainKey])) {
            $cumulative[$domainKey] = $subArray;
        }
        else { // could add conditionals to ensure X1 is set on $subArray
            foreach($subArray['X1'] as $key => $value) {
                $cumulative[$domainKey]['X1'][$key] += $value;
            }
        }
    }
    return $cumulative;
}, []);

See it in action in this playground example


Its not a problem but this seems strange:

stack_realloc(p, p->stackSize - p->capacityIncrement);

Decreasing the size of the stack when you take elements out. This may cause a lot of work (in your code) if you are near a boundary and do a lot of push/pop combinations. It is unlikely that the memory is actually released by realloc() when shrinking anyway.


I've two recommendations that probably have more to do with design rather than with code. The first one is to change the API path to players:

@RequestMapping("/players")

I personally like to pluralize resource path names even if it's widely discussed.

The other one is to modify your PUT endpoint in order to also accept resources to be created. That way you would have a single endpoint which accepts a list of players, where players might be new or already have an id. For the first case, the system must create them, for the second, update them. That's also a mather of disussion in the net.


Will this converstion to/from fixed point cause me to lose precision?

If the SANE_Fixed type has a constantly fixed precision of 1/65536, that means it always stores the fractional part of the number as a 16 bit (two-byte) unsigned integer (hence the SANE_FIXED_SCALE_SHIFT of 16 bits).  Since the whole number portion of the value can range from -32768 to 32767, that means that the whole part of the number is represented with a 16 bit signed integer (making the type use a total of 4 bytes).

The decimal type in .NET, while it is a floating point type, it is far more precise that the traditional float type.  It stores a 96 bit integer (plus an additional bit for the sign).  It then stores the position of the decimal point as a 5-bit integer, which allows the decimal point to be located after any digit in the 96-bit integer value.  As such, the larger the value gets, the lower the fractional precision becomes.

In other words, the decimal type can store a value up to 79,228,162,514,264,337,593,543,950,335 (29 digits).  If it does store a 29 digit number, however, it will be unable to store any fractional value with that.  It will only store the whole part of the number.  If, however, it is only storing a single digit value, the fractional part can be up to 28 digits long (e.g. 0.0000000000000000000000000001).

Bearing all of that in mind, if the maximum whole number that the SANE_Fixed type can store is 32767 (a five digit number), when cast to a decimal type, that leaves 24 digits of precision (e.g. 1/10^24) in the fractional part of the number.  That is still far more precise than the 1/65536 precision provided by the SANE_Fixed type.

Therefore, you can be confident that the decimal type will accurately retain the precise value.  Obviously, when casting from a decimal back into a SANE_Fixed type, you will lose precision, but since the value came from that type in the first place, your values are safe.


A Comparator is the correct approach, you just need to mod the month by the current month before comparing them. The easiest way to do this is to introduce a static variable currentMonth to hold the current month for all instances of DateObj.

Add DateObj.setCurrentMonth(CURRENTMONTH); to your Main, and use the code below:

//Custom Date Object
class DateObj implements Comparable<DateObj>{

    private int year;
    private int month;
    private int date;
    private static int currentMonth;

    DateObj(int year, int month ,int date){
      this.year = year;
      this.month = month;
      this.date = date;
    }

    public Integer getYear() {return year;}
    public Integer getMonth() {return month;}
    public Integer getDate() {return date;}
    public Integer getCurrentMonth() { return DateObj.currentMonth;}
    public static void setCurrentMonth(int currentMonth){
        DateObj.currentMonth = currentMonth;
    }

    @Override
    public int compareTo(DateObj o) {
        int months = (month+(12-currentMonth))%12 - (o.month+(12-currentMonth))%12;
        if(months == 0)
            return this.date-o.date;
        else{
            return months;
        }
    }
}

EDIT: An alternative approach is to simply define the Comparator in your main body. This avoids the use a static value to hold currentMonth:

    Collections.sort(list, (o1,o2)->{
            int months = (o1.getMonth()+(12-CURRENTMONTH))%12 - (o2.getMonth()+(12-CURRENTMONTH))%12;
            if(months == 0)
                return o1.getDate()-o2.getDate();
            else{
                return months;
            }
    });

Thanks to Mr.Wiggles for the recommendation.


Be careful that the random can be between 0 and 4 when it should be between 1 and 4. If you want to make it more object oriented, I would separate the interface (alert and prompt) from the game logic. As this is just a game with 1 ship, I would only do a Game and Ship objects to represent it, but for more complex versions other objects may apply. Here is how I would implement it having custom columns:

function Game(columns){
  this.guesses;
  this.guessarr;
  this.columns = columns;
  this.ship;
  this.ended;

  return this;
}

Game.prototype.getRandomNumber = function(min,max){ // interval [)
  return Math.random() * (max - min) + min;
}

Game.prototype.getRandomShipPosition = function(shipSize){
  return this.getRandomNumber(1,this.columns - shipSize + 2);
}

Game.prototype.init = function(){
  this.guesses = 0;
  this.guessarr = [];
  this.ship = new Ship(this.getRandomShipPosition(3), 3);
  this.ended = false;
}

Game.prototype.makeGuess = function(guess){
  if(isNaN(Number(guess))){
      return "Enter a valid number";
  }
  if(guess <= 0 || guess > this.columns){
      return "Guess has to be between 1 and " + this.columns;
  }
  if(this.guessarr.indexOf(guess) != -1){
      return "You've already entered this number. Try again";
  }
  this.guessarr.push(guess);
  if(this.ship.makeGuess(guess)){
      if(this.ship.isSunk){
          this.ended = true;
      }
      return "You got a hit!";
  }else{
      return "Miss";
  }
}

function Ship(start,size){
  this.start = start;
  this.hits = 0;
  this.size = size;
  this.isSunk = false;

  return this;
}

Ship.prototype.makeGuess = function(guess){
    if(guess >= this.start && guess <= this.start + this.size){
        this.hits+=1;
        if(this.hits == this.size){
            this.isSunk = true;
        }
        return true;
    }
    return false;
}

var game = new Game(6);
game.init();
while(game.ended == false){
    guess = Number(prompt("Enter a guess between 1 and 6"));
    alert(game.makeGuess(guess))
}
alert("you won!")


You restrict the scope of the variables to the nearest enclosing scope with let,
which is good.

The use of whitespace is not consistent: for( vs if (.

The variable names seem a be arbitrary: Why i and y, and not
a and b as in the LeetCode problem description?

The first you can do to speed things up is to "early return":

var judgeSquareSum = function(c) {
    for(let i = c; i >= 0; i--) {
        for(let y = 0; y <= i; y++) {
            let sum = i*i + y*y;
            if (sum == c)
                return true;
        }
    }
    return false;
};

There is no need to continue with the loops if a decomposition into a sum of
two squares has been found.

Now note that one integer in the decomposition determines the other. If we have
a test candidate \$ a \$  for  \$ c = a^2 + b^2 \$ then it suffices
to check if \$ \sqrt{c - a^2} \$  is an integer. Also we can assume that \$ a \le b \$,
which restricts the range of \$ a \$:

var judgeSquareSum = function(c) {
    let aMax = Math.sqrt(c/2);
    for (let a = 0; a <= aMax; a++) {
        let b = Math.sqrt(c - a * a);
        if (b === Math.round(b)) {
            return true;
        }
    }
    return false;
};

Only one loop instead of two nested loops now!

Further improvement is possible with the help of mathematics. As stated in
Sum of two squares theorem,

  An integer greater than one can be written as a sum of two squares if and only if
   its prime decomposition contains no prime congruent to 3 (mod 4) raised to an odd power.

So we need to determine if in the prime factorization
$$
  c = p_1^{e_1} p_2^{e_2} \cdots p_n^{e_n}
$$
there is a term \$ p_j^{e_j} \$ such that \$ p_i = 3 \bmod 4 \$
and \$ e_j \$ is odd.

This is more code, but very efficient for for large numbers, because

the range of prime candidates \$ p \$ can be bounded by \$ \sqrt c \$, and
once a prime factor is found, \$ c \$ can be divided by that factor, thus
reducing the remaining number of iterations.

Here is a possible implementation, with more explaining comments inline:

var judgeSquareSum = function(c) {
    // Handle 0, 1, and 2 directly:
    if (c <= 2) {
        return true
    }
    // Remove even factors:
    while (c % 2 === 0) {
        c /= 2;
    }
    // Find odd prime factors:
    for (let p = 3; p <= Math.sqrt(c); p += 2) {
        if (c % p === 0) {
            // Determine exponent e of p in c:
            let e = 0;
            while (c % p === 0) {
                e += 1;
                c /= p; // Remove this prime factor
            }
            // Is it a prime congruent 4 (mod 3), raised to an odd power?
            if (p % 4 === 3 && e % 2 === 1) {
                return false;
            }
        }
    }
    // If c > 1 at this point then it is another prime factor:
    if (c % 4 === 3) {
        return false;
    }
    return true;
};


I don't like how I have to invoke this with an empty list i.e.
let assignedJobs = AssignJobs crewMembers jobs []

Is there another way? Is recursion the best solution at all (presuming I'm not allowed to loop)?

The 'empty list' initiation is pretty standard in F#. The nice thing about it is if you load a list of currently assigned jobs from a data-source (database, API, etc.) you can seed the function with the current assignments.
Recursion is perfectly fine here, and in fact it's the route I would go to solve this issue. That said, I would actually consider an unfold as well, which would remove the empty-list requirement.
Basically, unfold takes some seed data (here it would be the crewMembers and jobs lists) and it creates a sequence/list/array from that seed data. (It's the opposite of fold: whereas fold creates a single result from a list, even if that's another list, unfold takes a single result and creates the original list.)
With regard to your current method, I have minimal comments. This is quite idiomatic F#, and follows most of the standard themes we use.

let AssignJob job crewMembers =
    let bestCrewMember = crewMembers |> Seq.sortWith crewMemberComparison
                                     |> Seq.head
    {CrewMember = bestCrewMember; Job = job}

I'm not a big fan of your formatting, but beyond that I see no issues here. Personally, I would break it down as follows:
let AssignJob job crewMembers =
    let bestCrewMember =
        crewMembers
        |> Seq.sortWith crewMemberComparison
        |> Seq.head
    { CrewMember = bestCrewMember; Job = job }

(I don't like leaving unnecessary whitespace on the left — makes it harder to find the code you need to see.)
Also, I would name that assignJob as is normal F# parlance for function names.
Lastly, you could take advantage of Seq.exept instead of Seq.filter ((<>) ...), but you need to instantiate an extra list or array to do that, so I'm not sure if it's worth it.


Defining a new Delphi Class with built-in Connection

Is this the best design?

Best design for what? and the answers of yes, no and maybe are all correct.

What you want to research is design patterns and more specifically Patterns of Enterprise Application Architecture, Active Record, Business Objects, Repository pattern Design etc. Also lookup ORM.


if you are just trying to find the minimum number of moves and not necessarily a solution you can use the Frame–Stewart algorithm that you linked to earlier

this builds up a solution to the number of moves to achieve a solution.

def FrameStewart(ndisks,npegs):
    if ndisks ==0: #zero disks require zero moves
        return 0
    if  ndisks == 1 and npegs > 1: #if there is only 1 disk it will only take one move
        return 1
    if npegs == 3:#3 pegs is well defined optimal solution of 2^n-1
        return 2**ndisks - 1
    if npegs >= 3 and ndisks > 0:
        potential_solutions = (2*FrameStewart(kdisks,npegs) + FrameStewart(ndisks-kdisks,npegs-1) for kdisks in range(1,ndisks))
        return min(potential_solutions) #the best solution
    #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)
    return float("inf")

print FrameStewart(16,4) #prints 161

this tells us that the optimal solution for 16 disks and 4 pegs is 161 moves, note that it does not tell us what those moves are

if you actually need the moves you will have to heavily modify this solution.

start by solving the towersofhanoi with 3 pegs as that is the traditional layout and has well defined algorithms to solve

def towers3(ndisks,start=1,target=3,peg_set=set([1,2,3])):
   if ndisks == 0 or start == target: #if there are no disks, or no move to make
      return [] #no moves
   my_move = "move(%s,%s)"%(start,target)
   if ndisks == 1: #trivial case if there is only one disk, just move it
      return [my_move]
   helper_peg = peg_set.difference([start,target]).pop()
   moves_to_my_move = towers3(ndisks-1,start,helper_peg)
   moves_after_my_move = towers3(ndisks-1,helper_peg,target)
   return moves_to_my_move + [my_move] + moves_after_my_move

you can easily verify that this is returning optimal solutions by knowing that the optimal solution to the towers of hanoi with 3 pegs is 2ndisks - 1

all thats left is to change FrameStewart to also return moves

def FrameStewartSolution(ndisks,start=1,end=4,pegs=set([1,2,3,4])):
    if ndisks ==0 or start == end: #zero disks require zero moves
        return []
    if  ndisks == 1 and len(pegs) > 1: #if there is only 1 disk it will only take one move
        return ["move(%s,%s)"%(start,end)]
    if len(pegs) == 3:#3 pegs is well defined optimal solution of 2^n-1
        return towers3(ndisks,start,end,pegs)
    if len(pegs) >= 3 and ndisks > 0:
        best_solution = float("inf")
        best_score = float("inf")
        for kdisks in range(1,ndisks):
            helper_pegs = list(pegs.difference([start,end]))
            LHSMoves = FrameStewartSolution(kdisks,start,helper_pegs[0],pegs)
            pegs_for_my_moves = pegs.difference([helper_pegs[0]]) # cant use the peg our LHS stack is sitting on
            MyMoves = FrameStewartSolution(ndisks-kdisks,start,end,pegs_for_my_moves) #misleading variable name but meh
            RHSMoves = FrameStewartSolution(kdisks,helper_pegs[0],end,pegs)#move the intermediat stack to
            if any(move is None for move in [LHSMoves,MyMoves,RHSMoves]):continue #bad path :(
            move_list = LHSMoves + MyMoves + RHSMoves
            if(len(move_list) < best_score):
                best_solution = move_list
                best_score = len(move_list)
        if best_score < float("inf"):
            return best_solution
    #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)
    return None

note that this is going to be much slower than the version that does not need to find the actual solution (this being codereview maybe some folks have suggestions to make it run faster)
Timings from this experiment

towers3(16)  # 0.09 secs
FrameStewart(16) #0.04 secs
FrameStewartSolution(16) #67.04 secs!!!

really slow as you can see

you can speed it up alot by memoizing it

import json

def fsMemoizer(f): #just a junky quick memoizer
    cx = {}
    def f2(*args):
        try:
            key= json.dumps(args)
        except:
            key =json.dumps(args[:-1] + (sorted(list(args[-1])),))
        if key not in cx:
            cx[key] = f(*args)
        return cx.get(key)
    return f2
@fsMemoizer
def FrameStewartSolution(ndisks,start=1,end=4,pegs=set([1,2,3,4])):
    ...

after memoization the time to calculate became much faster (less than a second)


This program reads in integers until a sentinel number is read. And prints the largest integer read

break;
            }
            else {

You don't need an else with a break.  The break ends execution inside the loop.  You can never reach the code after it in the loop unless it doesn't trigger.  Without all the else clauses, you can significantly reduce the amount of indentation.

Your code could also return instead of break.  That would be clearer in my opinion.

What's x?  What's y?  Why loop forever if you're just going to break out of it?

In my opinion, your comments would be better replaced with more readable, self-commenting code.

Consider the following

    public static int readLargest(final int SENTINEL) {
        int largest = readInt(" ? ");
        for (int current = largest; current != SENTINEL; current = readInt(" ? ") ) {
            if (current > largest) {
                largest = current;
            }
        }

        return largest;
    }

Which you'd use as

    public void run() {
        int largest = readLargest(SENTINEL_NUMBER);

        if (largest == SENTINEL_NUMBER) {
            println("No numbers?");
        } else {
            println("Largest number is " + largest + ".");
        }
    }

By using a separate method, we consolidate the possibilities.  We only have two println statements.  In the original code, you had the latter option three times.  Here we only need one.

This also makes the readLargest more reusable.  Even better might be to read all the values first, then call a findLargest method on that.  Then your readNumbers and findLargest methods would both be reusable separately.  Of course, you may not have gotten to Collection types yet.

In your original code, sometimes y was the largest and sometimes x.  In this code, largest is always the largest unless the most recent read returns a larger value.

I prefer the names current and largest as being more descriptive than single letter names.  I find that more important with largest.  I could live with x instead of current.

I'm not sure that it's necessary to say SENTINEL_NUMBER.  The current variable is an integer.  What would SENTINEL be?  A cabbage?  Obviously not.  You'd only compare an integer to some kind of number.  Others may disagree.  In particular, you may want to look up Hungarian Notation.

I prefer to pass the sentinel value as a parameter for flexibility.

Since we don't use current outside of the loop, I think that the for loop has better scope than a while loop.

The only comment that seems necessary is that readLargest will return the sentinel value if and only if there are no other numbers in the input (prior to the sentinel value).  Other than that, I feel that the code is pretty clear about what it is doing.  Perhaps some explanation of the initialization of largest.


How do you name a something as approximately equal?

About your current implementation, you write:

  The problem is that I think it is terrible.

But then, you don't explain why.

Then you go ahead and write much longer code, and a long list of objections.

In other words, maybe your original implementation is not so bad after all :)

The original code checks if there is any event that happened within the same second (more or less) as the reference event in the parameter (+ an additional date filter). The alternative implementation changes this logic to ±500 millis, which is different. Regardless of the logic you choose, the first option has some important benefits:

Simple
Efficient: sets constant values before a loop, rather than recalculate in every iteration

So I suggest to stick with that. Also remember Occam's razor.