How to correctly get a IDisposeable when you need to lock the factory?

Yes, assuming the factory is shared between threads and the created object doesn't contain any resource that is shared with other objects from the same factory.

But as was already pointed out in your previous question, a better solution might be to have a separate factory for each thread. Factories usually don't use much resources, so it should be fine to have more of them.


Pre-compilation

In theory, you're going to want to call this function more than once. That means that you only want to pay the cost of regex compilation once, and you should move your re.compile calls out of the function, setting your regex variables in the module's global scope.

Type-hinting

s is s: str, and char is (I think) also char: str.

'Removed from the string'?

I think this is the fault of unclear requirements, but - it would make more sense for the char argument to be the character[s] to strip from the string edges, not characters to remove from anywhere in the string. As such, you would need to re-evaluate how you create your regex.

Combine left and right

There's no need for two regexes. You can use one with a capturing group:

^\s*(.*?)\s*$


The short answer: restrict your sieving to what is necessary (sieve potential factors up to the square root of the upper end of the range, sieve the range itself). The runtime for that is a few milliseconds, compared to several seconds (or even minutes) for sieving all numbers up to the upper end of the range.

An extensive answer with all the bells and whistles is at StackOverflow, where the SPOJ PRIME1 question has already been asked and answered:

How do I efficiently sieve through a selected range for prime numbers?

In addition to what is said there: trial division is the slowest form of primality test ever. The Sieve of Eratosthenes is equally simple but it is the fastest of them all, for small numbers up to 2^64 or thereabouts. Special requirements like that of SPOJ PRIME1 require small complications - e.g. windowed/segmented operation - and there are many complications that can be added to make it even faster if that is desired. See the linked article. However, for SPOJ I would keep things sweet and simple.


Algorithms for traversing unordered tree

Do you see any way to optimize it further

I don't see why you have (i.e. don't think you should have) while (tmp != NULL) at the top:

On entry you know that this != NULL
You verify that the result won't be NULL before you execute the statement before each continue or break

Removing that would make it slightly faster.

Also I don't understand ...

    if (tmp->parent->left == tmp)
    {
      if (tmp->parent->right != NULL)
      {
        tmp = tmp->parent->right;
        break;
      }
    }

... because if (tmp->parent->left == tmp) and (tmp->parent->right == NULL) then you do nothing and therefore stay inside while(1) forever. So perhaps either your code is wrong, or one of those if conditions is unecessary.

Apart from the two items above, the existing code looks simple? Multi-threading, using a more-optimizing compiler, or trying to write in assembly are possibilities but not clever. Good optimizations sometimes come from changing the data layout.

For example, one faster algorithm might be to change the way in which the tree is contained in memory: use a custom allocator or similar, to ensure that nodes are physically contained in a contiguous array or vector.

Walking the whole tree would then mean, simply, iterating through the contiguous array: which is pretty quick.

If you do that, it would be easier to change your left, right, and parent pointers to indexes (into the array): because then you wouldn't need to change them if you reallocate (move) the array.

Alternatively keep the nodes in random heap-allocated memory but store the numbers themselves in a contiguous array. Instead of a number member, nodes would have an index member which says which slot in the array contains their number. Making the numbers contiguous (without extraneous tree-node pointers) might be the fastest way to iterate them.


Using events together with interfaces in VBA

I use an additional 'event' class, where all necessary events will be placed in, and which will be injected into the interface implementing classes.

That. That is how it's done. It's COM-friendly, it works, and it's simple. Beautiful.

From Option Explicit to the names of literally everything, including that private type and that this field. You could open any of my own VBA projects and see exactly that, it's almost scary.

I only have a few minor points, that Rubberduck would have picked up:

Public access modifier is sometimes explicit, often implicit.
Not sure why IWorkerEvents parameter needs to be passed ByRef.
Not sure why Message parameter needs to be passed ByRef.

With the next Rubberduck release, you could also have @Description annotations, that the add-in automatically translates to VB_Description attributes, for example:

'@Description "Sets the event provider object for this instance."
Public Property Set Events(ByRef value As IWorkerEvents)
End Property

'@Description "Executes the worker."
Public Sub Work()
End Sub

These special comments (well, the actual description string) would then be visible in the object browser's bottom panel, and in Rubberduck's context-sensitive selection command bar, whenever an IWorker member is selected anywhere in the code.

The write-only Events property is also a little flag: it prompts for a better design - a factory method off a default instance comes to mind:

Option Explicit
'@PredeclaredId
Implements IWorker

Private Type TWorker
    Events As IWorkerEvents
End Type

Private this As TWorker

'@Description "Creates a new worker instance."
Public Function Create(ByVal workerEvents As IWorkerEvents) As IWorker
    If workerEvents Is Nothing Then Err.Raise 5, "IWorkerEvents instance cannot be Nothing."
    With New Worker1
        Set .Events = workerEvents
        Set Create = .Self
    End With
End Function

'@Description "Gets this instance through the IWorker interface. Used by the Create method."
Public Property Get Self() As IWorker
    Set Self = Me
End Property

'@Description "Gets or sets the worker events. Useless from default instance."
Friend Property Get Events() As IWorkerEvents
    Set Events = this.Events
End Property

Friend Property Set Events(ByVal value As IWorkerEvents)
    Set this.Events = value
End Property

Private Sub IWorker_Work()
    If this.Events Is Nothing Then Err.Raise 5, "Instance was not created with .Create method."
    Debug.Print "Worker 1 works hard."
    this.Events.Notify Me, "is working..."
End Sub

The IWorker interface then looks like this:

Option Explicit

Public Sub Work()
End Sub

So the client code is written against IWorker and only sees a Work method, and that's really all they need to care about.

Guard clauses ensure the object is always in a valid state and prevent misusing the class.

The Worker1 concrete class has a VB_PredeclaredId attribute, which exposes the Create method, so the code that New's up a Worker1 class can do this instead:

With Worker1.Create(workerEvents)
    .Work
End With

The fact that Events is visible from a Worker1 instance is not a problem, because the client code does not work from that interface, it only ever sees IWorker members; the Friend modifiers could just as well be Public, but there's no point exposing them beyond this VBAProject, so Friend is good enough.

Notice I removed the Notify procedure (which was implicitly Public), because it's really just an implementation detail that doesn't need to be exposed, and can very well simply be inlined in the Work method.

Until the next Rubberduck release, the module and member attributes need to be added manually, by exporting the module, editing them in, and then re-importing the module.

I like seeing test code. VBA code that works off interfaces and injected dependencies want to be tested! With Rubberduck you could have written unit tests that actually document the implementation/specs, for example in some Worker1Tests module:

Option Explicit
Option Private Module

'@TestModule
'@Folder "Tests"

Private Assert As New Rubberduck.AssertClass
Private Fakes As New Rubberduck.FakesProvider

'@TestMethod
Public Sub GivenNullWorkerEvents_Throws()
    Const ExpectedError As Long = 5
    On Error GoTo TestFail

    Dim sut As Worker1
    Set sut = New Worker1

    If Not sut.Events Is Nothing Then Assert.Inconclusive "Events should be Nothing"
    sut.Work

Assert:
    Assert.Fail "Expected error was not raised."

TestExit:
    Exit Sub
TestFail:
    If Err.Number = ExpectedError Then
        Resume TestExit
    Else
        Resume Assert
    End If
End Sub

This simple test passes when the Work method raises run-time error 5 because the object wasn't created with the Create function.

Another test would pass when the Work method would raise the Notify event on a fake implementation of the IWorkerEvents class, ensuring that the Worker1 class is calling the Notify member on the IWorkerEvents object it's given.

And so on: a robust test suite would cover pretty much every single execution path, and clearly document how the class should (and shouldn't) be used.

A single "here, see, it works" test doesn't really do anything other than exercising the "happy path" - which is ok for showing off a prototype, but production code needs all cases covered.


From top to bottom

Since AddCopyrighttoPDF() is a public method you should validate its argument path.

Variables should be named using camelCase casing and should be spelled correctly string CopyRighText; -> string copyrightText;

try
{

    CopyRighText = "Copyright © " + DateTime.Now.Year + " All Rights Reserved.";
    PdfStamper pdfStamper = null;
    PdfReader pdfReader = null;

why are these 3 lines of code inside a try..catch block? Which exception could here happen? The try..cacth block can be removed.

You are using an using statement for the MemoryStream which is a good thing, but both PdfReader and PdfStamper are implementing the IDisposable interface as well hence they should be enclosed in an using block as well.

for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
    if (i > 1)
    {

If the loop would start at int i = 2 the if block would become superflous which saves one indentation-level of thecode.

BaseFont baseFont should be created outside of the loop and reused.

float n2 = 15F; should be named better and should be a constant.

float n3 should be named better.

overContent.ShowTextAligned(0, CopyRighText, n2, n3, 0F); here 0F should be extracted into a constant as well.

Disposing of the MemoryStream, which happens when the end of the using block is reached will Flush() and Close() it as well.

Implementing the mentioned points will lead to

private const float copyrightFontHeight = 7F;
private const float copyrightHorizontalPosition = 15F;
private const float copyrightVerticalBorder = 10F;
private const float copyrightRotationNone = 0F;
public static byte[] AddCopyrighttoPDF(string path)
{
    if (string.IsNullOrEmpty(path)) { return null; }

    string copyrightText = "Copyright © " + DateTime.Now.Year + " All Rights Reserved.";

    try
    {
        BaseFont baseFont = BaseFont.CreateFont("Helvetica", "Cp1250", false);
        using (MemoryStream ms = new MemoryStream())
        using (PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(path), System.Text.ASCIIEncoding.UTF8.GetBytes("1111")))
        using (PdfStamper = new PdfStamper(pdfReader, ms))
        {
            for (int i = 2; i <= pdfReader.NumberOfPages; i++)
            {
                Rectangle pageSizeWithRotation = pdfReader.GetPageSizeWithRotation(i);
                PdfContentByte overContent = pdfStamper.GetOverContent(i);
                overContent.BeginText();
                overContent.SetFontAndSize(baseFont, copyrightFontHeight);
                overContent.SetRGBColorFill(0, 0, 0);
                float copyrightVerticalPosition = pageSizeWithRotation.Height - copyrightVerticalBorder;
                overContent.ShowTextAligned(0, copyrightText, copyrightHorizontalPosition, copyrightVerticalPosition, copyrightRotationNone);
                overContent.EndText();
            }

            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            return ms.ToArray();
        }
    }
    catch { } //empty because if we just want to swallow the exception

    return null;
}

This should behave exactly like your former code. Thats why its not throwing an ArguemntNullException if path == null and why its not throwing an ArgumentException if path is whitespace only.

I couldn't find the C# documentation of BaseFont but if BaseFont is implementing IDisposable as well, it should be enclosed in an using block as well.


Making sure initialization code is executed before other code using Lazy Initialization

Your code does feel like a misuse of lazy evaluation. Some alternative approaches to consider:

MakeInitialize method public and throw if it was not called:

public override void Initialize()
{
    //do stuff
    _isInitialized = true;
}

public void Run()
{
    if(!_isInitialized) throw new InvalidOperationException();
    //do stuff
}

IMHO, it is all-around best option, as it allows you to control when to do initialization.
Call initialization automatically on every Run call:

protected override void Initialize()
{
    if (_isInitialized) return;
    //do stuff
    _isInitialized = true;
}

public void Run()
{
    Initialize();
    //do stuff
}

This approach is good in some cases. For example, when you have an unstable network connection, it makes sense to check the connection before every method call, and reconnect if needed.
Use Lazy objects to initialize actual services:

public CsvWriter CsvWriter { get { return _csvWriter.Value; } }
readonly Lazy<CsvWriter> _csvWriter;

public void Run()
{
    CswWriter.Write(...)
}

I'm not a fan of lazy initialization, but it is fine, if you use it to instantiate one or two actual services. Laziness is justified in scenarios when there are high chances that Run method will not be called at all by your software.

P.S. Note, that Lazy is thread-safe, while options #1 and #2 are not and require synchronization if thread-safety is required.


Validate the order of a List by custom strings

Dictionary

I'd prefer to store animal names and their "values" in a dictionary.

private static readonly Dictionary<string, int> AnimalValues = new Dictionary<string, int>
        {
            { "Cat", 1 },
            { "Dog", 2 },
            { "Horse", 3 },
            { "Elephant", 4 }
        };

Then the validation method will look like:

public static bool IsValidAnimalOrder(IEnumerable<string> animalNames)
{
    int prevValue = 0;
    foreach (string animalName in animalNames)
    {
        int curValue;
        if (!AnimalValues.TryGetValue(animalName, out curValue))
        {
            // If the animal's name is absent in the dictionary.
            return false;
        }
        if (curValue < prevValue)
        {
            // If the current animal's value less than the previous one.
            return false;
        }
        prevValue = curValue;
    }
    return true;
}

switch

Alternative way is to use the switch operator instead of a dictionary as follows:

public static bool IsValidAnimalOrder(IEnumerable<string> animalNames)
{
    int prevValue = 0;
    foreach (string animalName in animalNames)
    {
        int curValue;
        switch (animalName)
        {
            case "Cat":
                curValue = 1;
                break;
            case "Dog":
                curValue = 2;
                break;
            case "Horse":
                curValue = 3;
                break;
            case "Elephant":
                curValue = 4;
                break;
            default:
                // If the animal's name is not listed above.
                return false;
        }
        if (curValue < prevValue)
        {
            // If the current animal's value less than the previous.
            return false;
        }
        prevValue = curValue;
    }
    return true;
}

IEnumerable<T> problem

As @Mat's Mug♦ mentioned, IEnumerable<T> doesn't guarantee the order of its elements. So you could change argument type to IList<T> or IReadOnlyList<T>. But this will reject another enumerations with the specified order: IOrderedEnumerable<T> and IOrderedQueryable<T>.
As a workaround you could make the method above private and declare public overloads accepting all the suitable enumeration types above as argument:

public static bool IsValidAnimalOrder(IReadOnlyList<string> animalNames)
{
    return IsValidAnimalOrder((IEnumerable<string>)animalNames);
}

public static bool IsValidAnimalOrder(IOrderedEnumerable<string> animalNames)
{
    return IsValidAnimalOrder((IEnumerable<string>)animalNames);
}

public static bool IsValidAnimalOrder(IOrderedQueryable<string> animalNames)
{
    return IsValidAnimalOrder((IEnumerable<string>)animalNames);
}


Validating a credit card number using Luhn's algorithm

if [ $(($i%2)) -eq 0 ] ; then foo=bar; else arr[$char]=$double

Then foo=bar? In any case, an alternative way of writing this is something like (borrowing your final if statement):

[[ $resultchecknum == $checknum ]] && echo "CC Number is valid!" \
                                    || echo "CC Number is not valid."

Also, you have a mix of echo "..." | bc and bc <<< "...", I suggest keeping to the latter as it simpler to write.

A similar alternative to if-then-else is using &&:

[ ! $(($i%2)) -eq 0 ] && arr[$char]=$double


Shopping cart in Rails for karaoke items

Generally looks great.

Since @cart is basically a list of Karaoke ids, you could update the list_items method to look like that:

def list_items
  @items = Karaoke.find(@cart)
end

Then the cart view can be transformed into:

<h1> Cart </h1>
<% @items.each do |item| %>
  <p>
    <%= item.name %>
    <%= link_to "Remove", remove_path(item) %>
  </p>
<% end %>

Using a Set instead of plain array enables us to remove the presence checking and make sure items are always unique in the cart:

class ApplicationController < ActionController::Base
  ...

  def set_cart
    session[:cart] ||= []
    @cart = Set.new(session[:cart])
  end
end

class CartController < ApplicationController
  def add_item
   @cart.add(karaoke_id) if Karaoke.exists?(karaoke_id)

   redirect_to cart_path
  end

  def remove_item
    @cart.delete(karaoke_id)

    redirect_to cart_path
  end

  def karaoke_id
    params[:id].to_i
  end
end

As a side note, I know it's kind of a personal preference, but consider using 2 spaces for indentation as per the style guide.


Handling shared state among a lot of elements in Angular

Your View looks fine (HTML and CSS). However, representing the state of your data elements with two string variables that may or may not be storing the "name" field on the parent data object is a very bad way of representing state.

The guiding principal for these design questions: your object model should make it impossible to ever represent an inconsistent or meaningless state. With your object model there are many ways to represent inconsistent and meaningless states, for example:

It's possible for a data item to be simultaneously in state Med
and state Max
If medElement and maxElement variables contain
values which are not equal to the name field on the parent object,
those values are ignored

As a result your controller code is needlessly complex and very difficult to read.

Solution:

Represent the state of your data objects with an enum called ElementSize that can take exactly one of three possible state values: minimum, medium, and maximum. Then, use the ng-switch directive to specify what html you want to render for each of the three possible states.


For your purposes, you can treat touchleave and touchcancel the same way. The difference is touchleave happens when the touch point leaves the element and moves somewhere else in the document, and touchcancel happens when the touch point leaves the document entirely, like moving outside the browser window's content area or onto a plugin.

Minor stuff:

The functions you use to handle touchleave and touchcancel are exactly the same, so you could eliminate redundancy by reusing the same function for both.
The third argument to addEventListner, useCapture, defaults to false, so you don't need to explicitly pass it in.
The IIFE inside of bind_tap serves no purpose, it can be removed.
JavaScript identifiers should use camelCase; bind_tap is not an appropriate name for an identifier.
Variables named like el and cb aren't a big deal for internal stuff, but for code that's exposed as part of your API (function parameters) they should probably have fully descriptive names.
You have an extra semicolon at the end of your code. Function declarations are not separated by (or terminated with) semicolons.

Major stuff:

In your touchend handler you set touchStarted to false and then check it for a truthy value on the next line; if (touchStarted) cb();. The callback will never fire there. The code is only working because you have the callback handling the click event. When you fix this, you'll need to make sure that the callback only fires once. I added touchFinished in the example below to address that.
You probably want to pass the this binding and any arguments on to the callback.

Something like this should work (not tested).

function bindTap(element, callback) {
    var touchStarted = false,
        touchFinished = false;

    function startTap() {
        touchStarted = true;
    }

    function cancelTap() {
        touchStarted = false;
    }

    function endTap() {
        if (touchStarted && !touchFinished) {
            callback.apply(this, arguments);
            touchFinished = true;
        }
    }

    function handleClick() {
        touchStarted = true;
        endTap.apply(this, arguments);
    }

    element.addEventListener("click", handleClick);
    element.addEventListener("touchstart", startTap);
    element.addEventListener("touchcancel", cancelTap);
    element.addEventListener("touchleave", cancelTap);
    element.addEventListener("touchend", endTap);
}


Your code doesn't look that ugly!  Here are some suggestions to make it better.  Note that LeetCode makes significantly more mistakes than you when it comes to code quality; I have listed the suggestions for LeetCode-provided stuff too, so that you don't make the same mistakes when you are writing real code — you don't have to force LeetCode to accept them (i.e., some of them can be compromised for the purpose of passing their tests).

General design

The Solution class is very Java-style AFAIK, but it is not idiomatic in C++.  It should be replaced by a namespace, or removed altogether.  In C++, it is preferred to create a separate Tree class for the binary trees, instead of operating directly on the nodes.  Also, the value type should be a template parameter for reusability.

Naming

In C++, functions and variables are generally named in snake_case, with CamelCase names reserved for classes.

The name of the function is misleading — to me, isSubtree(s, t) means "s is a subtree of t," rather than the reverse.  contains_subtree may be better.  The parameters s and t are also non-descriptive and thus unreadable; I recommend tree and subtree.

The parameters to isSame (or maybe just same), on the other hand, can be named as simply as tree_a and tree_b, because the semantics is unambiguous.

Logic

(Note: the code snippets presented are intended to help you understand the review.  They are not tested; in other words, they and may contain mistakes and are not guaranteed to work.)

The logic of same can be simplified:

if both arguments are non-null, then they are identical if and only if

their values are equal; and
their left subtrees are identical; and
their right subtrees are identical;

otherwise, they are identical if and only if they are both null.

bool same(TreeNode* tree_a, TreeNode* tree_b)
{
    if (tree_a && tree_b) {
        return tree_a->val == tree_b->val
            && same(tree_a->left, tree_b->left)
            && same(tree_a->right, tree_b->right);
    } else {
        return !tree_a && !tree_b;
    }
}

This presents your logic in a way that is (hopefully) more readable.

Similarly,

if tree is non-null, then tree contains subtree if and only if

same(tree, subtree); or
tree->left contains subtree; or
tree->right contains subtree;

otherwise, tree contains subtree if and only if subtree is null as well.

bool contains_subtree(TreeNode* tree, TreeNode* subtree)
{
    if (tree) {
        return same(tree, subtree)
            || contains_subtree(tree->left, subtree)
            || contains_subtree(tree->right, subtree);
    } else {
        return !subtree;
    }
}

This refactoring eliminates the unnatural non-local control flow (i.e., writing to the bool& argument instead of using the return value).  It also ensures that the function returns as soon as a match is found.


Dynamic module import in a class hierarchy

Yes, this is definitely pythonic: implementing lib wrappers allows one to easily include additional features in wrapper classes, as a complement to pure import. So it is both concise and versatile.

As you are working with Python 3 (according to the shebang), you may use the simplified form for super():

super().__init__(*args, **kwargs)

instead of

super(ExtendedLibWrapper, self).__init__(*args, **kwargs)

It works even with multiple inheritance.


Here's a rewrite without any ifs:

function humanTime(minutes) {
  var units          = ['months' , 'weeks' , 'days' , 'hours'];
  var minutesPerUnit = [40320    , 10080   , 1440   , 60];
  var timeInUnits    = minutesPerUnit.map(x => Math.floor(minutes / x));
  var time           = timeInUnits.find(x => x > 0);
  var unit           = units[timeInUnits.indexOf(time)];
  return time + ' ' + unit;
}

Note I removed the <td>s from this code as it's mainly a view (formatting) concern.  This allows this function to remain more focused: it simply takes a number of minutes and converts it to hours/days/weeks/months as appropriate.

You might also consider returning an object of the form: {time: 6, unit: 'days'} instead of a string as I have, to make the separation of data and view even stronger.


Summations and products and factorials oh my

Some comments:

    |> Seq.map f
    |> Seq.sum

is just

Seq.sumBy f

Otherwise, if perf really matters I would avoid using Seq, and probably combine the map and fold in the product case.

Also, rather than

match (low, high) with
| (low, high) when low <> high ->
    { low .. high }
    |> Seq.map f
    |> Seq.sum
| (low, high) when low = high -> 0.0

I would use an if to avoid the warning about incomplete pattern match so it would become

if low=high then 0.0
else   {low .. high} |> Seq.sumBy f


Encapsulation and information hiding

The parameterless nucleotideCounts method exposes the map of counts.
If later you wanted to change the way you store the counts,
for example you wanted to store in a database instead of a map in memory,
you won't be able to do that,
because you did not hide this information.

Exposing the map is especially suspicious since the map is mutable.
Users of this class could circumvent the validation logic,
for example delete nucleotides or add invalid nucleotides.

In any case, it would be better to declare the count map private.

Unnecessary getOrElse

Thanks to the validate method,
and if we assume that users of the parameterless nucleotideCounts method will not abuse the class and delete nucleotides,
it's guaranteed that count.get(c).get will always find a value,
so you can replace all occurrences of count.get(c).getOrElse(0).

Mutable or not

It's not clear why you use a mutable map.
Your current implementation and tests would work with an immutable map too.

If you really want to use a mutable map, then you can replace this:

count = count.updated(i, count.get(i).getOrElse(0) + 1)

with:

count.update(c, count.get(c).get + 1)

Naming

count is a not a great name for a collection type.
For example the plural counts would be a more fitting name,
which would also match the naming of your parameterless nucleotideCounts method.

You used multiple names for a character in a DNA string: i, chr, nucleotide. It would be easier to read the code if you used a consistent name. i is especially a bad name, as it's typically used in counting loops.


Provide true clock-modulus operation for arbitrary sign values

Style comments:

Generic typename T implies you do not know or care what kind of type it is or which properties it has. Why not name it Numeric or something in that direction?
You should really use better names for variables. At first glance, no one has any idea what which variable is intended to do.
Even a single line if deserves braces. When omitting these and later adding to the code, programmers often forget to add them and introduce bugs.
typedef is a relic of C compatibility. Consider the using keyword instead.
Do not just arbitrary rename a type especially into something like D. You have an IDE it can do completion for you, use it. (And yes, even vim and emacs do completion, no excuses unless you write your code in notepad.)
Comment on your intentions and assumptions of the pieces of your code.

Solution issues:

  the sign of v indicates the 'direction of counting' round the clock, positive increments from 0, negative decrements from m

You are probably looking for this, meaning you should declare the template function and then offer specific implementations for the different possible instances of T.
Is a cast to long double really required? If T is a numeric type, all required operations should be defined for T. There is no reason to fall back to std::fabs().
If you want to do it by hand, I would suggest something in the way of

bool clockwise = (v >= 0);
T absolute_v;
if(!clockwise){ // !clockwise implies v < 0
    absolute_v = -v; // we want the abs(v)
} else {
    absolute_v = v;
}


You can have a separate project for your Dockfile and let gitlab keep the image in a container repository. That way you will not need to rebuild the image every build and you can reuse the container in other project without rebuilding it.


Making a Pong ball reflect off the paddle

Your ball can only move in the eight (semi)cardinal directions? It can't move at, say, a 30-degree angle?

Well, even so, it will simplify your code to treat the ball as if it can move in any direction. Either:

struct MoveDirection {
    double angle;
    double speed;
};

or more likely:

struct MoveDirection {
    double vx;
    double vy;
};

And then rewrite your getHitPos function as something more like

MoveDirection Ball::getHitPos(const Player& player) const
{
    MoveDirection dir; //Direction of movement

    //If ball is moving left
    if (m_dir.vx < 0)
    {
        std::cout << "Yes";
        int hitPos = m_pos.y - player.getPos().y; //Get hit position
        int playerSize = player.getPos().h / 2;
        int offSet = 25; //Enables to split up positions into three seperate parts
        //Calculate dir change
        dir.vx = +1;
        if (hitPos <= playerSize - offSet) {
            dir.vy = +1;
        }
        else if (hitPos >= playerSize + offSet) {
            dir.vy = -1;
        }
        else {
            dir.vy = 0;
        }
    }
    else if (m_dir.vx > 0)  // ball is moving right
...

Then just keep refactoring and turning branches into arithmetic expressions until you're happy. It might end up looking something like

MoveDirection result;
result.vx = -m_dir.vx;
const double hitPos = m_pos.y - player.getPos().y; //Get hit position
const double playerSize = player.getPos().h / 2;
result.vy = (hitPos > playerSize + 25) - (hitPos < playerSize - 25);
return result;


Converting a Website Into a Single Page App

It will work, but consider why you might be doing SPA's:

No more full screen flickering, better user experience
Keep your state on the browser side instead of pingponging it between server & browser
Less network traffic if you only request for data & do the rendering with templates in JS

With your approach,

You are rebuilding the whole DOM from scratch everytime, so there will still be flickering.
With script tags being replaced while JS is still running, I dont even want to think about what mess your state will be in ;)
You are still fetching data + layout from the server, so not gaining anything from a network perspective.

Furthermore, you run the risk of memory leaks, which happen like this:

Add any listener to your DOM
Forget to unbind that listener when the user clicks a link
New content is loaded, old DOM is gone, but that old listener is still out there


Numeric and percentage deadband calculation

I'm unclear about what is TRUE and what is FALSE (and how you interpret it).

Is it FALSE = when value is greater than previous by more than deadband?
    (i.e. value > previous + deadband is NOT OK)
    (i.e. value <= previous + deadband is OK)
That's how I did it below, but if you want the opposite, change the "<" sign.

I would change the two functions in one, and give an extra argument (true for numeric, false for percentage):

    function check_deadband($value,$previous,$deadband,$check_numeric) {
        if ($value <= 0) {
            return false;
        }
        if ($check_numeric) {
           // numeric testing
            $difference=abs($previous-$value);
            return $difference < $deadband;
            // ex. value: 74, previous: 70 => difference = 4
            // difference: 4 < deadband: 3 => false, not ok
        } else {
            // percentage testing
            $percentage=abs(($value - $previous) * 100/$previous);
            return $percentage < $deadband;
            // ex. v:111 p:100, (v-p)*100/p:11% < 10% => false, not ok
        }
    }

You eliminated the previous=0 or previous=value cases in your example, but I didn't understand why (you can put them back).
I also not sure that your percentage formula is corect. If you want the difference in percentage, then (value-previous)*100/previous will give you the right answer. (ex. value = 10, previous=5 => percentage is 100 - correct!)
You can check the function with the following testing code:

    $numeric_deadband = 3;
    $percentage_deadband = 10;

    /// GENERATE RADNOM DATA ex. 5.000 rows
    $rows_nr=5000;
    $min=40;
    $max=80;
    for ($i=0; $i<$rows_nr; $i++) {
        $numeric_set[]=array(
            "value"=>rand($min,$max),
            "previous" => rand(40,80));
        $percentage_set[]=array(
            "value"=>rand($min,$max),
            "previous" => rand(40,80));
    }

    $time=microtime(true); // just for testing purposes
    foreach ($numeric_set as $row) {
        // check NUMERIC set
        // remove echos after testing
        echo "NUMERIC >> value: $row[value] vs previous :".
            "$row[previous] (deadband: $numeric_deadband) => ";
        echo check_deadband(
            $row["value"],
            $row["previous"],
            $numeric_deadband,
            true)
            ? "true" : "false";
        echo "
";
    } unset($row);

    // CHECK time in miliseconds
    echo "
Checking deadband for NUMERIC ($rows_nr rows) took:".
        round((microtime(true)-$time)*1000)." miliseconds
";

    $time=microtime(true);
    foreach ($percentage_set as $row) {
        // check PERCENTAGE set
        // remove echo after testing
        echo "PERCENTAGE >> value: $row[value] vs previous:".
        "$row[previous]  (deadband: $percentage_deadband) => ";
        echo check_deadband(
            $row["value"],
            $row["previous"],
            $percentage_deadband,
            false)
            ? "true" : "false";
        echo "
";
    } unset($row);

    echo "
Checking deadband for PERCENTAGE ($rows_nr rows) took:".
        round((microtime(true)-$time)*1000)." miliseconds
";

Hope this works. Feedback would be appreciated!

EDIT:
Changed the script to detect both above and below deadband changes.


Give me some change as asked in interview

I think that a better algorithm can be developed and suggestions are welcome.

Yes! The core of the algorithm is the following:

for (int i : denomenations) {
  while (m - i >= 0) {
    m -= i;
    change++;
  }
}

What this does is looping through all the possibles denominations in descending order, removing them as long as necessary. This is the right idea: for a given number, like 36, this subtracts 10 three times, then 5 one time and then 1 one time.

This can be done in a faster way. You know in advance how many times you will need to loop. It is precisely m / i (with an explicit integer division).

Given 36, you want to know how many times 10 fits in there. This is the quotient of the integer division of 36 by 10, which is 3, result of 36 / 10.
Then, what remains in m is the remainder of the integer division of 36 by 10, which is 6, result of 36 % 10.

As such, you can have:

for (int i : denomenations) {
    change += m / i;
    m %= i;
}

without a single inner while loop.

I am not so sure about the initial time complexity of the algorithm, but with this revision, you clearly have a linear algorithm in terms of the denominations, which is probably the same as the original but will effectively be faster.

  I put some thoughts on testing strategies in this problem, since the input is integer I had few number of edge cases also the problem description doesn't cover edge cases (eg: maximum integer) but then also I thought to test it, is this the correct approach?

Testing edge cases is always welcomed, and I would encourage it. Do note that unit tests should typically sit in a dedicated test class run with a testing framework, like JUnit for example.

  For m = 0 the algorithm works fine but still I gave a guard condition for readability, don't know if this is a good strategy.

This is perfectly fine. You have an early return for negative values so you can add 0 to it since the results would already be known in advance.

A couple of other comments:

Beware of typos: denomenations should be denominations.
Since they are constants, you might also want to turn them explicitly into constants. A better alternative would be to let the CountChange method take the array of denomination as argument; this way, it is completely independant of actual values.
The method name should be countChange, not CountChange, with regard to Java naming conventions.
Consider having more descriptive names than m and i. One letter variables can be fine if their scope is really tight, but here, a longer name would be appropriate.


Extension method to get the Sunday date from current date based on weekOffset

I think your code could be more succinctly and usefully (ie don't return string) written as:
    private static DateTimeOffset[] GetWeekRange(this DateTimeOffset d, int weekOffset = 0)
    {
        var weekStartDate = new DateTimeOffset(d.Date, d.Offset).AddDays(weekOffset * 7 - (int)d.DayOfWeek);
        var weekEndDate = weekStartDate.AddDays(7);
        return new [] { weekStartDate, weekEndDate };
    }

But then given that end is so easily calc'd from start, maybe just return start, forget the array


Function to check whether entire list is prime numbers

There are a few obvious improvements, which either make it more readable or even faster:

True if n == 2 else ... is equivalent to n == 2 or ...
bool(all(...)) is the same as all()
You could pull out the special case of 2 in all(n % x for x in list(range(3, int(sqrt(n)+1), 2))+ [2]) by doing (n % 2 and all(n % x for x in range(3, int(sqrt(n)+1), 2))). This has the advantage that the range does not get consumed into a list which makes this stop generating values as soon as a value is found not to be prime.

This gives:

from math import sqrt

def primes(lista):
    return all(n == 2 or (n % 2 and all(n % x for x in range(3, int(sqrt(n)+1), 2))) for n in lista)

But if you really want to make it more readable, you should factor out the prime check into another function:

from math import sqrt

def is_prime(n):
    """Check if `n` is prime.

    Uses exhaustive search to look for factors up to sqrt(n) + 1.
    """
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    return all(n % x for x in range(3, int(sqrt(n) + 1), 2))

def all_primes(lista):
    """Check if all numbers in `lista` are primes."""
    return all(is_prime(n) for n in lista)

Another alternative is to compute a set of primes once and then just check if all of them are in this set:

primes_set = set(prime_sieve(100000))

def all_primes_set(lista):
    lista_set = set(lista)
    return len(primes_set & lista_set) == len(lista_set)

On my machine all of these are faster than your original function:

primes_list = list(prime_sieve(100000))

%timeit primes_op(primes_list)
77.3 ms ± 373 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit primes(primes_list)
67.8 ms ± 706 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit all_primes(primes_list)
70.9 ms ± 235 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit all_primes_set(primes_list)
823 µs ± 9.53 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

So if you know what the largest number is which you need to check, checking against a set that is computed only once is the fastest.


List Any vs Count, which one is better for readability?

For me, it's about intent. What does your code's business logic say if you read it in English (or your native language)?

It usually comes to me as "If there are any employees who are in the management role, then show a particular option panel".

And that means .Any(). Not .Count(). Very few times will I find myself using .Count() unless the underlying rule talks about "more than one" or "more than two" of something.

As a bonus, .Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....


Making a job completed, rolling back on error

Yes.

Throw specialized exceptions like CannotMarkJobCompletedException and CannotRollbackTransactionException...
Make your toString() method on exceptions to return something you want what your logger to log
Instead of doing: ...CAN_..._COMPLETED + jobId, you may do: thrown exception already knows this jobId
Store the thrown exception in a variable and call your logger once

By doing all of that you will solve the problem of having nested try-catch blocks.


In general your code looks nice, but it does show that you've got a another programming language background, and thus you do it the standard imperative way instead of utilizing some of the more pythonic way. In this review I'm deliberately going a little over the top, but in return you get to see some of the more special pythonic constructions.

Using __doc__ to get the docstring for display_help – In Python you can and should describe your code using docstrings, typically text with triple quotes, i.e. """ ... """. These can be used to describe the module, functions, classes (and methods). They typically come on the line after the definition of the item you want to document.

A neat thing is that this docstring can be accessed using a special variable, __doc__, or for a function as display_help.__doc__. And then it can be used for print outs, or similar.
Work a little more on naming methods – It is not very common in Python to have get_xxxx methods, rather name them according to specific function, like roll_multiple_dice() or roll_die(). Aim for simplicity and clarity. Using get_answer() implies that you want me to insert the answer of something, whilst number_of_pythons() indicates that this is going to be calculated.
List comprehensions are your friend – Instead of repeating code to build the list, use return [roll_die() for _ in range(number_of_dice)] which implements three nice features:

A list comprehension, which builds a list based on the inner generator, i.e. [ ... ]
The use of for within the generator, x for x in range(y), which compresses a for loop into the expression. This one would return the numbers from 0 to y-1
The use of _ when we don't really care about the number, but just want the code in front of the for loop to be executed

Generator expressions – The for loop of last item, can also be used outside of list comprehension, i.e sum(x for x in range(y)), which would sum all the numbers from 0 through y-1.

One major difference between a list comprehension and generator, is that the list comprehension actually builds the entire list, whilst the generators works in the background and gives you another element when you want it.

In the sum example this means that if you had y=1000000 you wouldn't allocate memory for more than 1 int, whilst if you used list comprehension you would allocate the entire list of 1 million elements, and then sum it.
The Python ternary, i.e. a  = b if c else d – This could take some time to get used to, but actually it reads out quite nicely: Set the value of a to b if the condition c is true, or d if not true.

Disclaimer: In my refactored code this is where it got a little ugly, as I combined multiple of this construction. But still, they kind of make sense. I used them in both number_of_pythons() and print_dice().
Avoid one-time intermediate variable – It's quite common to skip the intermediate variable, especially if you use them only once, and rather use the expression directly. I.e. in roll_die() just return the random number, and in roll_multiple_dice() return the list directly.
In some cases, you can sum using Booleans – Doing the if True: a += 1 is kind of an anti-pattern, and can in some cases be replaced by a += True, or in your case: streak += play_once(...).

Bug found by 200_success: Here the simplification went too far, as I by simply summing, removed the resetting of the streak counter.

Avoid flag variables, if possible – Your use of valid in get_guess() is better written using while True and a break like in your input validations. And skipping the intermediate variable, you could return straight out of the loop.
Try to avoid the chained if commands, doing the same stuff – In both get_answer() and print_dice() you have if chains where the block kind of does the same. This is usually an indication that you could find a better way of handling it.

In get_answer() I opted for a double ternary, doing answer += 2 if i == 3 else 4 if i == 5 else 0.
In print_dice() I used the fact that a six sided die has only 5 distinct patterns, and then I used yet another double ternary to select from the different options.

Disclaimer: Even though this code is a lot shorter than yours, that doesn't mean it is nicer as such. But it does show an alternate way, and there are multiple ways to print die results. See here or here.

Use constants, not magic number – Instead of hiding a 5 and an 8 in the code, use constants at top of file like REQUIRED_STREAK_RUN = 8 and NUMBER_OF_DICE = 5. This allows you to change them easily (and you can still make the document reflect the change using str.format()
Use str.format() for string formatting - This is a very useful construct, which is well worth some time to look into. You could either use it without names (see end of play_once()), or you could name your variables like in display_help().

PS! If using Python 2, I recommend using from __future__ import print_function to get the full extent of this beauty there as well.
Feature: You can't quit your program without becoming a Pythentate – I think it's nice to give users a way out. I've implemented a lazy version with terminating if entering a negative answer. This could be done a lot nicer, but it should be an option to quit at any time.

Refactored code

Here is the code using most (if not all) of the advice from above:

"""Pythons Around the Rose

The name of the game is Pythons Around the Rose.
The name is important. I will roll {number_of_dice} dice,
and I will tell you how many pythons there are.

For example:

| .   . |       | .   . | .     | .   . |
|   .   |   .   |       |   .   |   .   |
| .   . |       | .   . |     . | .   . |

Will result in 10 pythons. If you answer
correctly a given {streak_run} number of times you
will be declared a "Pythentate of the Rose".
"""
import random
import sys

REQUIRED_STREAK_RUN = 8
NUMBER_OF_DICE = 5

def display_help():
    """Use the docstring of the module."""
    print(__doc__.format(number_of_dice = NUMBER_OF_DICE,
                         streak_run = REQUIRED_STREAK_RUN))

def play():
    """Play until declared a Pytentate..."""
    streak = 0
    while True:

        # My bug: streak += play_once(roll_multiple_dice(NUMBER_OF_DICE)):
        if play_once(roll_multiple_dice(NUMBER_OF_DICE)):
            streak += 1
        else:
            streak = 0

        if streak == REQUIRED_STREAK_RUN:
            print('You are now declared a "Pytentate of the Rose"!')
            break

    print("Thank you for playing!")

def roll_multiple_dice(number_of_dice):
    """Return a list of die rolls."""
    return [roll_die() for _ in range(number_of_dice)]

def roll_die():
    """Return a single die roll."""
    return random.randrange(6) + 1

def play_once(results):
    """Play a single round, and return True if correct guess."""
    print("How many pythons here?")
    print_dice(results)

    guess = get_guess_of_pythons()

    # Simple bail out option... :-)
    if guess < 0:
        sys.exit(0)

    answer = number_of_pythons(results)
    if guess == answer:
        print("Correct!")
        return True

    print("Incorrect. The answer is {}".format(answer))
    return False

def get_guess_of_pythons():
    """Get input of pythons from user."""
    while True:
        try:
            return int(input("> "))
        except:
            print("\nOops! That is not a number. Try again: ")

def number_of_pythons(dice):
    """Return correct number of pythons."""
    return sum(2 if i == 3 else
               4 if i == 5 else
               0 for i in dice)

EYES = ["       |",
        "   .   |",
        " .     |",
        "     . |",
        " .   . |"]

def print_dice(dice):
    """Return a three-line string of all the dice."""
    rows = ["|", "|", "|"]
    for i in dice:
        rows[0] += EYES[0] if i == 1 else \
                   EYES[2] if i < 4 else \
                   EYES[4]

        rows[1] += EYES[4] if i == 6 else \
                   EYES[1] if i % 2 == 1 else \
                   EYES[0]

        rows[2] += EYES[0] if i == 1 else \
                   EYES[3] if i < 4 else \
                   EYES[4]

    print('\n'.join(rows))

def main():
    display_help()
    play()

if __name__ == '__main__':
    main()

Conclusion

I hope you are not intimidated by the length of this answer, or the content, because your code does look nice and it does do the work. But there are things to work with to make it more Pythonic, and I hope you've gotten a gist of even more of the beauty of Python here.


You can call it more directly using this:

return ko.bindingHandlers.text.update(element, valueAccessor);

The valueAccessor is already a function that returns the value, and update already uses unwrap internally, so there is no need to use the inline function.

Or more safely, preserving the other arguments to the handler, you can call it like this:

return ko.bindingHandlers.text.update.apply(this, arguments);

However, wrapping text binding handler is better done with a preprocessor, to ensure that other parts of the binding lifecycle are handled normally.

ko.bindingHandlers.line = {
    preprocess: function (value, name, addBinding) {
        addBinding('text', value);
        return value;
    },
    update: function (element, valueAccessor, allBindings) {
        if (ko.unwrap(valueAccessor())) {
            $(element).after('<br />');   // Make the element invisible
        }
    }
};

Here is a fiddle.


Solving a linear system with two variables

The good thing is, that you have made some meaningful methods with descriptive names.

But you have a quite peculiar workflow:

public void NumberGeneration()//1.Generates the variables, calculates x and y.
{
    a = rnd.Next(1, 10);
    b = rnd.Next(1, 10);
    c = rnd.Next(1, 10);
    d = rnd.Next(1, 10);
    e = rnd.Next(1, 10);
    f = rnd.Next(1, 10);
    y = ((a * f - c * d) / (a * e - b * d));
    x = ((c - (b * y)) / a);
    CheckForZeros();
}

Here you check for dividing by zero after you do the calculation that is supposed to be guarded by the check.

And calling NumberGeneration() recursively from CheckForZeros() and EnsureWhole()   if something goes wrong has the potential to end in a stack overflow, if all the generated sets of values fail in the two tests. This is not a good use of recursion, instead you should use an iterative approach and provide a value for max retries before the generator returns unsuccessfully.

Have you considered this condition properly:

  else if ((dy % 1) != 0 || (dx % 1) != 0)//Otherwise start again, generate a new set of numbers and attempt for a new answer where x and y are ints
  {
    NumberGeneration();
  };

Why must at least one of the result values in the current failed calculation be a decimal number in order to allow a new calculation with an entire new set of data? It makes no sense to me.

If everything go well you end the calculations by formatting a pair of private strings and then nothing happens:

    question = string.Format($"{a}x+{b}y={c}, \n {d}x+{e}y={f}", a, b, c, d, e, f);
    answer = string.Format($"x={x} and y={y}");

I imagine that you provide these results to the client in some way or else all the efforts seem useless :-)

In

  (dy % 1) != 0

  (a * e - b * d) == 0

The parenteses are unnecessary.

And so are the outmost parenteses in this expression:

  y = ((a * f - c * d) / (a * e - b * d))

I think you normally will solve the system with + between the parts:

  ax + by = c
  dx + ey = f

  <=>

  y = (cd - af) / (bd - ae)
  x = (c - by) / a

The randomly generated input values (a..f) are all integers, so you could do all calculations as integer calculations, because you only want solutions with integral x and y. That will make the calculations a lot easier and more reliable. Checking if two double values are equal is often not reliable.

There are a lot of ways to structure this kind of exercise. Below I have posted one version. I'm not claiming it to be the way to do it, but you may find some inspiration.

The approach is rather traditional, and I have focused on an easy-to-follow workflow, naming and testability - at least to a some level. It's only using integer values and calculations.

The solver itself controlling the workflow and doing the calculations:

///
/// Creates a random linear system of two equations with two variables of first degree and find a
/// possible solution with integral values for the variables x and y. This is the same as
/// finding the intersection between two lines in the plane.
///
public class LinearSystemSolver
{
  private readonly int maxRetries;
  private readonly ICoefficientProvider coefficientProvider;

  ///
  /// Constructor
  ///
  /// <param name="maxRetries">The number of times to try to find a valid solution before returning false from TrySovle().</param>
  /// <param name="coefficientProvider">An object that provides the coefficients in a linear system to solve.</param>
  public LinearSystemSolver(int maxRetries, ICoefficientProvider coefficientProvider)
  {
    this.maxRetries = maxRetries;
    this.coefficientProvider = coefficientProvider
                               ?? throw new ArgumentNullException(nameof(coefficientProvider));
  }

  public bool TrySolve(out IntegralLinearSystem result)
  {
    result = IntegralLinearSystem.Empty;

    for (int i = 0; i < maxRetries; i++)
    {
      Coefficients coefficients = GenerateCoefficients();
      if (HasSolution(coefficients) && GetIntegralSolution(coefficients, out int x, out int y))
      {
        result = new IntegralLinearSystem(coefficients, x, y);
        return true;
      }
    }

    return false;
  }

  private Coefficients GenerateCoefficients()
  {
    return coefficientProvider.GetCoefficients();
  }

  private bool HasSolution(Coefficients coefficients)
  {
    // This is a test of bd - ae != 0
    return coefficients.B * coefficients.D != coefficients.A * coefficients.E;
  }

  private bool GetIntegralSolution(Coefficients coefficients, out int x, out int y)
  {
    int numY = coefficients.C * coefficients.D - coefficients.A * coefficients.F;
    int denomY = coefficients.B * coefficients.D - coefficients.A * coefficients.E;
    y = numY / denomY;

    int numX;
    int denomX;
    if (coefficients.A != 0)
    {
      numX = coefficients.C - coefficients.B * y;
      denomX = coefficients.A;
    }
    else
    {
      // A and D can not both be 0 because the system then doesn't have a solution (the two lines are parallel with the x-axis)
      // A = D = 0 would have been caught by HasSolution() before ending here
      numX = coefficients.F - coefficients.E * y;
      denomX = coefficients.D;
    }
    x = numX / denomX;

    return numY % denomY == 0 && numX % denomX == 0;
  }
}

An object representing the integral solution - if found:

///
/// Object representing a linear system of first degree with two variables with integral solutions for x and y.
///
public struct IntegralLinearSystem
{
  public static readonly IntegralLinearSystem Empty = new IntegralLinearSystem(Coefficients.Empty, 0, 0);

  public IntegralLinearSystem(Coefficients coefficients, int x, int y)
  {
    Coefficients = coefficients;
    X = x;
    Y = y;

    if (!IsValid)
      throw new InvalidOperationException("Inconsistent integral linear system");
  }

  public readonly Coefficients Coefficients;
  public readonly int X;
  public readonly int Y;

  public bool IsValid
  {
    get
    {
      return
        Coefficients.A * X + Coefficients.B * Y == Coefficients.C &&
        Coefficients.D * X + Coefficients.E * Y == Coefficients.F;
    }
  }

  public override string ToString()
  {
    StringBuilder builder = new StringBuilder();
    builder.Append(Coefficients);
    builder.AppendLine();
    builder.AppendLine("<=>");
    builder.AppendFormat("x = {0}, y = {1}", X, Y);

    return builder.ToString();
  }
}

An object representing the constant values (coefficients) for the system

///
/// Object holding the coefficients to x and y and values on the right side
/// of the equal sign in a linear system with two variables of first degree
/// on the form ax + by = c and dx + ey = f
///
public struct Coefficients
{
  public static readonly Coefficients Empty = new Coefficients();

  public readonly int A;
  public readonly int B;
  public readonly int C;
  public readonly int D;
  public readonly int E;
  public readonly int F;

  public Coefficients(int a, int b, int c, int d, int e, int f)
  {
    A = a;
    B = b;
    C = c;
    D = d;
    E = e;
    F = f;
  }

  public override string ToString()
  {
    return $"{A}x + {B}y = {C}{Environment.NewLine}{D}x + {E}y = {F}";
  }
}

The contract between the solver and the generator of the constant values:

public interface ICoefficientProvider
{
  Coefficients GetCoefficients();
}

An object providing randomly generated coefficients to the system:

///
/// Creates randomly generated coefficients to a linear system of two variables.
///
public class RandomCoefficientProvider : ICoefficientProvider
{
  private readonly int min;
  private readonly int max;
  private readonly Random random;

  ///
  /// Constructor
  ///
  /// <param name="min">The inclusive lower boundary of the random numbers returned.</param>
  /// <param name="max">The exclusive upper boundary of the random numbers returned.</param>
  /// <param name="randomSeed"></param>
  public RandomCoefficientProvider(int min, int max, int? randomSeed = null)
  {
    this.min = Math.Min(min, max);
    this.max = Math.Max(min, max);
    random = randomSeed == null ? new Random() : new Random(randomSeed.Value);
  }

  public Coefficients GetCoefficients()
  {
    return new Coefficients
    (
      random.Next(min, max),
      random.Next(min, max),
      random.Next(min, max),
      random.Next(min, max),
      random.Next(min, max),
      random.Next(min, max)
    );
  }
}

Use Case:

  LinearSystemSolver solver = new LinearSystemSolver(10, new RandomCoefficientProvider(1, 10));
  if (solver.TrySolve(out IntegralLinearSystem result))
  {
    Console.WriteLine($"Result:{Environment.NewLine}{result}");
  }
  else
  {
    Console.WriteLine("No integral solution found");
  }

As seen, I have created the interface ICoefficientProvider in order to separate the (random) creation of the constant values of the system from the workflow and calculations.
It gives me the possibility to implement another coefficient provider like the below - for testing purposes - without changing anything in the solver:

///
/// A Coefficient Provider that can be used for testing purposes
///
public class ConstantCoefficientProvider : ICoefficientProvider
{
  private readonly Coefficients coefficients;

  public ConstantCoefficientProvider(int a, int b, int c, int d, int e, int f)
  {
    coefficients = new Coefficients(a, b, c, d, e, f);
  }

  public Coefficients GetCoefficients()
  {
    return coefficients;
  }
}

You could easily extend this pattern of dependency injection to handle other parts of the program, for instance the calculations.


Divide decimal by range of fractions, and then convert the fraction that is closest to a whole number to a mixed fraction

Trust the math.

        var fraction = 1 / i;
        var result = myDecimal / fraction;

is a long way to say

        var result = myDecimal * i;

Collecting results in the list is just a waste of space. You may maintain the most accurate candidate as you do compute results:

    for (double i = 1; i < 49; i++)
    {
        var result = myDecimal * i;
        var roundedResult = Math.Round(result);
        var remainder = roundedResult - result;
        if (remainder < bestRemainder) {
            bestRemainder = remainder;
            bestDenominator = i;
        }
    }


As @vnp has pointed out, each bulb can have two states, so the number of possibilities is \$2^N\$. However, the state where all bulbs are off is prohibited, so subtract one, and is the answer is simply \$(2^N -1) \mod 10^5\$.

The tricky part of the problem is that \$2^{{10}^4} -1\$ is a very large number to work with, so calculating \$(2^N -1) \mod 10^5\$ is a non-trivial problem.


Adding data to database using asp.net and sql-server

I would personally encapsulate your instantiation of MusicStoreDBEntities in a using statement so that the database connection is properly closed and disposed of.

using (MusicStoreDBEntities obj = new MusicStoreDBEntitiesObj())
{
    //code to add record goes here...
}

I think you should also pass in Instrument Item as a single parameter to AddStringInstrumentItems() rather than each individual property of that object so...

public static void AddStringInstrumentItems(instrumentItem item)
{
    using (MusicStoreDBEntities obj = new MusicStoreDBEntitiesObj())
    {
        obj.instrumentItems.Add(item);
        obj.SaveChanges();
    }
}

And in your instrumentItem class you want a constructor to instantiate it.

public instrumentItem(int typeId, int brandId, string model, double price, String itemimage1, String itemimage2, string description, string necktype, string body,
string fretboard, string fret, string bridge, string neckpickup, string bridgepickup, string hardwarecolor)
{
    this.typeId = typeId;
    this.brandId = brandId;
    // so on
    // so forth
}


To "Safely" store data, please don't use mysql_* functions. Use PDO or mysqli.

Also, use PreparedStatements wherever you use "where" clause in queries. That will protect you against injection.

http://au1.php.net/pdo.prepared-statements


Greedy solution not correct

First, we can transform the problem as OP did by taking the difference of the book values in each pair, and then trying to split these new values in to two equal halves.  In the example of (3,5), (7,11), (8,8), (2,9), this transforms into trying to split 2 4 0 7 into equal halves, which is achieved as closely as possible with the solution [0,2,4][7].

The greedy solution attempts to place the largest unused value on the smallest pile.  In the example above, the sorted values are 7 4 2 0, and the values are placed in the following way:

    Pile 1      Pile 2
    ------      ------
     7
     7           4
     7           4,2
     7           4,2,0

leading to the correct answer.

However, consider the case of 5 5 4 3 3.  In this case, the greedy method would place the values as follows:

    Pile 1      Pile 2
    ------      ------
     5
     5           5
     5,4         5
     5,4         5,3
     5,4         5,3,3

Ending with piles of size 9 and 11, with a difference of 2.  However, the optimal solution would be piles [5,5][4,3,3] with a difference of 0.

Dynamic Programming

Instead of a greedy method, you can use a dynamic programming method to solve the problem.  The algorithm will be as follows:

Transform the initial input by taking the absolute value of the differences between each pair of books.  This is the new list of values we will use.
Sum the list of values.  Call this sum total.  We are now trying to find a subset of the values that will sum as closely to total/2 as possible (without going over).  You can convince yourself that this subset will provide us with the best answer to the problem.
Create an array of booleans of size (total/2) + 1 and initialize to false, except for element arr[0] which you initialize to true.  Each element of this array contains whether it is possible to reach a sum of that index.  For example, if in the end, arr[15] is true, then it is possible to create a subset that sums to 15.
For each element in the list of values, you traverse the array, and whenever you find arr[j] to be true, you can set arr[j+val] to be true. Note: this traversal needs to start at arr[max-val] and search towards arr[0].  If you traverse in the forwards direction, the act of setting arr[j+val] to true will cause that array element to trigger later in the loop when it shouldn't.  For example, if val were 1, the forwards loop would mistakenly set every element in the array to true.
Once step 4 is finished, your array holds all the possible subsums.  Find the largest possible subsum, and that will be the value of one pile.  Call that value largestSum.  The other pile will have value total - largestSum.  The difference will be total - 2*largestSum, which is the answer to the question.

This approach will have complexity \$O(n * m)\$, where \$n\$ is the number of book pairs and \$m\$ is the total of all the differences.  In the problem description, there are max 150 books with max value 300, so the maximum value for \$m\$ is 45000.

Compare this to the recursive solution which tries to place each value in each pile, which has complexity \$O(2^n)\$.

Sample implementation using dynamic programming

I took your program and adjusted it to use the dynamic programming approach described above.  Here is the result:

#include <iostream>
#include <algorithm>
#include <cmath>

int main (int argc, char const* argv[])
{
    int n;
    std::cin >> n;
    int difference[n];
    int total = 0;
    for(int i=0;i<n;i++){
        int a,b;
        std::cin>>a >>b;
        difference[i] = std::abs(a-b);
        total += difference[i];
    }

    // Find each reachable sum up to total/2.
    int  max = total/2;
    bool arr[max+1] = { true };
    for (int i = 0; i < n; i++) {
        int val = difference[i];
        for (int j = max - val; j >= 0; j--) {
            if (arr[j])
                arr[j+val] = true;
        }
    }

    // Find the max reachable sum.  For that sum, print the difference between
    // one child's sum (i) and the other's (total - i).  Since i is always
    // less than or equal to (total - i), the difference will be total - i - i.
    for (int i = max; i >= 0; i--) {
        if (arr[i]) {
            std::cout << total - i - i << std::endl;
            break;
        }
    }
    return 0;
}


GetNeighborhood function for 3D cells structure in MATLAB

I think the biggest gain in efficiency you can get is to  not use a cell array. Each element of a cell array is an array. Each array has a header data structure that takes up 104 bytes (if I remember that number correctly). Storing only one number in an array means that there is a memory overhead of 104/(104+8)=92%. Access is also slower because of the double indirection. To store individual numbers you should always use a numeric array.
This code:
if X + x < 1
   xLocation = 1;
elseif X + x > size(inputCells, 1)
   xLocation = size(inputCells, 1);
else
   xLocation = X + x;
end

has quite some redundancy. Every time you write the same expression twice, you should think about storing the result of the expression. Even if the computation is trivial and likely not to slow down your code, duplicated code still leads to maintenance issues. You could do instead:
xLocation = X + x;
maxLocation = size(inputCells, 1);
if xLocation < 1
   xLocation = 1;
elseif xLocation > maxLocation
   xLocation = maxLocation
end

This can be further simplified using max and min:
xLocation = X + x;
xLocation = max(xLocation, 1);
xLocation = min(xLocation, size(inputCells, 1));

You could maybe even simplify this to a single line of code, though that doesn’t improve readability:
xLocation = min(max(X + x, 1), size(inputCells, 1));

Furthermore, this code is repeated three times, so you should make it into a function you can call three times.
Once your input and output are numeric arrays, you can likely vectorize the operation, removing the loops and further simplifying the code.
clear all is not recommended. clear by itself clears the workspace, deleting all defined variables. Adding the all argument causes it to additionally remove from memory all parsed and pre-compiled functions, meaning that the next time you call those functions they’ll take longer to run. clear all is hardly ever needed, and should not be a part of your normal workflow.


Counting thousands of selected checkboxes

I suspect you're going to struggle to optimise that, as DOM manipulation is always slow. See this guy's answer.

You could try do something like he suggests, keeping your data and the DOM separate from each other.

  Currently it loops through the entire form to count how many check boxes are selected, each time a checkbox is clicked

Why not increment or decrement a counter when a checkbox's state is changed? That'll be a lot quicker.


Simple todo list VanillaJS - repository pattern

General points

There is no need to add localStorage to the Repository object as it is part of the global this.
You can access localStorage values directly by the key name [.1].  Eg setting localStorage.myData = "Hi World", getting const message = localStorage.myData, to check if it exists localStorage.myData !== undefined, to empty a value localStorage.myData = undefined, and to delete delete localStorage.myData
LocalStorage should not be trusted. Calling JSON.parse on data from local storage should always be wrapped in a try catch in case the data has been modified by a 3rd party.
Using filter to remove items from an array is not as efficient as locating the item's index and splicing it. Even better would be to store the todo array as a Map indexed by uuid see second example.
You have some poor naming due to the repeated prefixing of todo to all the functions. I can imagine that the Repository is called todoList and thus is would be todoList.addTodo  todoList.removeTodo and so on.  Would be far more readable if you drop the todo . Eg todoList.add,  todoList.remove, ...
You are repeating code. Both add and remove functions filter (remove) a todo. I would be better for add to call remove

Good OO design

Javascripts class syntax is something you should avoid as it forces you to create objects with poor encapsulation (if you don't use the "abomination" that is # private  prefix) Javascript has several very robust object patterns that provide air tight encapsulation and should be used if you wish to follow good OO design.

The examples shows and immediately invoked function (IIF) pattern that defines the Object Repository as a function returning an ad hock Object that encapsulates via closure.

The todos array (or map) is isolated and not directly accessible. It uses a getter to return the array of todos as a shallow copy

Examples

Both examples use IIF pattern to encapsulate the object created from the named Repository

Note that it has slightly different behavior than your object.

You can instantiate the object with or without the new token. Eg todos = Repository() or todos = new Repository()

The first example store data in an array that it keeps private, copied on creation and copied when accessed via the getter todos.

IFF ad hock

export default Repository = (() => {
    const save = (todos) => localStorage.todos = JSON.stringify(todos);
    const load = () => {
        try { return localStorage.todos ? JSON.parse(localStorage.todos) : [] }
        catch(e) { return [] }
    }
    return function(todos = []) {
        todos = [...todos];
        return Object.freeze({
            get todos() { return [...todos] },
            remove(todo, saveChanges = true) {
                const idx = todos.findIndex(item => item.uuid !== todo.uuid);
                idx > -1 && todos.splice(idx, 1);
                saveChanges && save(todos);
            },
            add(todo, saveChanges = true) {
                this.remove(todo, false);
                todos.push(toDo);
                saveChanges && save(todos);
            },
            save() { save(todos) },
            load() {
                load().forEach(todo => this.add(Object.assign(new Todo(), todo), false));
                return this.todos;
            }
        });
    }
})();

IFF with Map

This example uses a map to improve the efficiency of removing items and reduces the source size. It behaves identically to the first example.

Also as using this does present a security concern (even in modules) thus example references self via the named constant API

export default Repository = (() => {
    const save = (todos) => localStorage.todos = JSON.stringify(todos);
    const load = () => {
        try { return localStorage.todos ? JSON.parse(localStorage.todos) : [] }
        catch(e) { return [] }
    }
    return function(todosInit = []) {
        const API = Object.freeze({
            get todos() { return [...todos.values()] },
            remove(todo, saveChanges = true) {
                todos.delete(todo.uuid);
                saveChanges && API.save();
            },
            add(todo, saveChanges = true) {
                API.remove(todo, false);
                todos.set(todo.uuid, todo);
                saveChanges && API.save();
            },
            save() { save(API.todos) },
            load() {
                load().forEach(todo => API.add(Object.assign(new Todo(), todo), false));
                return API.todos;
            }
        });
        return API;
    }
})();

Notes

[.1] Note that MDN localStorage page cites "The pitfalls of using objects as maps" as reason not to use direct key access. Why only warn on localStorage why not have the same warning on every Object? Get with it MDN!!


I'm severely confused by array.move_down, because I don't see any array or anything moving anywhere. If you are doing a super_list, wouldn't it be more readable to have sublist.begin and sublist.end?

Also I don't like fail-later approach with hiding an exception. If user makes an error in nesting lists, I would fail fast instead. It's a common behavior of all the languages I know (with an exception of early/ancient HTML).


By the way, the fastest way to see if a number is divisible by three is to use (zero? (remainder n 3)). If you want to do the digit summing for fun, fine, but it will make your code slower.

So, one way to sum the digits is to extract digits directly during the summing process, rather than building a list of digits first.

(define (digisum n)
  (let loop ((sum 0) (n n))
    (define-values (q r) (quotient/remainder n 10))
    (if (zero? n)
        sum
        (loop (+ sum r) q))))

Alternatively, you can use a for comprehension for this:

(define (in-digits n (base 10))
  (make-do-sequence
   (thunk (values (curryr remainder base)
                  (curryr quotient base)
                  n
                  positive?
                  #f #f))))

(define (digisum n)
  (for/sum ((digit (in-digits n)))
    digit))


Any solution to this would have to be at least O(n), because worst case you're going to have to check every character in the String.

A very simple solution to this problem is to create an array of 5 booleans, corresponding to the 5 vowels. Then iterate through the string, and if you see a vowel, mark that index (e.g. a = 0, e = 1, etc.) as true. As soon as all 5 are true, return true, as all the vowels occur (assuming that you don't care if they occur more than once).

That has the same time complexity as your regex solution and is far simpler to implement/read/maintain.

You could also sort the string and then binary search for each of the required characters. This has a higher upfront cost (nlogn for the sort, logn for each binary search), but if you're making multiple queries on the same string, might be more efficient in the long run.


Slicing up an image into rows and columns in Java

Not sure I understand your problem but what about changing the signature of you constructor to:

GridImage(String path, String filename, int rows, int columns)

And have path and filename be attributes of your object.

I don't know why you implemented it as a runnable, but then I would also put all the code in the run method (starting with loading the file)...

OK I got what you are asking now, do the following:

File originalImage = new File(filename);
String path = originalImage.getPath();
String fileName = originalImage.getName();

Now you have all you need to create your new files.

BTW: have a look at the File javadoc...


The first thing that comes into my mind is that if evapPerDay is <= 0 the function will continue infinitely - or more precise: until a stack overflow is encountered. So you have to guard against that:
let evaporatorReview (content: float) (evapPerDay: float) (threshold: float): int =
    if evapPerDay <= 0. then
        failwith "evapPerDay must be greater than 0.0"
    else
        // ... The original algorithm

The next is that by having the unnecessary local result variable solve() isn't tail recursive. You can fix that by simply return directly from the match-entries:
let evaporator (content: float) (evapPerDay: float) (threshold: float): int =
    let minUsefulAmount = content * (threshold / 100.)
    let evapAsPercentage = evapPerDay / 100.

    let rec solve (content: float) (dayCount: int) =
        let amountLost = content * evapAsPercentage
        let newContent = content - amountLost
        let stillUseful = newContent > minUsefulAmount

        match stillUseful with
        | true -> solve newContent (dayCount + 1)
        | false -> dayCount
    solve content 1

IMO all the temporary variables in solve() blur what actually is going on. By skipping them and do the calculations directly in the recursive call to solve() the picture is more clear:
let evaporator (content: float) (evapPerDay: float) (threshold: float): int =
    if evapPerDay <= 0. then
        failwith "evapPerDay must be greater than 0.0"
    else
        let limit = content * threshold / 100.
        let rec solve (content: float) (dayCount: int) =
            match content with
            | x when x <= limit -> dayCount
            | _ -> solve (content * (1. - evapPerDay / 100.)) (dayCount + 1)

        solve content 0

In fact you don't have to calculate on the content, you can do it percentage wise:
let evaporatorReview (content: float) (evapPerDay: float) (threshold: float): int =
    if evapPerDay <= 0. then
        failwith "evapPerDay must be greater than 0.0"
    else
        let limit = threshold / 100.
        let rec solve (remaining: float) (dayCount: int) =
            match remaining with
            | x when x <= limit -> dayCount
            | _ -> solve (remaining * (1. - evapPerDay / 100.)) (dayCount + 1)

        solve 1. 0

The mathematical "discipline" in question here is exponential growth (r > 0) or decay (r < 0) and there is a formula for that:
Xn = X0 * (1 + r)^n

Where Xn is threshold, X0 is 100 or content, r is evapPerDay / 100. and n is the number of days = the result.
This can be use in sequential calculations ending when the threshold is met:
let evaporatorSeq (content: float) (evapPerDay: float) (threshold: float): int =
    if evapPerDay <= 0. then
        failwith "evapPerDay must be greater than 0.0"
    else
        let limit = threshold / 100.0
        Seq.initInfinite (fun i -> i)
        |> Seq.takeWhile (fun n -> Math.Pow(1.0 - evapPerDay / 100.0, float n) > limit)
        |> Seq.last
        |> (+) 1

But even better, it can be solved in respect to n as :
n = log(Xn/X0) / log(1 + r)

which can be used in the function as an O(1) - solution:
let evaporator content evapPerDay threshold =
    match evapPerDay with
    | x when x = 100. -> 1
    | x when x <= 0.0 -> failwith "evapPerDay must be greater than 0.0"
    | _ -> int (Math.Ceiling(Math.Log((threshold / 100.) / 1.) / Math.Log(1. - evapPerDay / 100.)))

The division by 1. is of cause redundant, but it emphasize the relation of the expression to its origin.
if evapPerDay = 100. then 1 is necessary here because if evapPerDay = 100 then Math.Log(1.0 - evapPerDay / 100.) becomes Math.Log(0.) which isn't defined.


Afew things I noticed:

Concatenating strings using the plus operator(+), is very inefficient.  Each concatenation creates a new string.  This due to strings being immutable.  Using a char array or the StringBuilder is much more efficient.

The variable next is a double but the value you're assigning to it is 2 ints added together.  It would make much more sense to have this as a char.  In fact you should declare this before the if block to be able to use it in each condition.

Equals isn't doing what you appear to think it does.  Equals is for testing whether 2 objects are the same.  == is for testing whether 2 objects values are the same.

You appear to expect only lower case characters and spaces.  However you don't seem to have any mechanism for testing whether the string complies with that.

You can simplify getting the replacement character by using the modulus(%) operator. Something like this should work:  newChar = (char)(((oldChar - 'a') + key) % 26) + 'a'

Your code won't work right if the string has words from a language that uses two bytes to represent one character.

Right now you've hardcoded the key.  It would be better to have a method that takes the string and the key as parameters.


Compute variance via functional programming

First off, watch your formating. Java standard is to have spaces around operators, and a space after commas. In the reduce lambda you can leave out the return and the braces, just like you did't for iterate.
It's a bit ugly to use a DoubleStream for the array indices, and number streams provide a sum() method, so using reduce is unnecessary.
An array can easily streamed using Arrays.stream(), which produces an IntStream and  with mapToDouble a DoubleStream can be created:
double summation = Arrays.stream(array)
                     .mapToDouble(x -> (x - mean) * (x - mean))
                     .sum();


There is a race condition here:
while os.path.exists(self._lock_file_path):
...
with open(self._lock_file_path, "w") as fn:

The file could have been created by the other process in between. You need to check file existence and create the file in one operation.
Since python 3.3 there is a special open mode x for this use case:

open for exclusive creation, failing if the file already exists

For example:
while (time.time() - start_time) < self._lock_time_out:
    try:
        with open(self._lock_file_path, "x") as fn:
            fn.write(str(os.getpid()))
    except FileExistsError:
        time.sleep(5)


Ruby method that returns an age from a date of birth

Make an additional function  to handle plural

In-lining the extra logic to handle the plural is messy, I suggest a small separate method:

def plural(word, value)
  "#{value.to_s} #{word}#{value > 1 ? 's' : ''}"
end

Reduce nesting by returning early

If you write

if dob == nil
  return "No Date of Birth"
end

You can reduce nesting in the rest of the function and highlight the handling of the special case.


Run stored procedure from repository using EF

Dictionary<string, string> param: I realize why you named it param and not params, but the real solution was to call it parameters.

Even worse as a name is sqlParametesList: it contains a typo, and the name also contains the type ("List") which is completely superfluous.

But the real problem is that a Dictionary<string, string> is too limited. What if you need to pass an int or a datetime for instance? You even acknowledge this by converting the strings to objects, which isn't a solution at all.

NormalizeProcedureName is a seriously bad idea. It doesn't even do what it says, and what it does can be done far simpler with a string.join() -- not that this would be a good idea either.

I don't get the point of this:

throw new Exception(string.Format("Error in ExecProcedure: {0}", e.Message));

The stack trace should tell you where the exception happened, but you throw it away to create a far simpler error message.

IMO it would be far better to create a custom class to hold the necessary parameter data: the parameter name, its value and its type. You then pass a list of these objects to ExecProcedure, and loop through the list to construct the parameters you need to pass to ExecuteSqlCommand, making sure to also include the correct SqlDbType.

Or perhaps you can simply use SqlParameter instead of a custom class, it depends a bit on how you've abstracted your db logic from your business logic.

EDIT: To provide some guidance, here's an example of how I handled a similar problem.

I had to call a stored proc in an Oracle DB, which required a number of parameters. So I created this class:

public class LogMessageParameters
{
    public DateTime? Date { get; set; }

    public string From { get; set; }

    public long? Code { get; set; }

    public List<OracleParameter> ToOracleParameters()
    {
        return new List<OracleParameter>
        {
            new OracleParameter("DATE", OracleDbType.Date, Date, ParameterDirection.Input),
            new OracleParameter("FROM", OracleDbType.VarChar, From, ParameterDirection.Input),
            new OracleParameter("CODE", OracleDbType.Number, Code, ParameterDirection.Input),
            new OracleParameter("ID", OracleDbType.Number, ParameterDirection.Output)
        };
    }
}

Now all I needed to do was assign the proper values to the properties, and pass this class to the method where I needed to use the parameters.

Is this the ideal way? Not if I had to create a dozen of these classes, no: then I'd made sure to use reflection to figure out the type of a property so I could return the proper OracleDbType, I'd have used an attribute on a property to store the parameter name, etc.


First, use the doge version for everything possible:

    such fizzbuzz much max
        much very i is 0 next i smaller max next i more 1
            very result
            rly i % 3 is 0
                result more "Fizz" next
            wow
            rly i % 5 is 0
                result more "Buzz" next
            wow
            console dose with result or i next
        wow
    wow

As it's a fun fun language, making use of but rly is more important than optimizations:

    very result
    rly i % 3 is 0
        result is "Fizz" next
    but rly i % 5 is 0
        result is "Buzz" next
    but rly i % 15 is 0
        result is i

Making another function for printing instead keeping the result variable looks even better:

    such print much result
        console dose loge with result
    wow

    such fizzbuzz much max
        very i is 1
        much next i smaller max next i more 1
          rly i % 15 is 0
              plz print with "FizzBuzz"
          but rly i % 3 is 0
              plz print with "Fizz"
          but rly i % 5 is 0
              plz print with "Buzz"
          but
              plz print with i
          wow
        wow
    wow


Live-streaming tweets and plot its sentimental value in colors on a world map

Alright time to give this a shot!

Code style

I won't go in deep details, but the PEP8 standard is that methods should use snake_case not camelCase. You can do whatever you want with this information.

Comments

In my opinion, there are way too many comments in your code. Most of them can be removed with some refactoring. I'll try to target the different reasons why some things shouldn't be commented and the associated refactors for them.

There's one for which I don't have a refactor, because it's an old-school method of doing this that, I believe, shouldn't be done anymore :

""" Variables
================"""

Don't do this. People that will read your code will figure out that variables are following. If you change your code over time and keep this comment it's probable that this comment will become obsolete.

There's also the case of this comment : # if we sent a False as return value we close the "pipeline" of streams which just brings a load of confusion in the code. This comment probably doesn't need to exist as when we will see where the method on_data is called, we'll figure it out ourself.

Refactor 1 : Replace comments with better variable names.

maxTweets = 100000 # max number of tweets to analyse.

If you feel the need to put this comment, it's probably because your variable isn't well named. If you named your variable maxTweetsToAnalayse you wouldn't need the comment.

self.counter = 0            # Counts amount of tweets already got

Same here, you should rename your variable, maybe loadedTweetsCount or something like that?

# Checks so that the coordinate is in the tweet
if (datadict.get('place') != None):

Could be replaced by :

coordinateIsInTweet = datadict.get('place') != None
if coordinateIsInTweet:

Refactor 2 : Write validation rules for comments stating rules.

# max 250 input searches in a list of strings

That's something your code should be aware of. Instead of this comment, why not validate it in the code?

if len(searches) > 250:
   raise ValueError("Exceeded maximum searches inputs")

Refactor 3 : Write a method for a comment explaining a bunch of code lines.

# Get the Authentication keys from another file. (Easier to push to git)
# Twitter API needs to be validated

Instead of having this comments, why not do this :

def getTwitterAuthToken():
    with open("/Users/se/Documents/Lek med Python/pyCharmProjects/dataScienceFromScratch/src/twitterKeys.txt","r") as file:
        CONSUMER_KEY        = file.readline().rstrip()
        CONSUMER_SECRET     = file.readline().rstrip()
        ACCESS_TOKEN        = file.readline().rstrip()
        ACCESS_TOKEN_SECRET = file.readline().rstrip()

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

    return auth

The first comment was unnecessary, there are plenty of reasons why a configuration file is better than having hardcoded credentials in your code and your code is clear enough that well... the comment isn't necessary.

Refactor 4 : Use documentation instead of single line comments

# The class takes in a stream of tweets and filter out some specific properties.
# It is a live streaming so it will be kind of slow and in this purpose i filter
# the Coordinates which only around 3-4% of all tweets have.

This explains what the class does, so it should be inside the class. You can create class documentation by doing this (More info here):

class Stream2Screen(tweepy.StreamListener):

    """The class takes in a stream of tweets and filter out some specific properties.
    It is a live streaming so it will be kind of slow and in this purpose i filter
    the Coordinates which only around 3-4% of all tweets have."""

Same can be done for methods :

# This is the method that receives the tweet in the name of data.
def on_data(self, data):

Becomes

def on_data(self, data):
    """This is the method that receives the tweet in the name of data."""

That's about it for comments, I think this was the biggest "weakness" in the code and those refactorings will help make the code much better.


One potential security issue: what if ${drt} is not set before this is run?  A safety check will be very useful.

As for your wider issue, rather than having to download it every time, would it not be just as effective to remove the permissions on the phpmyadmin directory?  If you set it to 000, then nobody should be able to access it nor its contents.


r is always []. Simpler library functions can do some of the work.

zip' [] b = map (-1,) b
zip' a [] = map (,-1) a
zip' (x:xs) (y:ys) = (x, y) : zip' xs ys


C++ number-guessing game (computer tries to guess user's chosen number)

Some things stand out here:

Don't use using namespace std
Consider not using rand()
Prefer using \n over std::endl
return 0 can be dropped from main as it's optional
You really need better variable names. Names should explain what the variable is used for. If you pick better names your superfluous comments can be removed alltogether


Well, I think I broke SQLFiddle...  Just for clarity's sake, I'd refactor the subqueries... that's the best way I know to do step-wise development and refinement.  I know my subquery names suck - they should be descriptive.  I would also strip out un-necessary column names -- or in my case, comment them out.

with qry1 as
    (
        select td.modal_vend_code as vend_code,
               td.modal_vend_numb as vend_numb,
               td.modal_begin_frame as begin_frame,
               td.modal_description as description,
               te.modal_vend_begin_frame as te_begin,
               te.modal_vend_close_frame as te_close,
               tm.modal_class_code       as modal_class_code,
               case tm.modal_class_code
                   when 'A1' then 'AIRFREIGHT'
                   when 'A2' then 'AIRFREIGHT'
                   when 'G1' then 'GROUND'
                   when 'S1' then 'SEABOUND'
                   else 'UNKNOWN'
                end as freight_mode,
               case tm.modal_class_code
                   when 'A1' then 1
                   when 'A2' then 1
                   when 'G1' then 2
                   when 'S1' then 3
                   else NULL
                end as modal_class,
              rank() over (partition by td.modal_vend_code,
                                        td.modal_vend_numb
                               order by td.modal_begin_frame desc) as freight_choice,
               count(*) over (partition by td.modal_vend_code,
                                           td.modal_vend_numb) freight_count
        from  transdetail td
        inner join transeffective te on td.modal_vend_code = te.modal_vend_code
                                     and td.modal_vend_numb = te.modal_vend_numb
        inner join transmodal  tm  on td.modal_vend_code = tm.modal_vend_code
                                  and td.modal_vend_numb = tm.modal_vend_numb
     )
    ,
    qry2 as
    (
        select vend_code,
               vend_numb,
               -- begin_frame,
               freight_mode,
               -- freight_count,
               description,
              row_number() over (partition by vend_code,
                                              vend_numb,
                                              modal_class
                                 order by vend_code,
                                          vend_numb) as modal_class_count
        from
         qry1
           where freight_choice=1
    )

    select vend_code,
           vend_numb,
           description,
           freight_mode
    from qry2
    where modal_class_count=1
    ;

Then again, seeing as when I tried to run this in SQLFiddle, it didn't return for over a minute, and when I tried to refresh, I got a 404 -- my attempt may be a problem.


A JavaScript graph plotter for schoolchildren using paper.js

I'm not familiar with Paper so can't say anything about that. And I won't say much about the HTML, as it's obviously just a functional placeholder, except two points:

Use double quotes " consistently on all attributes.
Don't use on... attributes. Assign event listeners in the script using addEventListener.

Regarding the script:

Use let/const instead of var.
Declare the variable in loops separately in the for statement using let (e.g. don't reuse the same declared variable in all loops).
Use better variable names. I have no idea what z, zz, node2, code2, etc. mean. (Also make sure all variable names start with a lower case letter.)
Don't repeatedly create the same colors in the loops. Create them once outside the loop.


Star rating: Update stars on click and don't lose the actual vote on re-hover

About your HTML:

Consider using the meter element to display the rating:

<meter min="0" max="5" value="3">★★★☆☆</meter>

(However, I don’t know how current user agents present this, i.e., if they add some special styling.)
In any case, you should not use the i element for displaying an icon via CSS. Use span instead if you need an empty element.
If you don’t want to use a form for voting, consider using WAI-ARIA to make voting accessible.