List of TV show episodes, with next/previous episode links for each entry

Some points

Event listeners

When adding event listeners it is considered bad practice to add them in the page content.

You had

<button id="episode1next" onclick="S1E2()">Next episode</button>

Instead use addEventListener

const elem = document.getElementById("episode1next");
elem.addEventListener("click",S1E2); // remove the "on" from event name
                                     // point to the function (no () after function name)
                                     // DONT call the function (has () after function name)

Naming

Use a well defined naming convention, and use it consistently.

Each language has a set of conventions that define how you create names for various things. In JavaScript we use lower camelCase for everything except objects that you create with the new token, for which we use upper CamelCase

Unfortunately JavaScript shares its environment with the DOM (HTML and CSS) and they have a completely different naming convention called BEM, which is incompatible with JS (you can not use BEM names in JS as they break syntax rules) Article regarding BEM and CSS

Ideally you use the correct naming convention for the correct content and learn how to convert between them (when its automatic, when not automatic, and the exceptions)  eg CSS font-size becomes JS fontSize, element data attributes are automatically camelCased, ,any element attribute values (like ids) are not converted and may need to use indirect queries or bracket referencing.)

You will note that these are conventions. Some (like me) opt to follow only one convention. JS camelCase, using it in the DOM and CSS for all names I define. This is not main stream.

You have followed no apparent naming convention and that will make it very hard to know when and where to put capitals, '-' etc. You remember a variable by name, that for mere mortals does not include the naming format.

Use class

If you find your self setting class properties directly to elements you should give a moments time and consider if it is done better using a CSS rule.

You do the following

  document.getElementById("episode1buttons").style.display="block";
     document.getElementById("episode2buttons").style.display="none";

But it would be better if you create a CSS rule hide and apply that rule to the elements class

 /* CSS rule in CCS */
 .hide { display : none; }

 // Unhide and hide elements in JS
 document.getElementById("episode1buttons").classList.remove("hide");
 document.getElementById("episode2buttons").classList.add("hide");

A generic event listener

You have a list of objects related to a TV show. You have coded it by hand for each particular episode which is laborious, prone to error, and just a painful time consuming process.

Using your naming we can improve the code complexity by having only one event listener that can deduce what the click is for and what to do with it.

For this we wrap everything that needs a click event in a containing element ( element id episodes) For each clickable element we add data we can use to determine what to do with the click. (data-clickType and data-episode)

We set up the initial visibility of episodes in the HTML.

    <button id="episode1none" data-clickType="none">-</button>
    <button id="episode1next" data-clickType="next" data-episode="1">Next episode</button>

    <button id="episode2previous" data-clickType="prev" data-episode="2">Previous episode</button>
    <button id="episode2next" data-clickType="next" data-episode="2">Next episode</button>

    <button id="episode3previous" data-clickType="prev" data-episode="3">Previous episode</button>
    <button id="episode3next" data-clickType="next"  data-episode="3">Next episode</button>

**strong text**

Then in javascript add an event listener to the containing element

episodes.addEventListener("click",episodeClick);

And create a listener function that works out what to do with the click

function episodeClick(event){
   var dir = 0; // forward or backward
   if (event.target.dataset.clickType === "prev") { dir = -1 }
   if (event.target.dataset.clickType === "next") { dir =  1 }
   // only if there is a dir
   if (dir) {
       const epNumber = Number(event.target.dataset.episode); // convert to a number
       let elementName = `episode${epNumber}buttons`; // get element id to hide
       // hide the element
       document.getElementById(elementName).classList.add("hide"); // hide this element
       epNumber += dir; // get next or prev episode
       elementName = `episode${epNumber}buttons`; // get element id to show
       // show the element
       document.getElementById(elementName).classList.remove("hide");
   }
}

Now you can add to the HTML as many episodes as you like, and don't need to change the code saving you a lot of time, and reducing the chance of bugs creeping in due to typos just because there has been a content change.


I have some issues with your code and possible alternatives for implementation.

Usage of var

In Javascript using var instead of let or const are somewhat discouraged (in the new era of ES6). There is some value in block scope for loops using var but you can certainly always use ES6' let instead. Since you are not reassigning xmlHttp you might as well const that (same goes for x and let for url).

Use fetch instead of XMLHttpRequest

Fetch comes with a promise-ready easier API for handling requests. CanIUse reports that it's almost supported on every new Browser as well. A polyfill should be enough to support the rest of the browsers out there. It also helps in readability and simplicity.

In your case, getting HTML out of a requests is a simple as:

fetch(...)
  .then(function (response) {
    // Status 200? Type text/html? Might aswell check that here.
    return response.text();
  })
  .then(function (body) {
    // Insert into dom here...
    console.debug(body);
  })

Error handling thanks to fetch

What happens if your URL is faulty, temporarily unavailable and some other error? If you need error handling then just add a catch below then:

.catch(e){
  // Display message, console silenty
  console.debug(e);
}

Using external libraries is usually not necessary as ES6 brings the most bang for the buck anyway.


Binary search a sorted list of integers in Python 3

PEP-8

PEP-8 is a style guide for Python.
It contains several practices which you should follow, like having spaces around operators.  Use a tool, like pylint, to ensure you follow these practices.

Integer Division

mid=int((left+right)/2)

Python comes with a built-in integer division operator: //.  You should use it.

mid = (left + right) // 2

Termination

while x[mid] != y:

You are searching until you find the desired value.  What if the desired value is not present?  You will search forever???  Consider adding a different stopping condition.

Redundancy

    if x[mid]>y:
        #...
        mid=int((left+right)/2)
    if x[mid]<y:
        #...
        mid=int((left+right)/2)

Since you are looping while x[mid] != y, your only real choices are for x[mid] > y or x[mid] < y.  Instead of testing the second condition, how about using else:?

Since you enter will either the x[mid] > y then clause, or the x[mid] < y then clause, you will always be executing mid=int((left+right)/2).  You can safely move those two statements out if the if, and unconditionally execute it at the end.  As in:

    if x[mid] > y:
        #...
    else:
        #...
    mid = (left + right) // 2

Efficiency

If you start with left=0, right=99, mid=49, and find x[mid]>y is true, you proceed to search in the range left=0, right=49.  But you've already tested x[49] and found the value wasn't there; you don't need to include it in your search range anymore.  Similarly, when you find x[mid]<y, you don't need to include that mid point as the left end of your range.

    if x[mid] > y:
        right = mid - 1
    else:
        left = mid + 1

Bug

Your existing algorithm will not terminate for certain numbers.  If you search for 99, the value of mid will take on the following values:

49, 74, 86, 92, 95, 97, 98, 98, 98, 98, 98, 98, 98, 98, ...


I feel @spyr03's answer is great (+1 it), but I would like to extend it a but further in a number of ways.
Algorithm
The suggestion that you can validate the move by checking one axis moves 2, and the other moves 1, is an interesting, but not ambitious enough solution. A knight moves in a right-angled pattern, with 2 steps on one side, and 1 on the other.
Pythagoras indicates that the square on the hypoteneuse is the same as the sum of the other two squares.
Putting those together, there is a really neat trick....
public boolean isValid(int r1, int c1, int r2, int c2) {
    // use pythagoras to ensure that a move makes a right-angled
    // triangle move with sides of 1 and 2. 1-squared + 2 squared is 5.
    int deltaR = r2 - r1;
    int deltaC = c2 - c1;
    return 5 == deltaR * deltaR + deltaC * deltaC;
}

You can avoid the conditional checks on 1 or 2 steps, and you can also remove the Math.abs() calls because the square of negative numbers are always positive.
Try-With-Resources
I really like that you have used a try-with-resources to open the buffered reader (though again, @spyr03's suggestion to use a Scanner is a good one.
My special point here, though, is that one of the main reasons that try-with-resources was introduced, is to ensure the resources are always closed in a sane order.
There is no need to explicitly close the buffered reader at all... the try block is designed to do that for you.


for rev in xrange(repo[node].rev(), len(repo)):
        ctx = context.changectx(repo, rev)

In Python, I generally try to avoid iterating using xrange. I prefer to iterate over what I'm interested in.

def revisions(repo, start, end):
    for revision_number in xrange(start, end):
        yield context.changectx(repo, revision_number)

for rev in revisions(repo, repo[node].rev(), len(repo)):
    ...

Although I'm not sure its worthwhile in this case.

The only other issue is your use of abbreviations like repo and rev. They aren't that bad because its pretty clear from the context what they stand for. But I'd write them fully out.


I find your numpy code to be quite rational as far as my skills go, but your script have several things to improve on besides that.

Improvable in current scope :

Removing duplicate code thanks to a helper function
Painting the whole background to simplify
Removing (yet) unecessary line w, h, k = data.shape
Naming error, or logic error ? Background and edge color seem swapped. Changing <= level to > level
Some non-compliant and unexplicit variable names

Code showing this

# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image

def get_dist_array(data, shifted_data, level):
    distance_map = np.absolute(np.sum(data - shifted_data, axis=2))
    return np.asarray(distance_map > level, dtype="int32")

def stroke(image_path, output, level=80, edge_color=[255,255,255], blackground_color=[0,0,0]):
    img = Image.open(image_path)
    data = np.asarray(img, dtype="int32")
    level = min(max(1,level), 255)
    edges_right = get_dist_array(data, np.concatenate((data[:, 1:], data[:,-1:]), axis=1), level)
    edges_down = get_dist_array(data, np.concatenate((data[1:,:], data[-1:,:]), axis=0), level)
    data[:] = blackground_color
    edges = (edges_right+edges_down) > 1
    data[edges] = edge_color
    img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype="uint8"), "RGB")
    img.save(output)

if __name__ == "__main__":
    stroke("images/bob.png", "new_test.jpg")

Other things to consider worth improving :

Get rid of hardcoded file names. You could use argparse here
RGBA support ?


jQuery's .toggleClass() function allows you to determine the class name to be toggled by passing a function as the first argument:

$(".click").click(function() {
  $(".flipper").toggleClass(function() {
    if ($(this).is(".flipped")) {
      return "second-flip";
    } else {
      return "flipped";
    }
  });
});

Making your Javascript code cleaner and more usable. :)

$(".click").click(function() {
  $(".flipper").toggleClass(function() {
    if ($(this).is(".flipped")) {
      return "second-flip";
    } else {
      return "flipped";
    }
  });
});
.flip-container {
  height: 150px;
  width: 150px;
  perspective: 600;
  position: relative;
}
.flipper {
  height: 100%;
  width: 100%;
  position: absolute;
  transform-style: preserve-3d;
  transition: transform 1s;
}
.back,
.front {
  height: 100%;
  width: 100%;
  display: block;
  position: absolute;
  backface-visibility: hidden;
}
.front {
  background-color: red;
}
.back {
  background-color: blue;
  transform: rotateY(180deg);
}
.flipped {
  animation: spin180 1s 1 forwards;
}
.second-flip {
  animation: spin360 1s 1 forwards;
}
@keyframes spin180 {
  from {
    transform: rotateY(0deg);
  }
  to {
    transform: rotateY(180deg);
  }
}
@keyframes spin360 {
  from {
    transform: rotateY(180deg);
  }
  to {
    transform: rotateY(360deg);
  }
}

Front

Back

<button class="click">Click me</button>


Style
Standard C# naming convention for methods is PascalCase. For static and instance members there are more variants around but often they are prefixed with _ and/or area also PascalCase so they can be easily distinguished from local variables and parameters. Following standard naming conventions makes your code look more familiar to other C# developers.
Structure
It is all static methods and global variables which seriously hurts maintenance and makes testing the code real painful as you probably have already discovered (I guess you have managed with a lot of commenting in and out code).
The easiest way to simplify this is to provide an abstract base class which the various implementations can derive from an implement. You should also pass the buffer size and values to produce/consume as parameters to break dependencies on global variables.
Something along these lines:
public class ProducerConsumerBase
{
    protected char[] _Buffer;
    protected int _TotalNumberOfValues;

    protected ProducerConsumerBase(int bufferSize, int totalNumberOfValues)
    {
        _Buffer = new char[buffSize];
        _TotalNumberOfValues = totalNumberOfValues;
    }

    public abstract void ProduceAll();
    public abstract void ConsumeAll();
}

this can then be derived like this:
public class BusyWaitingProducerConsumer : ProducerConsumerBase
{
    public BusyWaitingProducerConsumer(int bufferSize, int totalNumberOfValues)
        : base(bufferSize, totalNumberOfValues)
    {
    }

    public void ProduceAll()
    {
        ...
    }

    public void ConsumeAll()
    {
        ...
    }
}

public class SemaphoreProducerConsumer : ProducerConsumerBase
{
    public SemaphoreProducerConsumer (int bufferSize, int totalNumberOfValues)
        : base(bufferSize, totalNumberOfValues)
    {
    }

    public void ProduceAll()
    {
        ...
    }

    public void ConsumeAll()
    {
        ...
    }
}

The main method of your program then would be:
static const int BuffSize = 10;
static const int ValuesToProduce = 95;

static void Main(string[] args)
{
    var producerConsumer = new BusyWaitingProducerConsumer(BuffSize, ValuesToProduce);
    Thread p = new Thread(new ThreadStart(producerConsumer.Produce));
    Thread c = new Thread(new ThreadStart(producerConsumer.Consume));
    p.Start();
    c.Start();
}

And you can easily swap out the concrete implementation you want to test with without having to change or comment out a lot of code.
Bugs
Your busy-waiting implementation is broken in that you will need to at least call Interlocked.Increment and Interlocked.Decrement on avail because ++ and -- are not atomic operations - they consist of a read, an increment/decrement and a store. For example if avail is 1 and avail++ and avail-- are executed on two different threads simultaneously then the end result could be 0, 1 or 2.


should DRY apply to unit tests as much as production code

As Cygal pointed out, keeping things DRY is a very good thing and I clearly agree with that. At the same time I did not want to just simply blame the tool for its limitations or to have to use a debugger when one really shouldn't have to be used.

So here's an alternative.

We have our own CppUnit library on top of CppUnit where we defined a whole bunch of helpers not available in the framework (things like CPPUNIT_ASSERT_IN_RANGE( min, max, value ) macro).
So I added this macro to our library:

#define CPPUNIT_CALL( expression )                                  \
    do {                                                            \
        try {                                                       \
            expression;                                             \
        } catch( ::CppUnit::Exception& e ) {                        \
            _RethrowCppUnitAssert( e, CPPUNIT_SOURCELINE() );       \
        }                                                           \
    } while ( false )

and the rethrow function is defined as:

inline void _RethrowCppUnitAssert( CPPUNIT_NS::Exception&           e,
                                   const CPPUNIT_NS::SourceLine&    outerLocation ) {
    CPPUNIT_NS::Message     msg( e.message() );
    char                    location[4096];
    sprintf_s( location, "From: %s(%d)",
               outerLocation.fileName().c_str(), outerLocation.lineNumber() );
    msg.addDetail( location );
    CPPUNIT_NS::Asserter::fail( msg, e.sourceLine() );
}

So now the actual unit test code looks like this:

...

CPPUNIT_CALL( SendNextPacket( 0, 1, 2 ) );

CPPUNIT_CALL( SendNextPacket( 1, 2, 2 ) );

...

Works like a charm and everything is DRY as it should be.  If anything inside those calls throws an assertion, that assertion will be intercepted, source file/line number of the CPPUNIT_CALL will be added to message details, and the whole thing will be rethrown.

(*) - p.s. I'm not sure what's up with do {... } while( false ) loop in there. I modeled this macro after CPPUNIT_ASSERT_NO_THROW_MESSAGE and that was in there, so I figured somebody at some point must have had a good reason.


LeetCode 952: Largest Component Size by Common Factor

Observation
I don't understand your solution.
Code Review
#define max(a, b) (a > b ? a : b) // std::max(a, b)

Don't do this. Use std::max() directly.
Long gone are the days that we used macros to inline code like this. The std::max() will work correctly in all situation this macro has edge cased that will fail (especially if a or b are not just simple numbers).

The size_t is coming because you included a C header file cstdint. It is not guaranteed to be in the global namespace (it commonly is but its not guaranteed). So prefer to use std::size_t.
        const size_t max_nums = *std::max_element(nums.begin(), nums.end());


Linkedlist visualization using html5 canvas

I'm not sure why are you using Object.create to instantiate your shape. You should know that operator instanceof only works with real javascript pseudoclasses (that is, if you even think you need pseudoclass for this), which look like this:

function Shape() {
  this.x = 0;
  this.y = 0;
  this.w = 0;
  this.h = 0;
  this.t = 0;
  this.rects = [];
}
Shape.prototype = {
  add:function(x,y,w,h,t) {
    this.x=x;
    this.y=y;
    this.w=w;
    this.h=h;
    this.t=t;
    this.rects.push({x,y,w,h,t});
  },
  draw:function(context,text) {
    for (var i in this.rects) {
      oRec = this.rects[i];
      context.fillStyle = 'red'
      context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
      context.fillText(oRec.t, oRec.x,oRec.y);
      context.beginPath();
      context.moveTo(oRec.x+oRec.w/2,oRec.y+oRec.h/2);
      context.lineTo(oRec.x+100,oRec.y+12);
      context.stroke();
      context.closePath();
      if(i==this.rects.length){
        // wtf is this exactly?
      }
    }
  }
}

There's also one very important difference, which is that in your case rects property is shared between all instances!. Here's a demonstration using your Shape. Here is the same example with my code.

Except for that, there's nothing much to say about the code. I'd be more interested how does it actually handle a linked list. Does it check for cycles? Does it show whether the list is circular or null-terminated?

Maybe just make the text black and put it one pixel up for readability. It looks better.

      context.fillStyle = 'black';
      context.fillText(oRec.t, oRec.x,oRec.y-1);


C++ class to compute similarity coefficients

I have to admit that I don't have any familiarity with this particular problem, so I can't offer any great advice on it. That said, I do see a few things in your code that I think could be improved.
Scope
One thing I would recommend is moving variables closer to the place where they are used. You're currently defining all variables at the beginning of the function, and that makes it harder to tell what might have been changed when reading the body of the function. In PearsonSimilarity() you're using aVal, bVal, and the vectors in the first for loop. The expected values are not used until the second for loop (inside an if). I would move their declarations into the else clause of the if because of this. Further, I would move each declaration to its own line. Your lines are very long and hard to read because I have to scroll to see everything on them.
In fact, it might make sense to break up the function and call 2 smaller functions - one which calculates the commonItemCounter and the arrays, and another which processes the arrays. That's up to you.
Performance
One big thing I see that could be improved is to remove all calls to pow(). In each case you are squaring the input value. pow() is a very expensive function, and it's a single instruction to just multiply a value by itself. I would first pull the value out of the array, and then use it multiple times, like this:
    for (int i = 0; i < aValues.size(); i++)
    {
        double a = aValues [ i ];
        double b = bValues [ i ];
        double ab = abValues [ i ];
        aExpectedValue += a / commonItemCounter;
        bExpectedValue += b / commonItemCounter;
        aSquaredExpectedValue += (a * a) / commonItemCounter;
        bSquaredExpectedValue += (b * b) / commonItemCounter;
        abExpectedValue += ab / commonItemCounter;
    }

Another thing that I see that is likely to be slow is that commonItemCounter is defined as an int but is used to calculate floating point values. You should declare it as a double. And then, once you have, it might make sense (measure to be sure) to invert it and multiply by it instead of dividing by it. (This might be a non-issue on modern systems, but has been an issue in the past.)
Early Returns
Early returns are helpful when you have some "early out" conditions such as the input being out-of-range or degenerate in some way. That's not the case here, and it can be confusing to follow. In this case, I'd recommend having a return value and only a single return statement at the end like this:
double result = 0.0;
if (aValues.size() > 0)
{
    for (int i = 0; i < aValues.size(); i++)
    {
        // ... rest of loop here
    }
    double denominator = sqrt(...stuff...)
    if (denominator != 0.0)
    {
        result = (abExpectedValue - (aExpectedValue * bExpectedValue)) / denominator;
    }
}
return result;

It's fewer levels of ifs (less cyclomatic complexity) and easier to understand the flow.


Your customization looks fine - that's the way it is recommended to do it.

The only note I could add is about your GetUserIdInt method which you can get rid of. You can just use this generic overload:

User.Identity.GetUserId<int>()


Separate model from DB mapper (entity manager)

The User class is doing too much. It represents a "User" and also handles the data connection and mapping. You have a need for two classes in the very least. The Repository Pattern is a common design solution for this and is quite easy to set up.
You first need to split up your concerns. You have a "User" and a "place users are stored."
The User class would be called the Domain Model. This represents a row from the "users" table and contains the data and methods that operate on that data. It does not contain data access methods. Rather, it should only contain "business logic."
From Wikipedia:

A domain model is a system of abstractions that describes select aspects of a sphere of knowledge, influence, or activity (a domain [3]). The model can then be used to solve problems related to that domain. The domain model is a representation of meaningful real-world concepts pertinent to the domain that need to be modeled in software. The concepts include the data involved in the business and rules the business uses in relation to that data.
A domain model generally uses the vocabulary of the domain so that a representation of the model can be used to communicate with non-technical stakeholders.

(emphasis, mine)
class User
{
    private $id;
    private $username;
    private $password;
    private $first_name;
    private $last_name;

    public function __construct($username, $password, $id = 0) {
        $this->setUsername($username);
        $this->setPassword($password);
        $this->setId($id);
    }

    // Getters

    // Setters

    public function getFullName() {
        if (isset($this->first_name) && isset($this->last_name)) {
            return $this->getFirstName() . ' ' . $this->getLastName();
        } else {
            return null;
        }
    }

    public function canChangePassword($oldPassword, $newPassword) {
        // Logic to check if the password can be changed
    }

    public function changePassword($oldPassword, $newPassword) {
        if (!$this->canChangePassword($oldPassword, $newPassword)) {
            throw new Exception("Cannot change password");
        }

        $this->password = $newPassword;
    }
}

Not every property needs a setter method. In fact, a User is not even a valid object unless it has a username, and password. The constructor is the perfect place to supply those values because the username shouldn't change, and the password can change, but the change in value should be tightly controlled by the User object (hence the canChangePassword and changePassword methods).
The data access code would go into a UserRepository class that specializes in CRUD operations on the "users" table. You can optionally create an interface for the repository class in case you want to unit test your application and provide a mock user repository.
interface IUserRepository
{
    public function add(User $user);
    public function findAll();
    public function find($id);
    public function findByUsername($username);
    public function update(User $user);
    public function remove(User $user);
}

The interface sets up the main operations you can perform on Users in the database. The UserRepository class below is where we actually start the data access code:
class UserRepository implements IUserRepository
{
    private $connection;

    public function __construct(PDO $connection) {
        $this->connection = $connection;
    }

    public function add(User $user) {
        // Create prepared statement for INSERT
    }

    public function findAll() {
        $results = // Query by prepared statement
        $users = [];

        foreach ($results as $data) {
            $users[] = $this->createInstance($data);
        }

        return $users;
    }

    public function find($id) {
        $data = // Query by prepared statement

        return $this->createInstance($data);
    }

    public function findByUsername($username) {
        $data = // Query by prepared statement

        return $this->createInstance($data);
    }

    public function update(User $user) {
        // Create prepared statement for UPDATE
    }

    public function remove(User $user) {
        // Create prepared statement for DELETE
    }

    private function createInstance($data) {
        return $this->map($data, new User($data['username'], $data['password'], $data['id']));
    }

    private function map($data, User $user) {
        foreach ($record as $attribute => $value) {
            $method = 'set' . ucfirst($attribute);

            if (method_exists($user, $method)) {
                call_user_func_array(array($user, $method), array($value));
            } else {
                throw new Exception("No setter method exists for '$attribute'");
            }
        }

        return $user;
    }
}

The instantiating and mapping of User objects is kept internal to the repository class. You could split this concern out into its own "mapper" or "factory" class if you wanted, but I generally start out with the mapping code right inside the repository class. Later on if I need to split out the mapping code, doing so is a simple refactoring job because these methods are private.
Now let's explore a sample use case where we change the password of a user:
// Create the "repostory" object
$users = new UserRepository($pdo);

// Fetch the user from the database
$user = $users->findByUsername('jdoe');

// Modify the User
$user->changePassword('password1', 'password2');

// Persist the changes back to the database
$users->update($user);

Clean and simple. That's the goal of splitting out your data access from your domain model. Furthermore, since your User class is devoid of data access code, you can now write unit tests validating the business logic of its methods.
Unit Testing
Earlier I mentioned that defining an interface for the repository can assist unit testing. We'll take a simple "MVC" example to illustrate this point. We have a "users controller" class that handles an HTTP request. It has two arguments in its constructor. The first argument has a Type Hint of IUserRepository and the second argument is the $_GET or $_POST array.
class UsersController
{
    private $params;
    private $users;

    public function __construct(IUserRepository $users, $params) {
        $this->users = $users;
        $this->params = $params;
    }

    public function changePassword() {
        $user = $this->users->findByUsername($this->params['username']);
        $user->changePassword($this->params['password1'], $this->params['password2']);
        $this->users->update($user);
    }
}

The changePassword method queries the repository for the user and calls the changePassword method on the User object. Lastly, it updates the user. Since the $this->users property was injected into the UsersController object in the constructor with a Type Hint, we can provide our own mock object to unit test the controller with.
class MockUserRepository implements IUserRepository
{
    private $data;

    public function __construct($existingUsers = array()) {
        $this->data = array(
            'all' => $existingUsers,
            'added' => array(),
            'updated' => array(),
            'removed' => array()
        );
    }

    public function add(User $user) {
        $this->data['added'][] = $user;
        $this->data['all'][] = $user;
    }

    public function findAll() {
        return $this->data['all'];
    }

    public function find($id) {
        // Find in $this->data['all']
    }

    public function findByUsername($username) {
        // Find in $this->data['all']
    }

    public function update(User $user) {
        $this->data['updated'][] = $user;
    }

    public function remove(User $user) {
        // remove from $this->data['all']
        $this->data['removed'][] = $user;
    }

    public function getData() {
        return $this->data;
    }
}

Now, the simple unit test:
$userToFind = new User('jdoe', 'password1', 123);
$mockUsers = new MockUserRepository(array($userToFind));
$params = array(
    'username' => 'jdoe',
    'password1' => 'password1',
    'password2' => 'abc123'
);
$controller = new UsersController($mockUsers, $params);

$controller->changePassword();

// Assert that $userToFind has a different password
// Assert that $userToFind was "updated"

Now we can unit test something more complex like a "controller" in an MVC application without requiring a connection to the database.

@PeraMika said:

I hope that it is OK to just have class User and class UserRepository without interface and or other classes that you have created here.

The interface is not a requirement. The most important thing is to separate the Domain Model from the Data Access.
@PeraMika said:

Is it good to have two classes for every table in DB, for example - if we have a table "Comments" - class Comment and class CommentRepository? Or, if we have table categories - class Category and class CategoryRepository?

The answer is two parts: "Yes" and "It depends".
If you have two tables called "comments" and "categories" you should have two Domain Models: Comment and Category. Yes, you should create one Domain Model class per table in the database.
When it comes to creating the repository classes, it depends. It's not a requirement to create one repository class per database table. If you don't have a large number of tables, one class might suffice. As your application grows, the number of tables grow. As a result, your data access code grows in size and stuffing all of it into one file can become cumbersome to maintain.
Really the decision of how many repository classes you need comes down to good object oriented design. I always approach class design with these in mind first:

Do one thing and do it well
Don't Repeat Yourself (DRY)

Do you need one repository class per table? No. If you start out doing this then you are creating a system that is easily extensible, yet doesn't make any assumptions about future business requirements. This is why I advocate for one repository class per table.
@PeraMika asked:

In methods with SQL (PDO), for example findAll()... is it good to check if the query is executed successfully, and if not - return false; For example:
if (!($stmt->execute())) {
    return false;
}

Also, in findById($id) is it good to have something like:
$record = $stmt->fetch(PDO::FETCH_ASSOC); $stmt-> closeCursor();

if (!$record) {
    return false;
}

Many Object Relation/Mapping (ORM) libraries in multiple languages and platforms seem to implement these rules:

If multiple records can be returned, but the query does not return results, an empty array or "collection" is returned. This helps prevents null pointer exceptions in later code

If a single record should be returned, for instance querying by primary key, and the query does not return results, return null instead and let the calling code decide if this is an "exceptional" condition (and then throw an exception).

If a single record should be returned and multiple records are found, throw an exception. You are expecting something to be unique and it is not. Your repository cannot resolve this situation, so failing early and failing loudly is the best option.

If the execute method returns false because of a failure in the database or problem with the SQL, this is an "exceptional" condition. It is appropriate to throw an exception in this scenario with the message being the error message sent back from the database.


Here's my 2 cents as Java "developer" with a little experience in c# and vba.

Your security here largely depends on whether you send the password and username in clear text or encrypted. You should force HTTPS protocol for access to the page.

You might also want to show errors if the login is invalid:

$valid = true;
if(!isset($_POST['username']) || empty($_POST['username'])){
   $errors .= "Please enter a username.
"
   $valid = false;
}
if(!isset($_POST['password']) || empty($_POST['password'])){
   $errors .= "Please enter a pasword.
"
   $valid = false;
}
if($valid){
  //check for username and password compliance
}

Also it would definitely be better to have the logout be handled in a different file than the login


Converting words/numbers to Discord "letter/number emojis"

Disclaimer: I know nothing about these "Discord letters"

Code organisation

You could reorganise your code to make units easier to use independently.

The easiest thing to do it to re-write the discord function so that it returns a value instead of updating a global variable.

Another thing to do is to put all the Tkinter logic into a function. Usually, that function actually doing things would be put behind an if __name__ == "__main__" guard.

We'd have

# the function to convert a String to "Discord Letters"
def convert_to_discord_letters(word):
    # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox
    result = []
    # List of numbers from 0-9 , is used to check the string for numbers and then convert them
    # to "Discord Digits" since they have a different syntax in discord than Letters
    chars = set('0123456789')
    s = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
         'w', 'x', 'y', 'z'}
    # In case the User enters spaces they get removed since they just cause trouble
    word = word.replace(" ", "")
    word = word.lower()
    w = word
    for i in range(len(w)):
        # checks if the string has a number and outputs accordingly
        if any((c in chars) for c in w[i]):
            list_one = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]
            result.append(':' + list_one[int(w[i])] + ":" + " ")
        # checks if the string has letter and outputs accordingly (might be unnecessary)
        elif any((c in s) for c in w[i]):
            result.append(':regional_indicator_' + w[i] + ":" + " ")
        else:
            # In case the user inputs something wrong
            print("False Input")
    # print(result)
    return result

# defines the funtion click which gets called when the submitButton1 is pressed
def click():
    # saves the text which is entered in the textentry box, this later gets converted to "Discord Letters"
    entered_text=textentry.get()
    # deletes the output box in case the user presses the button again to convert something new
    output.delete(1.0, END)
    # the function to convert a String to "Discord Letters"
    result = convert_to_discord_letters(entered_text)
    # loop which gets the length of the string typed in the textentry box and then outputs it to the output textbox
    for i in range(len(entered_text)):
        output.insert(END, result[i])

def tkinter_discord_letter_converter():
    root = Tk()
    root.title("Discord Letter Converter")
    # TextInput
    textentry = Entry(root, width=20, bg="white")
    textentry.pack()
    # submitButton
    submitButton1 = Button(root, text="Submit", width=6, command=click)#
    submitButton1.pack()
    # TextOutput
    output = Text(root, width=75, height=6, wrap=WORD, background="white")
    output.pack()
    root.mainloop()

if __name__ == '__main__':
    tkinter_discord_letter_converter()

Note: I do not have tested this because I do not have Tkinter but I've tested parts of your code because I have...

Unit Tests

Now that the code is reorganised, we can easily write small tests for the discord function that I've renamed test_convert_to_discord_letters

def test_convert_to_discord_letters():
    """Test function convert_to_discord_letters."""
    # TODO: This could/should use a proper unit-test framework
    # Empty case
    assert convert_to_discord_letters("") == []
    # Whitespace
    assert convert_to_discord_letters(" ") == []
    # Special characters
    assert convert_to_discord_letters("#~&$£()[]") == []
    # Lowercase letters
    assert convert_to_discord_letters("abcz") == [':regional_indicator_a: ', ':regional_indicator_b: ', ':regional_indicator_c: ', ':regional_indicator_z: ']
    # Uppercase letters
    assert convert_to_discord_letters("ABCZ") == [':regional_indicator_a: ', ':regional_indicator_b: ', ':regional_indicator_c: ', ':regional_indicator_z: ']
    # Digits
    assert convert_to_discord_letters("42") == [':four: ', ':two: ']
    # Mix
    assert convert_to_discord_letters("Bar -_- 9") == [':regional_indicator_b: ', ':regional_indicator_a: ', ':regional_indicator_r: ', ':nine: ']

Improving test_convert_to_discord_letters

Now that we have unit-tests for the function, we can more safely try to improve it without breaking its behavior.

Loop like a native

I highly recommend Ned Batchelder's talk "Loop like a native" about iterators. One of the most simple take away is that whenever you're doing range(len(iterabme)), you can probably do things in a better way: more concise, clearer and more efficient.

In your case, this gives:

    for char in w:
        # checks if the string has a number and outputs accordingly
        if any((c in chars) for c in char):
            list_one = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]
            result.append(':' + list_one[int(char)] + ":" + " ")
        # checks if the string has letter and outputs accordingly (might be unnecessary)
        elif any((c in s) for c in char):
            result.append(':regional_indicator_' + char + ":" + " ")
        else:
            # In case the user inputs something wrong
            pass # print("False Input")

Then, a few things seem more obvious:

we don't really need the w variable. Also, various re-assignment of word are not required
the variations of any((c in XXX) for c in char) look weird once we realise that char is a single character. We could write this: if char in XXX
the variable chars would be better named digits while s would be better named letters

At this stage, we have

# the function to convert a String to "Discord Letters"
def convert_to_discord_letters(word):
    # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox
    # List of numbers from 0-9 , is used to check the string for numbers and then convert them
    # to "Discord Digits" since they have a different syntax in discord than Letters
    digits = set('0123456789')
    letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
    result = []
    for char in word.replace(" ", "").lower():
        # checks if the string has a number and outputs accordingly
        if char in digits:
            list_one = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]
            result.append(':' + list_one[int(char)] + ":" + " ")
        # checks if the string has letter and outputs accordingly (might be unnecessary)
        elif char in letters:
            result.append(':regional_indicator_' + char + ":" + " ")
        else:
            # In case the user inputs something wrong
            pass # print("False Input")
    # print(result)
    return result

Definitions of data used

For letters, you could use ascii_lowercase from string module:

import string
...
    letters = set(string.ascii_lowercase)

For digits, you define a set and a list, convert the value to integer to get the string at the relevant index. It seems like the best data structure to use would be a single dictionnary mapping digits to strings.

    digits = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"}

Useless concatenations of literal string

":" + " " can be written ": ".

At this stage, we have:

# the function to convert a String to "Discord Letters"
def convert_to_discord_letters(word):
    # A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox
    # List of numbers from 0-9 , is used to check the string for numbers and then convert them
    # to "Discord Digits" since they have a different syntax in discord than Letters
    digits = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"}
    letters = set(string.ascii_lowercase)
    result = []
    for char in word.replace(" ", "").lower():
        # checks if the string has a number and outputs accordingly
        if char in digits:
            result.append(':' + digits[char] + ": ")
        # checks if the string has letter and outputs accordingly (might be unnecessary)
        elif char in letters:
            result.append(':regional_indicator_' + char + ": ")
        else:
            # In case the user inputs something wrong
            pass # print("False Input")
    print(result)
    return result

And we realise that most comments are not required anymore because the code is much clearer. On the other hand, we could add a proper docstring.

def convert_to_discord_letters(word):
    """Convert a string into a list of strings corresponding to "Discord Letters"."""
    digits = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"}
    letters = set(string.ascii_lowercase)
    result = []
    for char in word.replace(" ", "").lower():
        if char in digits:
            result.append(':' + digits[char] + ": ")
        elif char in letters:
            result.append(':regional_indicator_' + char + ": ")
        else:
            pass # TODO: I'll let you decide how to handle other cases
    return result

Removing the useless logic

It is now clearer that the .replace(" ", "") logic removes whitespace which would have no effect anyway (as we'd end up in the non-handled case).
You can remove this.

More

I suspect the click function could benefit from the same ideas but it can't test it at the moment.

Also, the code seems to assume that entered_text and result will have the same length which may not be the case for non-handled characters.


Bash script for an ABC organization fulfilling the following requirements

Better comments
You have put a comment on almost every line that just restates what the code already says and does not add any information or clarification.
This is a bad practice!
A comment that states "this is an if statement" makes the code less readable, by doubling the length of a line with no added value.
When adding a comment, you should only do so if it provides information that is not in the code, or is difficult to extract from the code given average knowledge of the programing language.
Input validation
It is customary to check all user input before using it in your code.
Unless you have been explicitly instructed to assume that the input is valid, you should add some code, for example to make sure age is actually a number.
Also, you may want to check for cases where age >= 60 i.e. the employee is about to retire, or has retired already.
Better flow control
The long if elif else tree where you calculate the bonus should be replace with a case statement.
This will make the code shorter, more readable, and make adding or removing bonus options easier.
Also, store bonus multiplier in a variable to avoid repeating code:
case $designation in
    "Higher-Management")
        hour_bonus=1000
        ;;

    "Lower-management")
        hour_bonus=800
        ;;

    "Other staff")
        hour_bonus=500
        ;;

     *)
        hour_bonus=0
        ;;
esac

bonus=$((hours * hour_bonus))

Note, that you could also add shopt -s nocasematch before the case block to make the comparison case insensitive, so that if your user forgets to type capital letters (or forgets the caps lock on) your code can still match the designation to the proper bonus value.


shopify get jquery code more readable, usable

Use const & let instead of vars
Create Docblock for functions
Arrow functions ES6


Using Task.Wait() for waiting while task is finished (even if it already finished)

You can use a CancellationToken and Task.WaitAll(...) to do this...

public class A
{
    private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
    private Task task1;
    private Task task2;

    public void Connect()
    {
        task1 = Task.Factory.StartNew(SomeWork, tokenSource.Token);
        task2 = Task.Factory.StartNew(SomeWork, tokenSource.Token);
    }

    public void Disconnect()
    {
        tokenSource.Cancel();
        Task.WaitAll(task1,task2);
    }

    public void SomeWork(object o)
    {
        CancellationToken token = (CancellationToken)o;
        while (!token.IsCancellationRequested)
        {
            Console.WriteLine("working...");
        }
    }
}

For more information on managed threads check this and this article on MSDN. Enjoy :D


Fastest way to find if N numbers are even or odd

Given that 99.9% of time is spent in scanf, cout and waiting for user input then there isn't much you can do about performance (but see notes).

What it may be improved is readability of your code. First of all your're mixing C style I/O (scanf) with C++ I/O (std::cout). Let's move to C++ std::cin.

Do not ever add using namespace std; (Why is “using namespace std” considered bad practice?)

In C++ there is no need to declare all variables at the top of your method.

I think ternary operator ?: is usually used for its result, not for side-effects of called code (here you're ignoring returned values). At first this usage is confusing for caller.

If you have a loop I think for is more clear (in intent) than while. Do not worry about extra variable, compiler will optimize it for you.

int main()
{
    int numbersToRead;
    std::cin >> numbersToRead;

    for (int i=0; i < numbersToRead; ++i)
    {
       int number;
       std::cin >> number;

       bool isEven = (number & 1) == 0;
       std::cout << (isEven  ? "Yes" : "No") << std::endl;
    }

    return 0;
}

This example is pretty small but for more complex code you may want to extract some functions:

int main()
{
    for (int i=readNumberOfValuesToRead(); i > 0; --i)
       std::cout << (isEven(readValue()) ? "No" : "Yes") << std::endl;

    return 0;
}

If you're already using Boost you may use boost::irange (let me also show that you may/should move formatting to a proper manipulator (for simplicity in this example I use standard one which prints true/false instead of Yes/No):

int main()
{
    std::cout << std::boolalpha;
    for (auto i : boost::irange(0, readNumberOfValuesToRead()))
       std::cout << isEven(readValue()) << std::endl;

    return 0;
}

I'd stop here (but read notes) for this code however if your scenario is (or it will be) more complex you will probably need to introduce more classes: ValuesReader base class (with a StandardInputValuesReader concrete class) to read values from an input stream and ValuesWriter (same...) to write output somewhere (using a ValueProcessor or ValueConverter and a custom stream manipulator?) Also remember that proper classes will make your life incredibly more easy during testing (because an abstract base class can be easily mocked while to read from std::cin you need much more code in your tests - and they can't be well-tested in isolation.)

EDIT

Few notes:

As Snowhawk04 noted I/O synchronization (between C and C++ functions) may slow down execution (or it may even not).
(number & 1) == 0 and (number % 2) == 0 seem to have the same performance (and generated assembly output), at least on GCC. Pick the one you feel more comfortable with.
Flushing output buffer (because of newline) may make it slower (but again consider that you're waiting user input). A different approach may help (concatenate results into std::string or std::stringstream and then write just once to std::cout). It's not a good approach if your application is interactive but it may be viable if it's intended to be used from command line with I/O redirection.

Just a proof of concept:

int main()
{
    std::ostringstream output;
    output << std::boolalpha;
    for (int i : boost::irange(0, readNumberOfValuesToRead(), 0))
        output << isEven(readValue()) << std::endl;

    std::cout << output.str();

    return 0;
}

Someone noted '\n' instead of std::endl will prevent flushing. '\n' has some performance benefits but you won't have a single flush because we're also reading from std::cin. The use of std::stringstream is the way to avoid flushing. Note that it is implementation dependent if this useless flush() will impact performance or not for std::cout (when std::cout.sync_with_stdio(false) is called.) In general I'd suggest to use it (measure...) but still stay on std::stringstream if you want to avoid multiple flushes (not for interactive use.)
I am just half joking but for a non-interactive use if you really need to squeeze maximum performance from this program then you may want to write it in C (in practice dropping C++ I/O and strings...)


:

Don't.

People read code downwards much better than they read across.
Almost all code everywhere operates under the convention "(at most) 1 statement/operation per line". Colons : are small and very easily missed. Just stick subsequent operations on newlines and you'll avoid a lot of confusion/errors down the line.

Call is fully deprecated

It's not needed anymore and your code will run just fine without it. Assuming you name your methods well, dropping Call will also means your code reads better.

You will need to modify your calling syntax slightly though. When you have a DoThing Sub, this is valid syntax:

Call DoThing(Arg1, Arg2)

But this is not:

DoThing(Arg1, Arg2)

Functions get brackets. Subs do not. Like so:

Var = Function(Arg1, Arg2)
DoThing Arg1, Arg2

Don't let renaming break your code

Call Modul1.AutoFill(target)

Sheets("SourceSheet").Range("B" & itemCell.row & ":G" & itemCell.row)

If that module gets renamed, or that sheet gets renamed, your code will break.

Fortunately there are easy solutions.

1: Don't qualify your module references

You shouldn't need to specify which module your subs are in. If you do, this implies wider problems with your code. If your methods are descriptively named and you don't do something horrible like having 2 identically-named methods in different modules, just call your method using its signature.

2: Sheets have Codenames

If you go to the properties window and select a Worksheet, there will be a (name) property. This is the sheet's Codename. By default, new sheets have codenames like Sheet1, Sheet2 etc. A Codename is effectively a global worksheet variable that always refers to that sheet.

So, assuming you give "SourceSheet" a Codename of sourceSheet then your code can simply be:

sourceSheet.Range("B" & itemCell.row & ":G" & itemCell.row)

And now your users can name the sheets whatever they like and your code will still run fine.

Be Explicit with your naming

Your method names are OK, but very, very ambiguous. AutoFill, GrabStoredData, FillRowWith, they all imply a level of generality that is at odds with what they actually do.

As a rule, names should be descriptive, then unambiguous and only then concise. Easy-To-Understand trumps Shorter-Name every time.

GrabStoredData(itemName). Not a clue what that does in particular.

GetRowRangeOfItemData(itemName). I immediately know exactly what that does. It's going to return a Range Object for a given item. This Range Object will be on a single row.

AutoFill(Cell). Fill What? Where? With what?

FillItemDetailsToRightOfCell(Cell). Takes about 0.2 seconds longer to read. Takes much less time to understand. Especially when someone else (or you in 6 months time) is coming back to this code with no memory of the internal workings.

FillRowWith(Range, Cell). If I see that I'm going to assume it, well, fills a row. No Idea what those variables are, particularly.

PasteRangeToRightOfCell(Range, Cell). Again, takes a fraction of a second longer to read, takes no time to understand exactly what's going on.


Print every line of file, last to first, with recursion

As I get started I just want to mention that you have two unused imports:

import java.io.FileInputStream;
import java.io.InputStream;

Now I'll address your questions:

  What are the differences between these two?

Virtually nothing other than the obvious:

Method #1 depends on a counter parameter to decide whether or not the line should be printed whereas the method #2 does not. This makes method #1 a little awkward to read, but anyone who understands recursion (which is any good programmer) should catch on to what you're doing. Having the counter could use slightly more memory but it's unlikely something this small would have any impact on overall performance and it's generally not worthwhile to optimize something like this unless you have measured your program's performance and determined there is a trouble spot.

Method #2 depends on calling the closeScanner method twice, and invoking a method may carry a bit of overhead cost. However you really don't need to concern yourself with this unless you have measured the performance of your code and find that there is a problem. (See the answer to this question)

  Is one better than the other?

Again, the two are so similar there isn't really an objective way to say with certainty which is "better". If I had to select one I would probably prefer method #2 as I think it would more straightforward for someone else to use. It doesn't require knowledge of recursion or passing a counter initialized to the correct value.

  How can I make this code better?

In general comment your code so that others recognize its intended purpose and expected inputs and outputs. Javadoc is a good way to do this. Something else you can do is modify your method(s) to return something (e.g. String) rather than printing to System.out so that you can write automated tests against them more easily.

Method #1:

else if (count % 2 == 0) { does not need to have the else since you would have returned from the method if there is no next line.

When you call this method you don't need a counter reference in main, so instead just directly pass the value of count like this:

recursiveCountEveryOtherLine(0, scan);

Method #2:

Replace this line: String tempGarbage = scan.nextLine();
with this: scan.nextLine(); as you have no reason to keep a reference to the lines you aren't going to print.

Inside of the closeScanner method you have:

else {
    return false;
}

you can simply write return false without the else since you would have returned true earlier if there is no next line.


Welcome!

Your first two lines are nice comments. Consider putting them in a module docstring:

"""Performs Linear Regression (from scratch) using randomized data.

Optimizes weights by using Gradient Descent Algorithm.
"""

Consider adding random noise to something linear (or to some "wrong model" sine or polynomial), rather than to a constant.

np.random.seed(0)

Nice - reproducibility is Good.

trainingSize = 10 ** 1
trainingSteps = 10 ** 3
learningRate = 10 ** -2

These expressions are correct and clear. But why evaluate a FP expression when you could just write it as a literal? 1e1, 1e3, 1e-2. (This answer would apply in many languages, including Python. And yes, I actually prefer seeing the two integers written as floating point, even if that forces me to call int() on them.)

PEP8 asks that you spell it training_size, and so on. Please run flake8, and follow its advice.

Your column names expression is fine. Consider handling the one-origin within the format expression:

col_names = [f'feature{i + 1}' for i in range(features)] + ['labels']

Specifying axis=1 is correct. I have a (weak) preference for explicitly spelling out: axis='columns'.

Consider hoisting the expression np.matmul(X, thetas) - y, so it is only evaluated once.

The three lambda expressions are fine, but they don't seem to buy you anything. Probably better to use def three times.

Ship it! But do consider noising a linear function, to make it easier to evaluate your results.


Security

First of, your code looks pretty good, especially from a security point of view. You use prepared statements, and you use them correctly, and you use bcrypt instead of some weaker hashing algorithm such as md5 or sha.

There are a couple of things which might cause problems under certain conditions, and as defense in depth it might be a good idea to include them:

always die after a redirect, because the redirect does not necessarily stop execution of the PHP script (you can easily test this yourself: header('Location: index.html'); echo "secret"; using curl: curl localhost/redirect.php would give you secret, because curl doesn't follow redirects by default).
you have new mysqli ([credentials]) in at least two places. This is not only bad because duplication makes code harder to read and maintain, with credentials it is especially bad because it makes it harder to remember to hide them (when posting code somewhere else, submitting it in version control, etc). It also makes it harder to move those PHP files that do contain credentials outside the web root. Just put the database connection in one file (located outside the web root) and wrap it in a getConnection function (this also makes it possible to use the same database connection for all queries, which improves performance).
with current default PHP.ini settings, this is less important, but it is still always a good idea to regenerate the session id when the state of the session changes (eg when logging in) to prevent session fixation.
as @sjonniesjon said, don't echo actual error messages to the user. It can directly enable some attacks such SQL injections into some keywords (such as insert, update, order by, etc) which only display data in error messages, and it can help an attacker identify vulnerabilities.

Misc

your indentation is sometimes off, leading to harder to read code. Your brackets are also placed inconsistently.
you also have too many newlines in some places.


Hierarchical data structure using classes

YOU ARE IN A MAZE OF TWISTY LITTLE CLASSES, ALL ALIKE

So when seeing a bunch of classes that are all very similar, I start to think Metaclass!  So let's give that a whirl.

Below I will discuss a refactor of your implementation using a metaclass.  The metaclass will allow us to implement the parent/child relationships generically, but then also gives us ready access to the same infrastructure using names which are not parent/child

What are metaclasses?

Metaclasses are classes that create classes.  This in the same relationship wherein classes are used to create objects.  Take for instance this class declaration:

# Static class declaration
class AClass(int):

    a_class_attribute = 'twisty'

The above can be equivalently declared by calling type directly as:

# Dynamic (meta) declaration
AClass = type('AClass', (int,), {'a_class_attribute': 'twisty'}).

And in this case type is the metaclass of AClass, since it is called to make a class.

I won't go any farther in this explanation because it can go on for a while, and there are lot's of resources to read on this topic.

Removing Common Code

So the data structure under discussion consists of 4 classes that are hierarchical as

class Module: a container for instances of:
class Submodule: a container for instances of:
class Ability: a container for instances of:
class Template:

The code then consists of various boiler plate for the management of the tree.  Let's refactor the various boilerplate into a metaclass, and a base class, to remove the common code.

Metaclass as a class

Our metaclass inherits from type and has the same signature:

class ModuleMetaClass(type):

    def __init__(cls, name, bases, attrs):

This __init__ method will be called every time we declare one of our classes.  In this __init__, we do the bookkeeping necessary to relate the classes to one another.  Basic idea is that we will declare our classes in the order they appear in the hierarchy.  Thus the first declaration will be for Module, and the second for Submodule, etc.  Then in the ModuleMetaClass.__init__ we can relate the classes to each other as parent/child.

__init__ starts with:

if cls._metaclass_instances is None:
    # First instance is ModuleBaseClass
    cls._parent_class = None
    cls._metaclass_instances = [type(None)]

here, we initialize the list of classes that will be instantiated, and note that this class being at the top of the tree has no parent. Continuing...

else:
    # parent class is the previously declared class
    cls._parent_class = cls._metaclass_instances[-1]

    # if not at the top of the tree, then we are our parent's child
    if cls._parent_class != type(None):
        cls._parent_class._child_class = cls

    # store this class in the list of classes
    cls._metaclass_instances.append(cls)

will note that our parent class is at the end of the class list (ie: last added), then if we have a parent, register us as his child, and then add ourselves to the end of the class list.

And that is basically it for the metaclass.  There is a bit more bookkeeping, but see the full listing at the bottom of the post for that.

A Base Class to manage the tree relationships

The first instance of our metaclass (ModuleMetaClass) will be a base class for each of the node types. Class starts with:

class ModuleBaseClass(metaclass=ModuleMetaClass):
    """ Base class for each of the derived classes in our tree """

This indicates that our class will be built by instantiating a ModuleMetaClass.  ModuleBaseClass.__init__() contains the boilerplate from the original data structure and the meta bits to allow our named attributes.  The fun bits start with:

# child class variable plural is used to add a common name
plural = getattr(self._child_class, '_plural')
if plural is not None:
    setattr(self, plural, self._children)

This code uses the information stored in the class hierarchy from the metaclass to add an access attribute to this node's children.  Similarly:

# add an access attribute for each of the nodes above us in the tree
while parent is not None:
    setattr(self, type(parent).__name__.lower(), parent)
    parent = parent._parent

adds an access attribute to our parent node, and his parent and... all the way to the top of the tree.  The original implementation only had an accessor for the immediate parent.

Declaring our classes

So the remaining code contains the operative elements of the classes themselves, with all of the common boilerplate removed to ModuleBaseClass and ModuleMetaClass.

class Module(ModuleBaseClass):
    def __init__(self, name, lang):
        super().__init__(name, None)
        assert lang in ['fr', 'en']
        self.lang = lang

class Submodule(ModuleBaseClass):
    _plural = 'submodules'

class Ability(ModuleBaseClass):
    _plural = 'abilities'

class Template(ModuleBaseClass):
    _plural = 'templates'

    def __init__(self, name, ability):
        super().__init__(name, ability)
        self.lang = module.lang

Note the last line where Template was able to reach all the way up to Module.lang to retrieve the language.

Full Code Listing

class ModuleMetaClass(type):
    """ Metaclass that is instantiated once for each class """
    _metaclass_instances = None

    def __init__(cls, name, bases, attrs):

        if cls._metaclass_instances is None:
            # First instance is ModuleBaseClass
            cls._parent_class = None
            cls._metaclass_instances = [type(None)]
        else:
            # parent class is the previously declared class
            cls._parent_class = cls._metaclass_instances[-1]

            # if not at the top of the tree, then we are our parent's child
            if cls._parent_class != type(None):
                cls._parent_class._child_class = cls

            # store this class in the list of classes
            cls._metaclass_instances.append(cls)

        # no child class yet
        cls._child_class = None

        # call our base (meta) class init
        super().__init__(name, bases, attrs)

class ModuleBaseClass(metaclass=ModuleMetaClass):
    """ Base class for each of the derived classes in our tree """

    def __init__(self, name, parent):
        assert isinstance(parent, self._parent_class)
        self.name = name
        self._parent = parent

        if self._child_class is not None:
            self._children = {}

            # child class variable plural is used to add a common name
            plural = getattr(self._child_class, '_plural')
            if plural is not None:
                setattr(self, plural, self._children)

        # add self to our parents collection
        if parent is not None:
            parent._add_child(self)

        # add an access attribute for each of the nodes above us in the tree
        while parent is not None:
            setattr(self, type(parent).__name__.lower(), parent)
            parent = parent._parent

    def _add_child(self, child):
        assert isinstance(child, self._child_class)
        assert child.name not in self._children
        self._children[child.name] = child

# --------------------------------

class Module(ModuleBaseClass):
    def __init__(self, name, lang):
        super().__init__(name, None)
        assert lang in ['fr', 'en']
        self.lang = lang

class Submodule(ModuleBaseClass):
    _plural = 'submodules'

class Ability(ModuleBaseClass):
    _plural = 'abilities'

class Template(ModuleBaseClass):
    _plural = 'templates'

    def __init__(self, name, ability):
        super().__init__(name, ability)
        self.lang = module.lang

# --------------------------------

module = Module('module1', 'fr')
sub_module1 = Submodule('sub_module1', module)
sub_module2 = Submodule('sub_module2', module)
ability = Ability('ability1', sub_module1)
template = Template('template1', ability)
print(template.lang)


Since you only use one function from both re and os, you could just import the specific function from each rather than the whole module.

from os import chdir
from re import sub

You shouldn't use a bare try except. You might be ignoring all sorts of errors without noticing. Instead, use the exception that you're expecting is likely to happen. According to this Stack Overflow answer urlretrieve will likely raise a URLError (which you also need to get with import URLError from urllib2). This way if you're having other problems you'll actually know about it.

try:
    urllib.request.urlretrieve(pic_url, pic_url.split('/')[-1])
except URLError:
    print("Image not found.")

Also it seems silly to have that message print out without indicating which images weren't found. You may be incorrectly parsing a lot of images without realising it. Just adding (pic_url.split('/')[-1] + " Image not found") would make it a much more useful error message. But it would be even more helpful if you logged the full path (pic_url).


method to get finger mask based on finger position

Yes, this can be done simply by using a power of 2.

private int getFingerMask(int fingerPosition)
{
    if (fingerPosition >= 0 && fingerPosition < 10)
    {
        return (int)Math.Pow(2, fingerPosition);
    }
    else
    {
        return 0;
    }
}


Communicating between GUI and controller class using Mediator pattern

Since you only support a limited subset of messages you might want to consider using an enum to represent the different kinds of messages.

I think you're building yourself a god-class though. Instead of having everything running through the MidiController (which makes the Mediator Pattern basically useless) you could just as well couple GUI and Controller directly.

Interestingly that's the more often used approach, to have the Controller take the role described as Mediator in the link you provided. This is especially interesting because it is not guaranteed that you have similar "suppliers of information" for your GUI.

I think the Mediator Pattern overall is the wrong pattern for your situation :/


Using Python to create a JSON file of recipes from MySQL

Preface

For this review, we shall need to refer to the database schema for the WordPress Simmer plugin:

if ( $items_table_name != $wpdb->get_var( "SHOW TABLES LIKE '$items_table_name'" ) ) {
        // The recipe items table.
        $query .= "CREATE TABLE $items_table_name (
               recipe_item_id bigint(20) NOT NULL auto_increment,
               recipe_item_type varchar(200) NOT NULL DEFAULT '',
               recipe_id bigint(20) NOT NULL,
               recipe_item_order int(11) NOT NULL DEFAULT '0',
               PRIMARY KEY  (recipe_item_id),
               KEY recipe_id (recipe_id)
               ) $charset_collate;";
}

if ( $item_meta_table_name != $wpdb->get_var( "SHOW TABLES LIKE '$item_meta_table_name'" ) ) {

        // The recipe item meta table.
        $query .= "CREATE TABLE $item_meta_table_name (
               meta_id bigint(20) NOT NULL auto_increment,
               recipe_item_id bigint(20) NOT NULL,
               meta_key varchar(255) NULL,
               meta_value longtext NULL,
               PRIMARY KEY  (meta_id),
               KEY recipe_item_id (recipe_item_id),
               KEY meta_key (meta_key)
               ) $charset_collate;";
}

Querying

To start, let's format your first query for readability:

query = """
    SELECT a.recipe_id, a.recipe_item_type
         , b.meta_key, b.meta_value, b.recipe_item_id
        FROM wp_simmer_recipe_items a, wp_simmer_recipe_itemmeta b
        WHERE a.recipe_item_id = b.recipe_item_id
        GROUP BY a.recipe_item_id
"""

Your query has a non-sensical GROUP BY clause.  The only way that this query could be legal is if the schema and query are formulated so as to guarantee that each recipe_item_id only appears at most once in the query result.  While the wp_simmer_recipe_items table does have a PRIMARY KEY (recipe_item_id) constraint, there is no such uniqueness guarantee in the wp_simmer_recipe_itemmeta table.  MySQL < 5.7.5 somehow executes the query despite the fact that it makes no sense; in MySQL ≥ 5.7.5, it should fail with an error, as it should in any sane SQL implementation:

  ERROR 1055 (42000): Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'somedb.b.meta_key' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Based on the query results, you build the ingredients and instructions lists by appending entries.  However, you fail to ORDER BY recipe_item_order, so the ingredients and instructions may appear in any order.  (Try baking the bread before mixing the dough!)

When joining tables, write the query using JOIN. It's more readable than implicitly joining tables using the WHERE clause.

The worst sin in this code is executing query1 for each recipe found by query.  This is a bad idea for two reasons:

For good performance, you should never execute queries in a loop, especially when the number of secondary queries depends on the length of the results of the primary query.  Each additional query necessitates a round trip to the server, and takes time to interpret and execute.
The information returned by query1 is entirely redundant — all of the information you need from it (namely, the meta_key and meta_value for each recipe_item_id) is already contained within the results of query!

Furthermore, you don't need to make two connections to the same database.  All you need is two cursors, which can be created from just one connection.

Suggested solution

Execute two queries: one to get the instructions, one to get the ingredients. (Here, I've taken a shortcut and assumed that every recipe will have at least one instruction and at least one ingredient.)

Take advantage of itertools.groupby() to help construct the inner lists and dictionaries.

from itertools import groupby
import json
from operator import itemgetter
import mysql.connector

cnx = mysql.connector.connect(
    database='somedb', user='root', password='root', host='localhost'
)
cursor = cnx.cursor()
data = {}

cursor.execute("""
    SELECT item.recipe_id
         , meta.meta_value AS instruction_text
        FROM wp_simmer_recipe_items item
            INNER JOIN wp_simmer_recipe_itemmeta meta
                ON item.recipe_item_id = meta.recipe_item_id
        WHERE
            item.recipe_item_type = 'instruction'
            AND meta.meta_key <> 'is_heading'
        ORDER BY item.recipe_id, item.recipe_item_order
""")
for recipe_id, instructions in groupby(cursor.fetchall(), itemgetter(0)):
    data[recipe_id] = {
        'instructions': [row[1] for row in instructions],
        'ingredients': [],
    }

cursor.execute("""
    SELECT item.recipe_id
         , meta.recipe_item_id
         , meta.meta_key
         , meta.meta_value
        FROM wp_simmer_recipe_items item
            INNER JOIN wp_simmer_recipe_itemmeta meta
                ON item.recipe_item_id = meta.recipe_item_id
        WHERE
            item.recipe_item_type <> 'instruction'
        ORDER BY item.recipe_id, item.recipe_item_order, meta.meta_key
""")
for (recipe_id, item_id), item in groupby(cursor.fetchall(), itemgetter(0, 1)):
    data[recipe_id]['ingredients'].append({row[2]: row[3] for row in item})

cursor.close()
cnx.close()

with open('data.json', 'w') as outfile:
    json.dump(data, outfile, sort_keys=True, indent=4)

Further discussion

MySQL, since version 5.7.22, has JSON support.  It would be nice to rewrite the SQL such that the entire JSON result could be returned from just a single query.  Unfortunately, the JSON_ARRAYAGG() function does not let you specify the order of its results:

  JSON_ARRAYAGG(col_or_expr)

  Aggregates a result set as a single JSON array whose elements consist of the rows. The order of elements in this array is undefined.

That, to me, would be a deal-breaker for exporting a recipe.


Why do you use logger.severe(...) in your MalformedURLException, but in your IOException you use e.printStackTrace()? Pick one and stick with it; this can include, for example, totally removing the printStackTrace() and replacing it with a comment that explains that you don't need to log it because [reason]. However, I'd suggest logging everything. It's a lot easier to find bugs if you log everything.

try (InputStream inputStream = packURL.openConnection().getInputStream()) {

And when you get a MalformedURLException in the try/catch before, your user is going to receive a very confusing NullPointerException instead of a more palatable (possibly custom) exception that means something in context. You can always catch (NullPointerException e) { throw /*your exception here*/; } to 'change' the exception being thrown (though be sure to use better indenting)

You define packURL right before you use it, but you define hash way at the beginning. Be consistent -- move String hash = "none"; to the line just before the relevant try.

Why is the default hash "none"? Wouldn't an empty string make more sense?

Aside from that, though, it looks about as good as it'll get. The multiple separate try/catch blocks are messy, but as far as I can tell that's the best way to do it.


Python - ternary operator or if statement?

get() takes an optional second parameter, for a value to use if the key isn't present:

token = map.get(token_str, Course(token_str))

I think that one is clearly the best solution, unless you don't want to create and immediately throw away a Course object. In that case, I would use 'or':

token = map.get(token_str) or Course(token_str)

Both of these are only one line, that one line is quite readable, and there is no unnecessary repetition.

There is one third possible situation, in which you don't want to unnecessarily construct a Course instance, and you also can't rely on the values that are present to evaluate as True. Then 'or' wouldn't work correctly.

Then I would use an 'if' statement:

token = map.get(token_str)
if token is None:
    token = Course(token_str)

but that's personal preference. Something using 'in' is also fine:

token = map[token_str] if token_str in map else Course(token_str)

although of course that looks up token_str in map twice, so if you need to be really time efficient then don't do that.


javascript for controllers of multiple audio tags

This is good code for a new coder.

Some observations:

I am not sure why you add a pause button through JavaScript, you could have this button declared simply in the HTML.
doAudios -> misnomer, since it deals with 1 audio at a time, so doAudio makes more sense.
You go through a lot of effort to give everything an id so that you can wire everything together, it is not needed if you use your closure inside the main loop.

I would counter-propose something like this to get rid of the id centered code:

$(document).ready(function(){

    $(".my_audio").each(function(index){
        var audio = this,
            playPause = $( '
<button>Pause</button>
' ),
            button = $( audio ).after( playPause ).children().first();

        button.addEventListener("click", function(){
            if(audio.paused){
              audio.play();
              this.innerHTML = "Pause";
            } else {
              audio.pause();
              this.innerHTML = "Play";
            }
        }, false);
    });
});

If you were willing to drop the div and put the styling on the button, it would be a bit cleaner :

$(document).ready(function(){

    $(".my_audio").each(function(index){
        var audio = this,
            button = $( '<button class="audio_controls_bar">Pause</button>' ),
            $( audio ).after( button );

        button.addEventListener("click", function(){
            if(audio.paused){
              audio.play();
              this.innerHTML = "Pause";
            } else {
              audio.pause();
              this.innerHTML = "Play";
            }
        }, false);
    });
});

Since here you can drop playPause and the .children().first();.


Format multiple dates to look good in text, using functional approach

I personally prefer the first one, but this is very subjective. From a person reading the code for the first time, I can skim over the first version and have a good general idea of what the code is about. For the second version, I see a bunch of abstract functions and it takes me longer to see what the code actually does.
While the second version has some advantages, I don't believe it's worth it in this particular case unless you know something about the future of this code that I don't. I guess the point I'm trying to make is that, you should only reformat your code like that if you have a good reason for it. For example, you want to be able to change some part of the function behavior at runtime or when it's called from different parts of the codebase.


The itertools library has a function called product. You can rewrite your snippet as:

global sum_list=itertools.product(list_a, list_b, list_bb) + itertools.product(list_a, list_c, list_cc)

If you don't want to use itertools (e.g. because you're stuck on python 2.4), you can also use a list comprehension:

global sum_list=[]
sum_list.extend([a,b,bb] for a in list_a for b in list_b for bb in list_bb)
sum_list.extend([a,c,cc] for a in list_a for c in list_c for cc in list_cc)


Vectorising orthogonal-triangular decomposition for 3D matrix

Your code looks fairly good, but there are a few things I would do differently:

It's very confusing that you call B_rep for B, and call B the mean of B_rep. The comment and code here looks very strange. You should call B_mean = mean(B_rep, 1) to stick with the general naming convention in your code.

B_meanB=bsxfun(@minus,B_rep,B); % B minus mean values of B

bsxfun performs better than repmat, so instead of B_rep=repmat(matrice2,[1 1 n2]); you can do:

B_rep = bsxfun(@times, matrice2, ones(1,1,n2));

Instead of ', you should use .' when transposing an array. The first one is the complex conjugated transpose.
i and j are bad variable names in Matlab.
You should try to use more spaces. It makes the code much easier to read.

I don't have the statistical toolbox, so I can't test your code myself. I'm not sure how it can be vectorized, so I can't help with much when it comes performance gain I'm afraid.


Python [Discord.py] - Sports Fixture Bot

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

There is a bug if GUILD is not in the client guilds, as it will print out 'client.user' is connected to the last guild in the list. This is especially problematic if client.guilds is empty, as you'll end up with an exception due to never initialising 'guild'.
I would suggest a little more "defensive" code to check for this kind of problem, as good logging here could save you a headache later. It should be fine to do since this code will rarely be run.
@client.event
async def on_ready():
    def get_guild_by_name(guild_name):
        for guild in client.guilds:
            if guild.name == guild_name:
                return guild

    guild = get_guild_by_name()
    if not guild:
        // Code to handle this case. Log, print, throw, whatever you want it to do

        return

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

id = client.get_guild(73194****229982)

This is an example of a hardcoded value that should really be either in a config file, or assigned to a constant at the top of the file. If you were ever to change the guild for some reason, you'd have to track down all these occurrences and update them. Other places to look at are the hardcoded paths, and the token(!) at the bottom.

if str(message.channel) == "boxingmma":
    if message.content.find("!boxing") != -1:

        with open('/home/brendan/Desktop/boxingtest.txt', 'r') as file:
            msg = file.read(2000).strip()
            while len(msg) > 0:
                await message.author.send(msg)
                msg = file.read(2000).strip()

This block of code repeats a few times, with some minor differences. Since you may add more stats or need to make information available across multiple channels, I would think about how to make adding new commands to a channel as easy as possible. Ideally adding a new command is at most a line long, and obviously doesn't break any other commands.
I think splitting the above code into two functions, one that checks if the command is recognised (the matching) and one that does the work (retrieving the stats). The reasoning behind this separation is that the part of the above code that does the work doesn't change much, but the command matching does.
Some small things of note

x in y is a little more direct than y.find(x) != -1
I don't know why it reads the file in 2000 byte chunks, so I've left it alone. Is this really needed?
while len(msg) > 0: can be reduced to while msg: as containers like strings are truthy when they are not empty.
If you are on a recent enough version of Python, the walrus operator can be used here to remove some repeated code.
I like Path from pathlib, it has prevent a couple of errors I would have otherwise made.

The below code is for demonstration purposes, I haven't run it so I don't know if there are any issues. I also have defined the functions inline, but they would probably be better off outside on_message definition.
@client.event
async def on_message(message):
    id = client.get_guild(73194****229982)

    def matches_channel_command(message, expected_channel, expected_command):
        channel_name = str(message.channel)
        if channel_name != expected_channel:
            return False

        return expected_command in message.content

    async def retrieve_stats(path_):
        with open(path_, 'r') as file:
            msg = file.read(2000).strip()
            while msg:
                await message.author.send(msg)
                msg = file.read(2000).strip()

    if matches_channel_command(message, "boxingmma", "!boxing"):
        await retrieve_stats("/home/brendan/Desktop/boxingtest.txt")
    ...


The question is moot, as the methods give different results. It doesn't matter if a method is faster, better, simpler, nicer, fancier or cooler if it doesn't work properly.

The first method works as expected. It always truncates the string to the desired length, if the string is long enough to truncate. (Note though that this could break a combination of unicode characters used to compose a character, but that's a whole different level of expectations.)

The second method will behave badly if the string that you try to truncate contains whitespace characters in the "wrong" place.

For example, Truncate2("A   B", 3) returns "A" instead of "A  ".

The method will even crash in some situations where it should just return the input unchanged. To get an OutOfMemoryException you can call Truncate2("", Int32.MaxValue).


FWIW, this might be a rare case where the Mid statement is apropos here. This doesn't require any API. This should yield similar performance characteristics since we only allocate the buffer once just as we do with the API version.

Public Function Replicate(RepeatString As String, NumOfTimes As Long)
    Dim s As String
    Dim c As Long
    Dim l As Long
    Dim i As Long

    l = Len(RepeatString)
    c = l * NumOfTimes
    s = Space$(c)

    For i = 1 To c Step l
        Mid(s, i, l) = RepeatString
    Next

    Replicate = s
End Function


I'm not sure entirely what you're asking. If you're asking for which of three is "better" code between:

int x = count_if(vec.begin(), vec.end(), [](int x) {return x < 6; });
int y = count_if(vec.begin(), vec.end(), lessThan<6>);
int z = count_if(vec.begin(), vec.end(), LessThan(6));

I would say x then z then y. The reason for this is that the lambda solution is the only one where the actual functor is in-line with the algorithm. Anybody reading that code knows exactly what x should be immediately. There is no question. It is clear (to the extent that lambda syntax is) and concise.

z would be the C++03 way of doing this thing. It's... ok. We wrote that code for many years. The problem is the body of the functor is often hundreds of lines removed from the call, maybe in a different file... so readers of your code will have to find it. And it's never going to be perfectly clear either (who knows, maybe you named your functor weird and it's returning 6 < x? Naming things is really hard)

y is the worst. Having 6 as a template argument adds nothing to your performance (it's not like you're optimizing out a comparison), has equal readability loss compared to the lambda with the functor, and on top of that, can't even be called with a variable. With the other two, I can easily write:

int threshold = get_threshold();
int x = count_if(vec.begin(), vec.end(), [=](int x) {return x < threshold; });
int z = count_if(vec.begin(), vec.end(), LessThan(threshold));

But there's no way to pass threshold in as a template.

Typically, for algorithms, strongly prefer lambda unless (1) the algorithm call is a small part of the function and (2) the functor is very long and complicated. I say both must be met because something like this is still perfectly acceptable in my opinion:

int countBySomeCriteria() {
    return count_if(vec.begin(), vec.end(), [=](Foo const&) {
        /* some 15 line complicated functor */
    });
}

whereas if that call were surrounded by a lot of other logic, it would be much harder to easily make out.

Lambdas got added to the language basically to make stuff like this easier to write and easier to read. You should use them because they succeed in that goal.

PS. There is a fourth way to pass a functor: the lambda that was a lambda before C++11 lambdas: Boost.Lambda:

int q = count_if(vec.begin(), vec.end(), _1 < 6);

Make of that what you will.


First of all, I like the idea and the implementation.
I have refactored it a bit and came up with that:
isConnected: Extract connection[a] and connection[b] in local variables and simplify the condition.
Eclipse can assist you with the first step, the second one I did manually.
    private static boolean isConnected(int a, int b) {
        if (a == b) {
            return true;
        } else {
            final var pa = connection[a];
            final var pb = connection[b];
            return pa != null && pb != null && pa.pointerForJoin == pb.pointerForJoin;
        }
    }

In union I did the same with the local variables (beware of the assignments in the array.
Then I used nested IFs, which make the program flow easier to read.
This results in:
private static void union(int a, int b) {
    final var pa = connection[a];
    final var pb = connection[b];
    if(pa != null) {
        if (pb != null) {
            if(pa.pointerForJoin != pb.pointerForJoin)
                pa.pointerForJoin = pb.pointerForJoin = pa;
        } else {
            connection[b] = pa;
        }
    } else {
        // pa == null
        if(pb != null) {
            connection[a] = pb;
        } else {
            connection[a] = connection[b] = new Pointer();
            connection[a].pointerForJoin = connection[a];
        }
    }
}

The next step is to use a helper class instead of static variables, like that:
public class UnionFind {

    public static class Pointer {
        Pointer pointerForJoin;
    }

    private final Pointer[] connection;

    public UnionFind(int n) {
        connection = new Pointer[n];
    }

    private void union(int a, int b) {
        final var pa = connection[a];
        final var pb = connection[b];
        if(pa != null) {
            if (pb != null) {
                if(pa.pointerForJoin != pb.pointerForJoin)
                    pa.pointerForJoin = pb.pointerForJoin = pa;
            } else {
                connection[b] = pa;
            }
        } else {
            // pa == null
            if(pb != null) {
                connection[a] = pb;
            } else {
                connection[a] = connection[b] = new Pointer();
                connection[a].pointerForJoin = connection[a];
            }
        }
    }

    private boolean isConnected(int a, int b) {
        if (a == b) {
            return true;
        } else {
            final var pa = connection[a];
            final var pb = connection[b];
            return pa != null && pb != null && pa.pointerForJoin == pb.pointerForJoin;
        }
    }

    public static void main(String[] args) {
        var uf = new UnionFind(10);
        uf.union(1,2);
        uf.union(2,3);
        uf.union(5,6);
        uf.union(8,9);
        uf.union(8,2);

        System.out.println(uf.isConnected(8,3)); //true
        System.out.println(uf.isConnected(8,2)); //true
        System.out.println(uf.isConnected(9,1)); //true
        System.out.println(uf.isConnected(1,6)); //false
        System.out.println(uf.isConnected(1,7)); //false
        System.out.println(uf.isConnected(0,0)); //true
    }
}

You see how you can create multiple instances of UnionFind? You can even set a capacity at runtime.
I will leave the addition of the missing JavaDoc to you.


Day elapsed since today from a given date

It's weird to take a std::vector<char> instead of a std::string.  If you must take a std::vector<char>, then make two overloaded versions of the function, where the vector variant calls the string variant.

You never use the val parameter.  You probably meant to use it to return the computed result?  However, the computed difference is a double.

strtol() returns a long, but you assign it to an int.  Then you check if that int exceeds INT_MAX or is less than INT_MIN — which is impossible by definition.  Comparing an int with LONG_MAX and LONG_MIN is similarly nonsensical.  Really, all you want to do is check whether errno is non-zero.

You seem to expect the input in YYYYMMDD format, but you don't do any validation other than checking for overflow or underflow.  There are plenty of 8-digit numbers that shouldn't be valid dates.

Unfortunately, the localtime_s() function is Windows-only.  POSIX has localtime_r(), whose arguments are in the other order, but Windows doesn't support it.  You'll probably need an #ifdef _WIN32.

When testing for the validity of x and y, put the early-return failure case first.  That's just a better pattern for error handling, because the successful case doesn't have to be indented another level.


Identify possible pair of factors from a product

Don't using namespace std; - this namespace isn't designed for wholesale import like that.

Import <cstdlib> to declare std::system() - though note that almost any use of this function makes your code highly platform-specific (that just gives a sh: pause: not found error here, for example).

Never ignore the return value from std::system or from streaming with >>.

Error messages should go to std::cerr and end with a newline (and we should return early in the error case, rather than continuing to the while loop).

if ((f1 && f2) == p) is a highly unconventional way of writing if (p == 0).  Don't make it unnecessarily hard to read.

In the while condition, (f1 && f2) != p) can only be false when p is 1, so just treat that case separately, before the loop.

Prefer pre-increment (++x) to post-increment (x++) in C++ code when not using the result.  Here, with integers, the compiler can optimize to the same code, but with more complex types, that's not always possible.


this.state = (State) Class.forName("state"+state).getConstructor().newInstance();

This looks for a class named "stateWhatever", which isn't what you're doing below. Let's assume it's an error which happened when you copied the code.

private  void setState (String state) {
    switch (state) {
        case "Title":
            this.state = new Title ();
            break;
        case ....................
        default:
            System.out.println ("Tried to set state to " + state.toString() + ", but no such state exists.");
    }
}

Yes, this is going to get pretty long. But don't you simply separate the setting of the state from its computation?

 private State getState() {
    switch (state) {
        case "Title":
            return new Title ();
        case ....

Here, you save one line, you could save another one if your conventions allow it and that's the optimum.

In case you can precreate your states, then simply

private static final Map<String, State> stateMap;
static {
     Map<String, State> map = new Map<>();
     map.put("Title", new Title()):
     ...
     stateMap = Collections.unmodifieableMap(map);
}

would do. The usage is obvious.

In case you can't precreate your states, then you could create a

private static final Map<String, Class<? extends State>> stateClassMap;

and use reflection for the instance creation.

You're having many implementation of state and each of them has a no-args constructor. This looks like an enum.

    System.out.println ("Tried to set state to " + state.toString() + ", but no such state exists.");

You know that's no proper error handling, right?