How can I improve this PHP MySQL rank query?

DO NOT USE THE mysql_* FUNCTIONS!
They are DEPRECATED.

<?php if ($row_ranks['padric'] == '1' ) {
  echo ('
Ricerca
');
      }
      else  {
      echo ('
Ricerca
');
      }
?>

Your indentation style is a mess, decide what indentation style to use and if to use tabs or spaces (and if yes how many) and then stick to it:
<?php
    if ($row_ranks['padric'] == '1' ) {
        echo '
Ricerca
';
    } else  {
        echo '
Ricerca
';
    }
?>

Normally there's also no space between the line and the closing semicolon.
Additionally the echo function does not need any parentheses.

if ($row_ranks['padric'] == '1' )

If your code is in your native language, please always convert it to English before posting it here for review. It makes things easier for us.
Now what you use here is called a magic string or magic number, it's a fixed value that has some meaning but does not provide any explanation what's-o-ever what that meaning is or why it is that way. Use named constants instead.
const SOME_CONDITION = "1"; // Change the name to something meaningful.

if ($row['padric'] == SOME_CONDITION) {

Also do you now the difference between the equality and identity operator? The equality operator == will perform casting as needed which can yield interesting effects, the identity operator === on the other hand will also compare the types.
Some examples:
0 == 0     -->  true
0 == "0"   -->  true
0 == ""    -->  true
0 == NULL  -->  true

0 === 0     -->  true
0 === "0"   -->  false
0 === ""    -->  false
0 === NULL  -->  false

So always sue === unless you have a compelling reason not to.

$_POST[$field] = '0' ;

First of all, global variables are bad. And after that, writing into the Super-Globals is a bad idea for many reasons. Nobody expects that super globals are modified in any way and that can lead to funny errors which you'll be looking for for days.
Extract the values from the super globals and work with that variable.

$updateSQL = sprintf("UPDATE ranks SET $field='".$_POST[$field]."' WHERE userID='".$_POST['ID']."'"); // set privileges for user

One word (okay, it's two): SQL Injection. There is no, absolutely no (and I mean no) excuse to allow SQL injection. Imagine somebody would manipulate the POST request to contain the value '; DROP TABLE ranks; -- which will yield the query:
UPDATE ranks SET field='field' WHERE userID=''; DROP TABLE ranks; --'

...any questions?
Why are you using sprintf here?

$row_RSfields = mysql_fetch_assoc($RSfields);
do {
    // code
} while ($row_RSfields = mysql_fetch_assoc($RSfields));

Traditionally it's a while loop:
$result = getResult();
while ($row = fetchRow($result)) {

}

Now let's get to the core problem: You are using the mysql_* functions. You should either use mysqli_* or PDO.
Personally I prefer PDO over mysqli_* because it has an object oriented interface and support multi-statements. So here's an example on how to use PDO:
/**
 *
 * @var PDO
 */
$pdo = new PDO($dsn, $user, $password, $options);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // See footnote!

/**
 *
 * @var PDOStatement
 */
$statement = $pdo->prepare("SELECT field FROM table WHERE id = :id;");
$statement->bindValue(":id", $id, PDO::PARAM_INT);

$statement->execute();

while ($row = $statement->fetch()) {
    echo $row['field'];
}

$statement->closeCursor();

Question on Stack Overflow about when to turn off emulated prepares.

Are you aware of the difference between strings?
'A simple string'
"A string with automatic $variable expansion"


Bash script to send certain data from AWC EC2 to CloudWatch

Good

good variable names
nice indentation
good use of $()
double quoting $ variable interpolation

Challenges

I'm guessing some part of what you removed and xxxd has caused the putdata function to not do anything with the argument you are passing in.  If I guessed wrong, then you should remove the arguments so it doesn't cause someone else confusion.

Do you want this to be totally silent?    I'm not sure if the aws command produces any output here.  Adding a date command in the while loop would help debugging if you come back to the terminal later to figure out what happened.  I'd run this in a terminal under tmux for a few weeks before I started trying it in containers.  This sort of thing can have fun edge cases when some API falls over.  It can take a while to catch all of those.

It sounds like you'd like some logging.  That can be done in bash with redirection such as >> logfile.  Of course, there are more advanced choices.

I'd put a blank link before the while loop and get rid of the blank line inside of it.

You mention rewriting in python.  I wouldn't worry about it for anything this small.  But generally for AWS programming python is the winning choice since AWS provides their API that way.  Functionality may be available through the API before it is available in console.  Everything in the aws CLI command is built with this.  You can use jq to process JSON that comes back from running the aws command to do the same stuff in bash, but it is more work than python where you get a dictionary back and not have to parse any JSON.

Finally, using shellcheck is a good habit to get into when shell coding.


Look up value from one dataframe and find percent of values in another dataframe that are less than that

If you want to encapsulate the ddply logic, you can use the lapply(split(data, data[ , c("Site", "variable") ], function)-approach. I'm assuming that lookup only has one "value" for each combination of "Site" and "variable". Something like:

lapply( split(data, data[ , c("Site", "variable") ]),
       function(d) { percent= 100*sum(d$value)/ lookup[
                                   lookup$Site==d$Site[1] lookup$variable==d$variable[1] ,
                                       "value"]}
       )

Another approach (only successful if the factor levels in both dataframes match) would be to use the quotient of two tapply-(matrix) results from each dataframes:

 percent= 100*tapply( data$value, data[ , c("Site", "variable")] , sum, na.rm=TRUE)/
 tapply( lookup$value, lookup[ , c("Site", "variable")] , sum, na.rm=TRUE)


I'm going to assume Java 7 for this review. I'm sure somebody else will come along with a Java 8 version that does the whole thing in half a line. :-)

Also, pretty much everything I'm saying here has already been mentioned to you in answers to your earlier questions.

Naming

Methods in java start with a lowercase letter. Variables start with a lowercase letter (ssn, not SSN) and use camelCase, not snake_case.

Formatting

Curly braces should typically not be on their own line in cases like try { and } catch (.... Use whitespace consistently - your code is indented all over the place.

Correctness

Use the try-with-resources paradigm where possible to ensure that resources get cleaned up correctly.

SSN should be a String to preserve any leading zeros.

Design

You are just on the edge of having few enough variables in ClubInfo to have a constructor that just takes them all. That will help simplify the code. A builder would be another reasonable option.

Use methods! Short methods are easy to read and can greatly reduce repetition in your code.

It's generally, though not universally, considered a bad practice to have struct-like objects with public-visibility member variables. While it's easier to develop against, it can make life hard on you later. Using accessor methods is generally preferred.

Separate the building of ClubInfo objects from their serialization. Using a Map will trade off memory footprint and slower startup performance for faster runtime performance and easier-to-read code. Note that in this case the performance differences are insignificant and should be ignored. You might also consider an enum instead.

It's unlikely that ClubInfo initialization should be in your serialization class, but this project is probably extremely small, so it's not awful. Just bear in mind the preferred design practice would be to do it elsewhere.

Putting it all together, a simpler implementation might look more like:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public final class Serializer {

    private static final File OUTPUT_FILE = new File("/home/cg/root/club.ser");

    private static final Map<Integer, ClubInfo> CLUBS = buildClubs();

    public void serialize() {

        final MainMenu passChoice = new MainMenu();
        final int passedChoice = passChoice.chooseTeam();

        final ClubInfo club = CLUBS.get(Integer.valueOf(passedChoice));
        if (club == null) {
            return;
        }

        try {
            this.writeToFile(club);
        } catch (final IOException e) {
            e.printStackTrace(System.err);
            return;
        }
        System.out.printf("Serialized data is saved in " + OUTPUT_FILE);
        System.out.println("Choice is :" + passedChoice);
    }

    private void writeToFile(final ClubInfo clubInfo) throws IOException {
        try (final FileOutputStream fileOut = new FileOutputStream(OUTPUT_FILE);
                final ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(clubInfo);
        }
    }

    private static Map<Integer, ClubInfo> buildClubs() {
        final Map<Integer, ClubInfo> clubs = new HashMap<>();

        clubs.put(
                Integer.valueOf(1),
                new ClubInfo("Arsenal", "Emirates", "Premier League", "11122333", 60000));

        clubs.put(
                Integer.valueOf(2),
                new ClubInfo("Aston Villa", "Villa Park", "Premier League", "111223334", 40000));

        return Collections.unmodifiableMap(clubs);
    }
}


using method missing to reduce the code in ruby

Ruby already has a module which allows you to forward specific methods to a given object in its standard library: the Forwardable module.

Using it you can write code like this:

class << self
  extend Forwardable

  def_delegators :first, :increment_value, :max_work_hours_per_day #...
end

I think spelling out the methods you want to forward like this is preferable to simply forwarding everything as it won't accidentally forward something you don't want to forward. It also does not affect the error message when calling a method that does not exist.


Defining a Constructor In an Interface Java?

The warning you get, is because you call an overridable method from your constructor. This is bad because subclasses may change the implementation of the method to access other parts of the object, while it is not fully initialized yet.

So to get rid of the warning : don't call overridable methods from the constructor.

Then how to get around your predicament?

Well you could :

make the public method final.
make the class final (which you found yourself)
duplicate the logic (while possible, not the way to go)
have the public method delegate to a private method, and have the constructor call the private method.

Like this :

public class BoardImpl implements Board {
    public BoardImpl(String b) {
        doConvertFromString(b);
    }

    public void convertFromString(String formattedString) {
        doConvertFromString(formattedString);
    }

    private void doConvertFromString(String formattedString) {
        //do some parsing on string and set up the BoardImpl properties
    }
}

I wouldn't worry about making all implementations final. final is your friend.


Get chat message data from table, grouped by date

Lots of little pieces of advice:

Tab the lines of code inside of your loops and functions (etc) for improved readability.
Only declare the $key variable in your foreach() loop if you intend to use it.
Avoid performing iterated trips to the database.  Furthermore, always endeavor to minimize total trips to the database unless you have a data volume issue to contend with.
Use meaningful variable names.  $checkArr does not speak clearly of the data that it holds.
Quote your associative array keys.
You aren't filtering out any dates between the two selected users, so you can avoid calling date-fetching queries entirely.
After writing your WHERE condition to isolate the messages between the pair of users, sort the rows by descending datetime.
Use all uppercase for MySQL reserved words for clarity / readability.
Before return $data, you can run a simple loop to group the message data by date.  Use the date value as the first level keys and just push the row data as subarrays.

Suggested single query: (well... really I recommend a prepared statement)

$query =
"SELECT DATE(date_added) AS `date`, sender_id, receiver_id, `msg
FROM tb_chats
WHERE
  (sender_id = " . (int)$checkArr['sender_id'] . " AND receiver_id = " . (int)$checkArr['receiver_id'] . ")
  OR
  (sender_id = " . (int)$checkArr['receiver_id'] . " AND receiver_id = " . (int)$checkArr['sender_id'] . ")
ORDER BY date_added DESC";

Grouping with php:

foreach ($data as $row) {
    $grouped[array_shift($row)][] = $row;
}
// this step can be performed in a number of different ways according to style preference / micro-optimization
return $grouped;

I don't know code igniter, so if the grouping can be done with an available function, I don't know it.


Checking if a number is a power of 2 without loops

Use only necessary #includes. The <stdlib.h> is not needed here.
Give your operators some breathing space. ((nr&(nr-1))==0) is next to unreadable.
Separate logic from presentation:

int is_power_of_two(int nr)
{
    return nr & (nr - 1) == 0;
}

is much more reusable.
Care about corner cases. Your code claims that 0 is a power of two (which it is not).


Your fib function would benefit strongly from memoization, as currently you don't reuse the values you've already calculated to save on computations, resulting in O(n^2) computation time, as each fib(k) takes O(n) on average and you do O(n) calls.

By storing the results of previous calls, you can bring total complexity down to O(n) as each consecutive call will take O(1) and you do O(n) calls.

An easy way to do this with Python 3 is to use functools lru_cache decorator as so:

from functools import lru_cache

@lru_cache(maxsize=None)
def function_to_memoize(n):

As a side note, there is a fun fact about fibonacci numbers that every 3rd one is even and the rest are odd, so you can use that to avoid checking parity. See my answer for more details.

As for your other answer, while you seem to have the correct code, I just would like to present an alternative solution for the sake of completeness which first extracts the first letter of every word and then filters by capitalization. I also made use of lambdas for such simple functions.

def acronym(name):
    return tuple(filter(lambda x: x.isupper(), map(lambda x: x[0], name.split())))

I would warrant that your code runs faster though as it does a map on a filtered result rather than a filter on a mapped result, as filter usually reduces the search space while map does not


Object-oriented design implementation of an Elevator

Person + Derived Classes

accessibleFloors is a breach of Open–closed principle. Anyone is able to modiy this collection.
accessibleFloors could be considered a breach of Single responsibility principle. Consider having a Role class and Person storing his Roles set. This way, you can also mitigate redundant code and remove the need of derived classes as EmployeeFromThirdFloor, Guest and MaintenanceEmployee (in this trivial example these classes are not required).
accessibleFloors can be null. The code is not able to handle this situation.
HasAccess is way to convoluted: accessibleFloors.Contains(_floor); would do it.

public abstract class Person
{
    public Floors[] accessibleFloors;

    public bool HasAccess(Floors _floor)
    {
        foreach (Floors i in accessibleFloors)
        {
            if (_floor == i)
            {
                return true;
            }
        }
        return false;
    }
}

We can create a class Role.
public class Role
{
    public HashSet<Floors> AccessibleFloors { get; }

    public Role (HashSet<Floors> accessibleFloors)
    {
        AccessibleFloors = accessibleFloors
            ?? throw new ArgumentNullException(nameof(accessibleFloors));
    }

    public bool HasAccess(Floor floor)
    {
        return AccessibleFloors.Contains(floor);
    }

    // override equals and gethashcode ..
}

We can refactor Person.
public class Person
{
    public HashSet<Role> Roles { get; }

    public Person(HashSet roles) {
        Roles = roles ?? throw new ArgumentNullException(nameof(roles));
    }

    public bool HasAccess(Floors floor)
    {
        return Roles.Any(r => r.HasAccess(floor));
    }
}

Because of Inheritance, the derived classes do not require to create their own instance variable _accessibleFloors.

base.accessibleFloors = _accessibleFloors;

Elevator

There is tight-coupling between an Elevator and a Person. You force the elevator to exist only with a person. What about an empty elevator.
GoToFloor is not usable code. Consider returning a Boolean and putting the Console.WriteLine in the calling code.
The code cannot handle when Person is null.

public class Elevator
{
    Person person;
    public Elevator(Person _person)
    {
        this.person = _person;
    }

    public void GoToFloor(Floors _floor)
    {
        if (person.HasAccess(_floor))
        {
            Console.WriteLine("Elevating to " + _floor.ToString());
        }
        else
        {
            Console.WriteLine("No Access to " + _floor.ToString());
        }
    }
}

Elevator could be refactored as follows.
public class Elevator
{
    public Person Person { get; private set; }

    public bool IsFull => Person != null;
    public bool IsEmpty => Person == null;

    public bool Enter(Person person)
    {
        if (person == null) throw new ArgumentNullException(nameof(person));
        if (IsFull) return false;
        Person = person;
        return true;
    }

    public bool Exit(Floors floor)
    {
        if (IsEmpty) return false;
        if (!Person.HasAccess(floor)) return false;
        Person = null;
        return true;
    }
}

Program
class Program
{
    static void Main(string[] args)
    {
        var guestRoles = new HashSet<Role> {
            new Role(new HashSet<Floors> { Floors.FirstFloor })
        };
        var guest = new Person(guestRoles);
        var elevator = new Elevator();

        if (elevator.Enter(guest))
        {
            Console.WriteLine("guest has entered elevator");
        }
        else
        {
            Console.WriteLine("guest cannot enter elevator: elevator is full");
        }

        if (elevator.Exit(Floors.FirstFloor))
        {
            Console.WriteLine("guest has exited elevator at FirstFloor");
        }
        else
        {
            Console.WriteLine("guest cannot exit elevator at FirstFloor: access is denied");
        }

        Console.ReadLine();
    }
}


Why not just compare directly to the charcode?

function characterToNumberCoverter(character) {
  let code = character.toUpperCase().charCodeAt(0);
  if (code > 64 && code < 91) return code - 64
  return 0
}


The last know location could be null. So you need a further check for this, then ask for a quick update:

   if(location == null){
            String provider = locationManager.getBestProvider(criteria, true);
            if (provider != null){
                locationManager.requestLocationUpdates(provider, 0, 0, singeUpdateListener, context.getMainLooper());
            }else {
                Log.e("TAG", No location set");
            }
    }

class variable:

protected LocationListener singeUpdateListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            String lati = Double.toString(location.getLatitude());
            String longi = Double.toString(location.getLongitude());
            locationManager.removeUpdates(singeUpdateListener);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
      };


OOP in PHP. Exercising on creating a blog

That's a good start but the structure is overall inefficient, that leads to code duplication.

the main problem is the violation of the Single responsibility principle. The ShowABlogPost does four things at a time:

connects to the database
checks the HTTP data
fetches a certain record from the database
displays some error

it should be doing only one thing, what it's intended for - fetching a record from a database.

Another issue is multiple calls to ShowABlogPost(). It would be, like, if you have to pay a cab driver 44.50 and you got this exact amount in your pocket, but would fetch the notes and coins one by one instead of taking them all at once.

You already have an array that contains all the data from the first call. So just use this array.

Other issues are:

$DB = DatabaseFactory::getFactory()->Connect(); is duplicated in every method. Why not to make a database connection a class variable? So it will be available in all class methods by default.
PDO::FETCH_ASSOC could be made the default fetch option so you won't have to call it every time explicitly
when no variables are going to be used in the query, there is no use for the prepared statements.
when you need to fetch only one row, then you have to use fetch() method, not fetchAll()

So let's rewrite your class

<?php
class BlogPosts {

    protected $db;

    function __construct($db) {
        $this->db = $db;
    }

    public function ListAllBlogPosts() {
        $sql = "SELECT * FROM posts ORDER BY date DESC";
        $return $this->db->query($sql)->fetchAll();
    }

    public function ShowABlogPost($post_id) {
        $query = $this->db->prepare("SELECT * FROM posts WHERE id = :post_id");
        $query->bindParam(':post_id', $post_id, PDO::PARAM_INT);
        $query->execute();
        return $query->fetch();
    }
}

And now we can rewrite post.php

<?php
include_once 'connect.php';
include_once 'class_blogpost.php';

$db = DatabaseFactory::getFactory()->Connect();
$blogposts = new BlogPosts($db);

if (!isset($_GET["id"]) {
    die( "Empty request");
} else {
    $post = $blogposts->ShowABlogPost($_GET["id"]);
}
?>

<?php if ($post) : ?>

<?= $post['title']; ?>

<?= $post['post']; ?>

<?php else : ?>
    Post not found.
<?php endif ?>


Algorithm

You can increase the efficiency of the algorithm by making use of two facts (particularly the second one):

Given m and n, m < n, the largest palindrome m*j, m < j <= n, if there are any, is the one for which j is largest.  In other words, with m fixed, we can look for palindromes m*j, beginning with j = n and then successively reduce j until either a palindrome is found or we conclude there are no palindromes m*j for m < j <= n. If a palindrome mk is found, then (for fixed m) there is no need to consider values of j for which m < j < k, as we have found the largest palindrome whose smaller factor equals m and whose larger factor is between m+1 and n.
If a palindrome k*l has been found, where k < l <= n, then in order for i*j > k*l, where i < k, i < j <= n, we see that j > k*l/i (regardless of whether i*j is a palindrome).  In other words, there is no need to check to see if i*j is a palindrome for j <= k*l/i, as it cannot be larger than the currently largest known palindrome.  Moreover:

if i*j, is found to a palindrome, where k*l/i < j <= n, it becomes the currently largest known palindrome; and
if k*l/i > n, we are finished, as no product e*f, e <= i, e < f <= n, can be larger than the currently largest known palindrome.

These two observations are implemented in a straightforward way by the code that follows.

Code

def largest_palindrome(low=1,n)
  best = { product: false }
  (n-1).downto(low) do |start1|
    start2 = best[:product] ? (best[:product]/start1.to_f).ceil : start1+1
    break if start2 > n
    found2 = n.downto(start2).find { |j| palindrome?(start1*j) }
    best = { product: start1*found2, v1: start1, v2: found2 } if found2
  end
  best
end

def palindrome?(n)
  (s = n.to_s) == s.reverse
end

Examples

largest_palindrome(99)
  # {:product=>             9,009, :v1=>       91, :v2=>      99,
  # :smaller_at_term=>         90, :nbr_palins=>1, :soln_time=>"0.00004"}
largest_palindrome(999)
  # {:product=>           906,609, :v1=>      913, :v2=>      993,
  #  :smaller_at_term=>       907, :nbr_palins=>2, :soln_time=>"0.00101"}
largest_palindrome(9,999)
  # {:product=>        99,000,099, :v1=>     9901, :v2=>     9999,
  #  :smaller_at_term=>    9,900,  :nbr_palins=>1, :soln_time=>"0.00178"}
largest_palindrome(99,999)
  # {:product=>     9,966,006,699, :v1=>    99681, :v2=>    99979,
  #  :smaller_at_term=>     99661, :nbr_palins=>1, :soln_time=>"0.02040"}
largest_palindrome(999,999)
  # {:product =>  999,000,000,999, :v1=>  999,001, :v2=>  999,999,
  #  :smaller_at_term=>   999,000, :nbr_palins=>1, :soln_time=>"0.20434"}
largest_palindrome(9,999,999)
  # {:product=>99,956,644,665,999, :v1=>9,997,647, :v2=>9,998,017,
  #  :smaller_at_term=> 9,995,665, :nbr_palins=>1, :soln_time=>"2.05677"}

I have formatted the numbers to make them easier to read and also added three statistics I thought might be of interest:

the value of the smaller of the two factors when the search was terminated;
the number of palindromes found before the search terminated; and
the solution time in seconds (on a newish Mac).

To see where each search terminated, divide best[:product] by n, round up and subtract 1. For example, for n = 9999, this would be:

(99000099/9999.0).ceil - 1 #=> 9900

This shows that when determining the largest palindrome for numbers up to 9,999, it was only necessary to consider pairs with values greater than 9,900. Hence, at most (9999-9900)*(9999-9901) => 99*98 => 9,702 pairs were examined, which is 0.0097% of all 9999*9998 => 99,970,002 pairs of numbers up to 9,999.

For n = 999, two palindromes were found before the search terminated. In each of the other four examples, only one palindrome (i.e., the largest) was found before the search terminated.


template < typename _Msg, typename _Alloc = std::allocator<_Msg> >

Those names are dangerous - underscore followed by capital is reserved to the implementation for any purpose.  That means they could be macros, which would give you some tricky parse errors to diagnose!  Stick to names you're allowed to use (in this case, I'd just drop the underscores).
post()

{
    QMutexLocker lock_(&mx);
    que.push(msg);
    cv.wakeOne();
}

There's an inefficiency here, because waking another thread while we still hold the mutex will cause that thread to immediately block.  Better to release the mutex before waking:
{
    {
        QMutexLocker lock_(&mx);
        que.push(msg);
    }
    cv.wakeOne();
}

A design choice here: should a queue be allowed to expand until it throws std::bad_alloc?  Or do we want a maximum capacity at which the write end blocks?
If you have enough C++11 support, prefer to accept the argument by value, then std::move() it to the container.  That avoids copying rvalue arguments.
wait()

void wait(DataType& msg)

That's a clunky interface.  Prefer to just return the DataType.
I'm not a fan of the truncated "Que" name, and seem to stutter on it every time I read it.  What's wrong with the full word?


Speeding up loop-rich Matlab function to calculate temperature distribution

First, using vectors would probably speed it up quite much, and would be worth the effort.

However, here's a small tip, that could improve the performance a little bit:

In many of the CPU-hungry iterative computations, you could replace the computations that occur several times by a variable.

In the code, there are several "j+i" terms. They can simply be replaced by a variable named, "jpi". So, the number of additions in each value of j would decrease by 5 (not 6, as you still need to do an addition, once per each iteration of j).

dis(j) is also frequently used, and it might be useful to create another dummy variable, like dis_j = dis(j) once per each iteration of j. I don't know if matlab compiler does this itself to optimize performance. this one stops the cpu from looking at the value of dis(j) each time it is called. So it should help a little bit.


A history lesson

I feel obligated to note that similar functionality (in the page body) has already been implemented in native html using the <marquee> tag (mdn). This tag has been deprecated for forever though, because it is deemed a usability nightmare and visually distracting without a cause.

The same issue applies to changing the title of the page. It distracts the user, and may annoy the user. Users can already view the entire page title by hovering over the tab, but most people do not care about what the title is at all.

Avoid onload (and other on... definitions)

Don't use the on... family of attributes to create listeners for events. Your code does not operate in a void. There are other scripts, some of which you do not have control over. When you assign to an on... attribute, you override the previous assigned function. This, in turn, creates hard to debug problems.

Instead, use .addEventListener(..) (mdn). You can add and remove as many listeners as you want without having to worry about other code.

var clicker = document.getElementById('clicker');

clicker.onclick = function () {
  console.log('First handler');
}
clicker.onclick = function () {
  console.log('Second function');
}
The problem with onclick (and onload, and other on... attributes):

Click me!

Custom parameters

You are correctly using attributes with the data- prefix for your custom attributes. If we want to use such attributes though, we usually put them on the element we are manipulating, not a random script tag. In this case, it's probably better to put it on the title tag. This will also simplify your code a lot, since you only need to grab the title tag and do not have to worry how you load in your code, or if any other code is using your custom attributes.

Optimalisation of housekeeping in interval callback

You are currently using the following code for housekeeping in your interval callback

i++;

if (i === title.length) {
    i = 0;
}

You could instead leverage the modulo operator to simplify the code.

i = (i + 1) % title.length;

Separator

You are calculating your title length without the separator. This means that the title will not complete a full round and instead will jump back to the beginning when -- is at the start.

Various other things

It is always a good idea to use IIFE (Immediate Invoked Function Expressions) to encapsulate your code. This prevents other scripts from interacting with your variables and functions. An IIFE looks something like the following, and is invoked with the variables it depends on (e.g. a javascript library such as jQuery):

(function () {
  // Your code
})();

You have on inconsistent space in your function declaration at setInterval(function () {. Your variable title_ref is not written in camelcase, while the rest of the variables and functions in your code are written that way.

Other than that your code looks clean. Your variable names are clear and make it easy to understand what they contain.


Calculating an object's stopping distance

Considering this as a uniformly accelerated linear motion problem with given velocity and (negative) acceleration, you could use:

function getStoppingDist(speed, accel) {
  var dist = 0.5*Math.pow(speed,2)/accel;
  return dist;
}


When using decorators, you should familiarize yourself with functools.wraps. Consider the difference in available informations between these two (useless) decorators:

from functools import wraps

def decorate1(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

def decorate2(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

When applied to a function:

@decorate1
def test1(x, y, z):
    "test1 docstring"
    print(x, y, z)

@decorate2
def test2(x, y, z):
    "test2 docstring"
    print(x, y, z)

The help on each function look quite different:

>>> help(test1)
Help on function wrapper in module __main__:

wrapper(*args, **kwargs)

>>> help(test2)
Help on function test2 in module __main__:

test2(x, y, z)
    test2 docstring

Since you’re using Python 3, you should consider using better timing primitives. Namely time.perf_counter():

def wrapper(*args, **kwargs):
    begin = time.perf_counter()
    res = original_function(*args, **kwargs)
    elapsed = time.perf_counter() - begin

Lastly, you should consider using format all along instead of string concatenation:

import time
import colorama
from functools import wraps

def timeit_decorator(original_function):
    @wraps(original_function)
    def wrapper(*args, **kwargs):
        begin = time.perf_counter()
        result = original_function(*args, **kwargs)
        elapsed = time.perf_counter() - begin
        print("Function {color}{}{reset} executed in {color}"
              "~{:.2f}{reset} minutes!"
              .format(
                  original_function.__name__,
                  elapsed / 60,
                  color=colorama.Fore.GREEN,
                  reset=colorama.Style.RESET_ALL))
        return result
    return wrapper


I'm not so sure about this method:

Why would you call this for a value type, if you already know that you're dealing with a value type? You mentioned something about 'obviously wrong default values', but that probably depends on the context.
If you do find a general definition of what exactly being 'available' means, you may want to document it. Chances are that what's obvious to you isn't obvious to someone else, or even to yourself a few months later.
What's the point of checking if an IEnumerable contains Any available items? It could still contain many unavailable items, so you'd still have to check each item before use. All would be more appropriate, but that would make this method very 'eager'.
Iterating an IEnumerable can cause problems when you're working with lazily evaluated sequences. You'd have to be careful with where you use this method, or you could accidentally fetch data from a database twice, or do other duplicated work. Letting the caller check each item before use seems a much safer (and cheaper) alternative.
That Cast<object>() call causes T in the inner call to be object, so the IsValueType and IEnumerable checks won't work.
You'll want to know the actual type of the value you're checking, so use value.GetType() instead of typeof(T). And instead of calling IsAssignableFrom, you can use is, or just use as immediately and then check if the result isn't null.
What's the point of converting the given value/object to a string? It's basically checking the result of value.ToString(). Any class that overrides ToString and that returns null or an empty string will always be seen as unavailable, which is probably a subtle bug lying in wait. I'm not sure what this check is meant to accomplish.

All in all, I don't really see what value this method provides. If you've got a value type then you probably already know it, and you most likely know better which values are valid and which ones aren't, depending on context. In any other case, you can use the Elvis operator (?.) or do a null check of some sort.


Creating a pythonic snippet to read and clean .csv files

Firstly, you should raise not return your errors.

Secondly, try: with a bare except: is bad practice (e.g. http://blog.codekills.net/2011/09/29/the-evils-of--except--/); what do you expect could go wrong with each step? Test for specific errors and deal with them appropriately. It is this which has hidden the NameError I mention at the end.

Thirdly, your use of the flag err seems a bit odd; much more Pythonic to use an actual boolean err = False or, better, else::

try:
    validate_email(e_mail) # see comment below
except: # but only the errors you expect - see above
    pass
else:
    cleaned_csv_content.append((fname, lname, e_mail)) # note additional parentheses

or, even better, refactor validate_email to return True for a valid email and False otherwise, rather than raising errors:

if validate_email(e_mail):
    cleaned_csv_content.append((fname, lname, e_mail))

Finally, note that "email" != "e_mail".


The idea of abstracting DateTime.Now and DateTime.UtcNow for testability is definitely a good one. There are some improvements I'd suggest:

Naming

FooProvider is a name I usually pick when I absolutely can't think of a better name for something that provides Foo. In this case, a much more natural name than DateTimeProvider would be Clock.

I also don't really like the name ConstValue. For one thing it's an unnecessary shortening of ConstantValue. But probably Override would be more descriptive.

Implicit Operator

I tend to lean towards being pretty permissive with the use of the implicit operator. It's often a good way to be able to write more expressive code without cluttering things up with constructor calls.

But in this case I think the benefit is very marginal. The difference in readability between calling e.g. AddTimestamp(clock) and AddTimeStamp(clock.Value) is very minor, and the latter is actually more expressive of that fact that you're stamping it with the time at the point that the AddTimeStamp method was called (rather than at some arbitrary point during its procedure).

Design

Splitting Now and UtcNow into different classes seems weird, for a couple of reasons:

It implies that you need both in your system, but never in the same place. If you did need them in the same place, you'd need to handle two different clocks, which would be cumbersome.
Similarly, it's quite possible you'll have a class which should make its own decision about whether to use Now or UtcNow. It may be a natural part of a class's responsibility to make that decision, not something that should be chosen in bootstrapping. In that case, you'd need to give the class some kind of DateTimeProviderProvider so it could get the right one!

So with that in mind I'd suggest an intermediary step of changing to:

public abstract class Clock
{
    public abstract DateTime Now { get; }

    public DateTime? NowOverride { get; set; }

    public abstract DateTime UtcNow { get; }

    public DateTime? UtcNowOverride { get; set; }
}

Override logic

Admittedly, the above actually looks worse than what we started with, but there's one more problem to tackle: the use of override-type logic. The issues with this:

It's hard to test. Your NowDateTimeProvider exists so tests don't have to deal with the real current date time. But that class itself can't be tested without dealing with the real time. Although it's a simple class, it still has logic, which means not being able to test it is a problem.
Your production code has to deal with testing concerns. Every clock you write can have the time overridden, even though there's no scenario in real code where this should be allowed. It's unsafe, and even if you're careful, it degrades the expressiveness of your code to have "Don't call me!" methods.
It's more code. Instead of a simple Now, you need a Now, a NowOverride, and logic to glue them together.

Fortunately, none of these are hard to fix:

public abstract class Clock
{
    public abstract DateTime Now { get; }

    public abstract DateTime UtcNow { get; }
}

public class RealClock : Clock
{
    public override DateTime Now { get { return DateTime.Now; } }

    public override DateTime UtcNow { get { return DateTime.UtcNow; } }
}

public class TestClock : Clock
{
    public override DateTime Now { get; set; }

    public override DateTime UtcNow { get; set; }
}

And finally...

From that last version, you can see that once we've made these changes, there's no need to have an abstract class anymore. We're left with just signatures, so we can change to an interface. This also means we can consider not writing TestClock at all and using a mocking library instead.


I want to suggest that you use LESS/SASS to build your library

You have a lot of math. One problem here is that if you want to change your sizes, you'd be facing a calculator, calculate and change values for each. One decimal place wrong and it could ruin your pixel-perfect calculations.

With LESS/SASS, you can define your values in variables, and have properties as math expressions. Want to change the dimensions? No need to meddle with the implementation, just change the variables (That's how BootStrap customizers work).

@fullWidth : 1800;

.fifty {
  width : percentage(@fullWidth/2);
}

Also, it has nesting. I think this is possible in place of your very long sequence up there. Much cleaner.

.belt {
  .m1, .m2, .m3, .m4, .m5, .m6, .m7, .m8 {
    ...
  }
}


Use functions whenever possible

I think there are too many classes and you should consider using functions instead: it is easier to test (unit testing).

Use a logger

First thing: the code below make me think that you should use a logger instead of reinventing the wheel:

report = reporter.format_report()
save_to_file.send(report)
show_on_console.send(report)

Here is how you can define a root logger which can log in the console as well as in a file:

import logging

def setup_logger(log_dir, log_file_name):
    # root logger
    logger = logging.getLogger()

    formatter = logging.Formatter(
        "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")

    file_hdlr = logging.FileHandler(
        "{0}/{1}".format(log_dir, log_file_name))
    file_hdlr.setFormatter(formatter)
    logger.addHandler(file_hdlr)

    console_hdlr = logging.StreamHandler()
    console_hdlr.setFormatter(formatter)
    logger.addHandler(console_hdlr)

    logger.setLevel(logging.DEBUG)

This setup_logger function should be called at program startup, in your main, for instance:

if __name__ == "__main__":
    setup_logger("my/work/dir", "my_app.log")

You can use this logger anywhere: in each Python module, you can define a global variable named LOG, and use it like this:

LOG = logging.getLogger(__name__)

def my_function():
    LOG.info("log message")

See the How To documentation

wrong usage of generator

In your, competitors is a generator, not a tuple. After having iterate a generator the first time, then the generator is exhausted. It means that the second loop will end immediately.

self.competitors = (item for item in competitors if self.valid_item(item))

The call to rule_compared_smaller will iterate the competitors, then the call to rule_compared_two_times_smaller will do nothing because the competitors is exhausted.

You need to create a list:

self.competitors = [item for item in competitors if self.valid_item(item)]


Dealing with Entity Framework's lack of enum support

I keep seeing all these really complex solutions to the lack of enum support, but most make things tricky when taking into account that next entity framework release is probably going to have enum support.

Here's my solution. A sample class, before our workaround:

public class Widget
{
    public int ID { get; set; }
    public Status Status { get; set; }
}

Obviously Status won't be saved as it's an enum, and if we provide a fancy workaround, things will probably break when we upgrade to the next entity framework release, as it'll suddenly start trying to read and write that property. So we do the following:

public class Widget
{
    public int ID { get; set; }
    [NotMapped] // stop future entity frameworks from accidentally using this column
    public Status Status { get; set; }

    [Column("Status")]
    private int StatusEnum
    {
        get { return (int)Status; }
        set { Status = (Status)value; }
    }
}

The new property is private so we can't see it externally, so it doesn't exist to the outside world for all intents and purposes. The entity framework can see it as you've marked it with a [Column] attribute and so it'll be found via reflection. The original enum column will be skipped even if we upgrade to a later version of the framework, and then all we have to do is remove those few lines of workaround code and things should still work seamlessly.

The result?

The class looks the same to anything consuming it, but now enums are saved and loaded
No additional code complexity
Future-proofed against entity framework upgrades
Super easy to remove the additional code when upgrading to a version of the framework that supports enum persistence


Yusshi's code is perfectly fine. If you know that all the characters are in a specific range (e.g., ASCII code 0 to 255), you could also use either of the following codes which is faster. They uses an array rather than a hash set. The time complexity is O(n) and the space complexity is O(1). You cannot go lower in either case.

This one sorts the characters in the output string:

public static String removeDuplicates(String str) {
    int charsCount[] = new int[256];

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        charsCount[ch]++;
    }

    StringBuilder sb = new StringBuilder(charsCount.length);
    for (int i = 0; i < charsCount.length; i++) {
        if (charsCount[i] > 0) {
            sb.append((char)i);
        }
    }

    return sb.toString();
}

This one preserves the order of the characters:

public static String removeDuplicates(String str) {
    boolean seen[] = new boolean[256];
    StringBuilder sb = new StringBuilder(seen.length);

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (!seen[ch]) {
            seen[ch] = true;
            sb.append(ch);
        }
    }

    return sb.toString();
}


It's better than rendering HTML in some other language manually, but it's at a disadvantage to HTML super-set template languages.

Mirroring the structure of HTML in JS makes the design more verbose because you need to map object fields to HTML tokens like attr: and not tangibly better than HTML that's parameterized with jQuery.  Mistakes in such a scheme, while not as bad as rendering HTML directly, are easier to make and harder to find than writing straight HTML or a super-set thereof because no IDE is going to understand how the JS object maps to an HTML snippet to validate it.  Most HTML super-set template languages have the same problem with IDEs, to be fair, but it's usually easier to see what the HTML emitted is going to look like.

Another thing I might look into refactoring is the mapping object, which is using specific attribute names.  You have an abstraction in the design, handle, that could just as easily be applied to attribute names, and your mapping would not have to reference the design's HTML at all.  That might be an idealistic complaint, though.

In summary, what I would rather see is roughly the same data and mapping methodology, but make the design something my IDE (and eyes) will better understand as HTML.


Functional approach to splitting list into sub lists

Haskell:

import Data.List.HT -- or Data.List.Grouping

takeruns xs@(x:xss) = map (map fst) pss
  where pss = segmentAfter (uncurry (>)) $ zip xs xss

EDIT
Example:

xs = [1, 2, 3, 2, 4, 1, 5]
xss = [2, 3, 2, 4, 1, 5]
zip xs xss = [(1, 2), (2, 3), (3, 2), (2, 4), (4, 1)]
uncurry (>) (1, 2) == 1 > 2 = False
segmentAfter ... = [
    [(1, 2) /* False */, (2, 3) /* False */, (3, 2) /* True */],
    [(2, 4) /* False */, (4, 1) /* True */],
    []
]
map (map fst) (segmentAfter ...) = [[1, 2, 3], [2, 4], []]

And, it turns out that my function is wrong :)
Correct version:

takeruns xs = map (map snd) pss
  where pss = segmentAfter (uncurry (>)) $ zip (minBound:xs) xs


By improvement, I suppose you have performance in mind because your queries are fairly basic and not hard to understand.
I have had a look at your SQL fiddle and your tables have no indexes. Absent any other optimization mechanism the database engine will have to perform a full table scan to fetch the wanted rows. Thus, I don't expect much difference between a join or a subselect, or CTE. On a large table, the bottleneck is likely going to be row filtering, on a small table the performance hit should be negligible.
First, consider adding indexes on your tables, for example the user ID field could be a primary key.
Then use the explain command, preferably on a larger dataset for more representative results. For this you could write a script to generate a large bunch of random records.


Separating integers substrings from those with alphabetical letters

The elif in

   if character in "0123456789":
        // ...
    elif character not in "0123456789":
        // ...

can be replaced by an else.

if string_type in ("Int", ""):
    current_substring += character
    if string_type == "":
        string_type = "Int"
else:
    character_list.append(current_substring)
    string_type = "Int"
    current_substring = character

can be simplified to

if character in "0123456789":
    if string_type == "Str":
        character_list.append(current_substring)
        current_substring = ""
    string_type = "Int"
    current_substring += character

and similarly for the non-digits case. However, using strings
("", "Str", "Int") for the current state is error-prone.
An enumeration would be an alternative, or in this case simply a boolean:

in_digits = None
for character in input_text:
    if character in "0123456789":
        if in_digits is False:
            character_list.append(current_substring)
            current_substring = ""
        in_digits = True
        current_substring += character
    else:
    // ...

And now the two cases can be combined into one:

in_digits = None
for character in input_text:
    is_digit = character in "0123456789"
    if in_digits == (not is_digit):
        character_list.append(current_substring)
        current_substring = ""
    in_digits = is_digit
    current_substring += character

More remarks:

if not input_text:
    return None

When called with an empty string, I would expect the function to return
an empty array, not None.

character_list = []

The variable name is slightly misleading, this is a list of strings.

Summarizing the suggestions so far, we have

def separate_text(input_text):
    string_list = []
    current_substring = ""
    in_digits = None
    for character in input_text:
        is_digit = character in "0123456789"
        if in_digits == (not is_digit):
            string_list.append(current_substring)
            current_substring = ""
        in_digits = is_digit
        current_substring += character
    string_list.append(current_substring)
    return string_list

Finally note that the same can be simply achieved by splitting the
string on a regular expression:

import re

def separate_text(input_text):
    return [item for item in re.split('(\d+)', input_text) if item]


Countdown to multiple update times each day

You don't need to create Date object for each day time case (morning/midday/afternoon) since you don't actually use any date component except hour. So you only need to extract current hour from today and define range it belong to.

var today = new Date();
var hour = today.getHours();
hour = hour < 10? 10 : hour < 14? 14 : hour < 17? 17 : 0;
var countDownTo = [today.getFullYear(), today.getMonth()+1, today.getDate()].join('/')+ (hour? hour+':00:00' : '');
...


Create HTML page to document contents of directory

(Warning I havn't tested the following code.)

Python

Offload the custom html to a template engine. Jinja2 can be used in both flask and django. And so I'll change your code to use this. (I'm not affiliated)
It's good to see you manually .closeing your files. But using with is better.
Use ' or " string delimiter. You can switch if the string contains your prefered one. I prefer ', but would use "it's" rather than 'it\'s'.
You can move your CSS into its own file and copy the file with whatever you think is best.
I'd use ''.join and a comprehension to make filenames a string, that can be passed to Jinja.

#! /usr/bin/python3
from os import walk
from pathlib import Path
import shutil

from jinja import Environment, FileSystemLoader, select_autoescape

FILE = Path(__file__).resolve()
RESOURCES = FILE / 'name'
CWD = Path.cwd()

env = Environment(
    loader=FileSystemLoader(str(RESOURCES / 'templates')),
    autoescape=select_autoescape(['html'])
)

if __name__ == '__main__':
    shutil.copyfileobj(
        open(RESOURCES / 'css' / 'style.css'),
        open(CWD / 'style.css', 'w+')
    )

    filenames = ''.join(
        '{{ "name":"{0}", "desc":"{0}" }},'.format(f.name)
        for f in CWD.iterdir()
        if f.is_file()
    )

    with open(CWD / 'index.html', 'w+') as html:
        page = env.get_template('index.html').render(
            title='Documents',
            links=filenames
        )
        print(page, file=html)

CSS

From the little I've done with CSS your file looks a bit off to me:

I'm used to seeing a line between each style.
I'm used to seeing K&R, rather than Allman, indentation style.
You should keep your indentation consistant.
I'm used to seing a space after : and ,.

New location: /bin/name/css/style.css.

body {
    font-style: normal;
    font-family: sans-serif, Georgia, Helvetica, Arial, sans-serif;
    background-color: white;
    color: black;
    margin-left: 5%;
}

div.navbar {
    text-align:center;
}

HTML

I'm used to seing indentation, most webdev tools also do this for you. And so I'd assume that if they're doing it then there's a good reason for it. I find your HTML code to be a bit hard to read currently because of it.

New location: /bin/name/templates/index.html.

<!DOCTYPE html>

  <title>{{ title }}</title>
  <link rel="stylesheet" href="style.css">

Documents

    These directories may contain proprietary and confidential information.

Document list

&nbsp;

        index.html

        this file


A defined macro to copy selected values of std::vector to an array using std::copy

Basically, there are very few places in C++ where you want to use Macros. A lot of old C code used function-like macros because of performance reasons - calling a function requires creating a new stack frame. They were also used to get away from C's type system. With C++, inline functions and templates remove the need for this 99% of the time.

template <typename T>
inline void copy_vector_to_array(const std::vector<T>& vec,
                                 std::size_t position,
                                 std::size_t length,
                                 T* array)
{
    std::copy(vec.begin() + position, vec.begin() + position + length, array);
}

In C++11, we can do better still - an erroneous length passed in above will cause problems, and will be hard to detect:

#include <vector>
#include <array>
#include <iterator>
#include <cassert>

template <typename T, std::size_t N>
inline void copy_vector_to_array(const std::vector<T>& vec,
                                 std::size_t position,
                                 std::size_t length,
                                 std::array<T, N>& array)
{
    assert(length <= N);
    std::copy(std::begin(vec) + position, std::begin(vec) + position + length,
              std::begin(array));
}

This will be just as efficient as the macro version, however, we also gain type safety, as well as (easy) bounds checking.

We can also improve on it. So that it handles other container types:

template <typename C, std::size_t N>
inline void copy_container_to_array(const C& container,
                                 std::size_t position,
                                 std::size_t length,
                                 std::array<typename C::value_type, N>& array)
{
    assert(length <= N);
    std::copy(std::next(std::begin(vec), position), std::next(std::begin(vec), position + length),
              std::begin(array));
}


For an implementation without the STL, this is pretty good.  There's no risky memory-management going on with the raw pointers, and your sorting isn't needlessly slow (compared to bubble sort).  I'll base my review on the STL anyway (for future reference), along with some other general tips.

SIZE should be of type std::size_t.  It's preferred to use an unsigned integer type for sizes, plus you'll have a larger range (no negative values are part of it).
If you have C++11, prefer std::array (or any other STL container) over C-style arrays.  This also makes it needless to pass the array size since STL containers already know their own.

Your array initialization, for instance, would look like this:

std::array<int, SIZE> iArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If you use the above array or another STL container, the loop counters in reverse() and display() should be of type std::size_type.  This will ensure:

the supported size type for this container is used
the loop will be able to access any number of elements

Also, as @thelamb mentioned, pre-increment (++index) is preferred because it will avoid extra copies.  This is especially important for user-defined types (such as std::array), while post-increment is still okay with native types (such as int).
Prefer iterators to raw pointers in C++:

// with C++11

auto begin = std::begin(container);
auto end   = std::end(container);

// without C++11

std::ContainerType::iterator begin = std::begin(container);
std::ContainerType::iterator end   = std::end(container);

You could compare your reverse algorithm to the idiomatic STL method with regards to efficiency (if you were to perform a speed test on them):

std::reverse(container.begin(), container.end());

I'd avoid the extra newlines in display().  The function's purpose is solely to display the array, plus you'll be forced to have the newline with each call.  Two things for this:

add the newlines before and/or after the function call instead
use \n instead of std::endl (the latter also flushes the buffer, which takes longer)

So, instead of this:

std::cout << std::endl;

std::cout << "Backwards:\n";
display(iArray);

you could have this:

std::cout << "\nBackwards:\n"; // another '\n' at the front
display(iArray);
std::cout << "\n";             // newline here instead of in display()

For comparison, here's an idiomatic alternative using templates (any element type is supported).  It uses an std::vector instead of an array, saving you size constraints.  It also displays the vector in forward and in reverse using an iterator, instead of mutating it for the reverse.

#include <algorithm> // std::copy, std::reverse_copy
#include <iostream>
#include <iterator>  // std::ostream_iterator
#include <vector>

template <typename T>
void displayForward(std::vector<T> const& vec)
{
    std::copy(vec.cbegin(), vec.cend(),
        std::ostream_iterator<T>(std::cout, " "));
}

template <typename T>
void displayReverse(std::vector<T> const& vec)
{
    std::reverse_copy(vec.cbegin(), vec.cend(),
        std::ostream_iterator<T>(std::cout, " "));
}

int main()
{
    std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    std::cout << "Forward:\n";
    displayForward(vec);

    std::cout << "\nBackwards:\n";
    displayReverse(vec);
}


Improving and optimizing squeeze() function

You want to avoid repeat iteration over the 2nd string, which is O(N).  Do this N times and you have an O(N2) algorithm.

One trick you could use is to build a lookup table of the chars in str2.  This would cost O(N) and some extra memory upfront, but then subsequent lookups in the table could be brought down to O(1).

Here's a simple example.  The trade-off is this takes a bit more memory and makes some assumptions about the range of char.  It also clobbers the buffer of str1:

#include <limits.h>   // for UCHAR_MAX

char *squeeze (char *str1, char *str2)
{
   char present[UCHAR_MAX + 1] = {0};
   char *src, *dst;

   // Build lookup table of chars in str2
   //
   while (*str2)
      present[(unsigned char)*str2++] = 1;

   // Iterate through str1, removing chars along the way.
   //
   src = dst = str1;
   while (*src)
   {
      // Is *src in str2?
      //
      if (present[(unsigned char)*src])
      {
         // Yes, remove this char.. (Advance src but not dst.)
         //
         ++src;
      }
      else
         *dst++ = *src++;
   }

   // NUL terminator
   //
   *dst = 0;

   return str1;
}


I ended up using this code a few times, and recently was thinking through a scenario where the above will fail:

var iParam = Expression.Parameter(typeof(int));
var lParam = Expression.Parameter(typeof(int));

var original = Expression.Invoke(
    Expression.Lambda(
        Expression.Invoke(
                Expression.Lambda(
                    Expression.Add(iParam, lParam),
                    iParam),
                Expression.Constant(1)
        ),
        lParam),
    Expression.Constant(2)
);
var transformed = original.InlineInvokes();

The original can be visualized as:

Invoke(Param_0 => Invoke(Param_1 => (Param_1 + Param_0), 1), 2)

Here, the inner invocation is using a parameter from its parent. Since we're using a stack to represent the mappings between parameters, we're not taking into consideration Param_0. Here's the current output:

(1 + Param_0)

Here's the fixed code:

protected override Expression VisitInvocation(InvocationExpression e)
{
    var callingLambda = e.Expression as LambdaExpression;
    if (callingLambda == null)
        return base.VisitInvocation(e);
    var currentMapping = new Dictionary<ParameterExpression, Expression>();
    for (var i = 0; i < e.Arguments.Count; i++)
    {
        var argument = Visit(e.Arguments[i]);
        var parameter = callingLambda.Parameters[i];
        if (parameter != argument)
            currentMapping.Add(parameter, argument);
    }
    if (_context.Count > 0)
    {
        var existingContext = _context.Peek();
        foreach (var kvp in existingContext)
        {
            if (!currentMapping.ContainsKey(kvp.Key))
                currentMapping[kvp.Key] = kvp.Value;
        }
    }

    _context.Push(currentMapping);
    var result = Visit(callingLambda.Body);
    _context.Pop();
    return result;
}

Note that we only propagate the parameters if they don't already exist. This is required in situations as follows:

var iParam = Expression.Parameter(typeof(int));
var lParam = Expression.Parameter(typeof(int));

var original = Expression.Invoke(
    Expression.Lambda(
        Expression.Invoke(
                Expression.Lambda(
                    Expression.Add(iParam, lParam),
                    iParam, lParam),
                Expression.Constant(1), Expression.Constant(3)
        ),
        lParam),
    Expression.Constant(2)
);

Invoke(Param_0 => Invoke((Param_1, Param_0) => (Param_1 + Param_0), 1, 3), 2)

Here, the inner invoke is providing a value for Param_0 which takes precedence over what the outer invoke is providing. If we compile that expression (without inlining) - we see the result is 4.

Thus, we must ensure that we only add parameters from our parent context if we haven't already been provided them.


Creating user accounts as an administrative user

It's fine to create 2 methods to break up the logic a bit - however, there are other things I'd look into before tackling the user vs admin stuff:

Firstly: Ruby style prescribes 2-spaces indentation - not tabs, not 4 spaces.

Second, if you're going to use them, make those create_by* methods private. Don't mix 'em with the regular controller actions.

Third: String interpolation:

flash[:success] = "User for #{@user.name} created."

But success is an uncommon flash key. You can use the default notice message type directly in your redirect

redirect_to root_url, notice: "User for #{@user.name} created."

If you absolutely want to use success, you can use add_flash_types to add it, and use redirect_to ..., success: '...'.

And then you have this:

render 'new_by_admin' # basically a new.html.erb but with a dropdown for the admin setting

Don't use two templates - that's a giant hassle to maintain. Use a conditional in the view itself to show or not show the dropdown. I'd also add an admin? helper like this

# in application_controller.rb
def admin?
  current_user.try(:admin?)
end
helper_method :admin?

(I'm assuming that current_user is nil if you're not signed in).

So now you can check for admins in one go rather than both check signed_in? and then check current_user.admin?

In the new view you get this:

<% if admin? %>
  your dropdown
<% end %>

And you don't need to 2 templates. Your if..elsif..else in #create can also become the more readable:

if admin?
  ...
elsif signed_in? # regular user
  ...
else
  ...
end

Your code also makes me wonder how you handle passwords. If an admin creates a user, I imagine you'll want to send login instructions and password to the new user.

Right now, it looks like the admin picks a password for other people, but you should already have a "reset password" method (for users who've forgotten their password) that will create a random password and email it to the user. It shouldn't be the admin's job to make up passwords.


When a constructor calls a helper function, should the helper mutate the object or return part of the object?

As far as I see no-one has mentioned temporal coupling yet, so here it is.

The second one (which returns void) has this code smell. Consider the following constructor code:

createMonsters();
...
doSomethingWithMonsters();

A maintainer easily could mix up the order of the called methods which breaks your class and might turn out only at runtime. It's not possible the following:

Monster[,] monsters = createMonsters();
...
doSomethingWithMonsters(monsters);

Changing the order of the two methods simply would not compile.

Another advantage of the first one is that your field could be final (or readonly, I'm not too familiar with C# but I guess it has something like that). The following constructor code also does not compile in Java if the monsters field is final:

doSomethingWithMonsters(monsters);
monsters = createMonsters();

Furthermore, having the array return value makes the code easier to read. It's obvious from the signature what the method does, readers don't have to check the method body to figure out its side-effects. Finally, you could call createMonsters() from other methods without side-effects.

Anyway, having the separate factory class (as a constructor parameter) looks even better, it's less coupled, +1 to Simon.

See also: Clean Code by Robert C. Martin, G31: Hidden Temporal Couplings, p302


Splits up two comma separated items, if they exist

Some quick remarks:

The class "Container" has a property named "Container"? That is... confusing, to say the least. Hence you having to name it item when iterating through it, which is unclear (and thus bad).
"Cointians" has two typos.
If you need to have a case insensitive Contains(), there are better ways to do it than use ToUpper(): https://stackoverflow.com/a/54686459/648075
Do not copy-paste logic when it is the same for two cases; instead move it to a method and call it.
Why is the property Amount a string instead of an int? Your code constantly needs to converts strings to ints and vice versa; why not use the proper types instead and avoid all that?
Is the Container of a Container always a comma-separated string of two items? Why then not make it a List<string> Names?

Most impotantly: due to the bad names, I have trouble figuring out what your code actually does.

That joinedDisposables is a list of Containers is unclear, and due to "Container" being both the name of a class as well as one of its properties the code becomes even more unclear.

I have the impression that once your Container class has a "proper" structure, much of this code can be replaced by simple LINQ queries; it's just that the bad names and the bad structures obfuscate so much it makes things hard to grasp.

To me it looks like public List<Container> Containers { get; set; } should be a Dictionary<string, int>, and that what you pass to SeperateJoinedDisposables should be a List<string> where each string is a comma separated list. And then your code would be something like this:

Dictionary<string, int> Containers = new Dictionary<string, int>();

private void Parse(List<string> commaSeparatedValues)
{
    foreach (var commaSeparatedValue in commaSeparatedValues)
    {
        foreach (var value in commaSeparatedValue.Split(','))
        {
            var normalisedValue = value.ToLower();

            if (!Containers.TryGetValue(normalisedValue, out int count))
            {
                count = 0;
            }

            count++;
            Containers[normalisedValue] = count;
        }
    }
}

To me this code expresses far more clearly the intent of what you're trying to do -- if I correctly understand the purpose of your code, of course.

But then I don't know where IEnumerable<Models.Container> joinedDisposables comes from and how it is constructed and why it is constructed that way, so I can only assume a "better" solution based on limited knowledge.


Type Hinting

You were halfway there! Good job having the type of values accepted and returned in the method docstring. Now, you can use type hints to show in the header of the method what values are accepted and returned, as follows

from typing import List

def snakes_and_ladders(board: List[List[int]]) -> int:

Consistent Spacing

This

for i in range(1,7):

should be this

for i in range(1, 7):

You have good spacing in the rest of your code, but you should stay consistent and apply this spacing everywhere.

The same for this line

stack.append([1,0]) -> stack.append([1, 0])

Magic Numbers

We're coming back to this line again

for i in range(1, 7):

What is 7 supposed to represent? The max number of rows or columns? What if you have to change it later on to apply to smaller/bigger snakes and ladders boards? I would advise using a variable to hold this value, naming it accordingly.

List Comprehension

You use lots of loops with one line in them. Particularly when appending to lists. Luckily, you can add two lists together and it will merge them.

From this

for col in range(cols):
    board_2.append(board[row][col])

to this

board_2 += [board[row][col] for col in range(cols)]

You can do the same for the next loop a couple lines down

From this

for col in range(cols - 1, -1, -1):
    board_2.append(board[row][col])

to this

board_2 += [board[row][col] for col in range(cols - 1, -1, -1)]


Find the nearest point of a given set of points (part 2)

Mostly this looks good.

  assign_box is used to build the bounding box or envelope

I benchmarked the speed of assign_box. Please see https://github.com/jhanley634/testing-tools/blob/master/problem/bench/min_of_copied_list.py#L104..L109 . It turns out one can compute a pair of min's / max's slightly faster:

0.017s  scan_manually_with_if
0.019s  scan_with_two_copies
0.030s  assign_box
0.049s  scan_with_key
0.078s  scan_manually_with_min_max

The first two scan approaches are faster than your code.

  find_min

A comment of # try 8 neighbors first would be more natural than 9, since distance won't be less when row & column offsets are zero.

  bruce_force

Maybe this is a Bruce Lee joke. I recommend renaming it def brute_force.

  distance is a utility method ...

I recommend renaming it def distance_squared, as it clearly does not compute Euclidean distance. It's only used in comparisons, and N^2 is monotonic w.r.t. N, so there's no harm done. But you should say what you mean, and mean what you say.


for crl in ${crls[@]}; do

It's a good habit to always double-quote array expansions.

Cleaning up the temp directory after a successful run would be a nice touch (or do away with it altogether; see below).

cat ${crl_temp}/*.pem > ${crl_temp}/${new_crl}
mv ${crl_temp}/${new_crl} ${crl_dir}/${new_crl}

I assume you're doing this to get atomic replacement?  It only works if /tmp and /etc are on the same filesystem.  If they're not, you could get an empty destination file when (for example) the target is full.  Consider creating a working directory under /etc to be certain.

You could be more concise using cd and brace expansion and bash's own error handling (via set -euxo pipefail):

set -euxo pipefail

cd /etc/pki/tls/misc
temp=$( mktemp -p . )

for url in http://…blahblah…/{RootCA,IntermediateCA,IntermediateCA2}.crl ; do
    curl $url | openssl crl -in - -inform DER
done > $temp
mv $temp newcrl.pem


Arcpy script to check for TIFF files and add them to different lists

You want to learn what a dictionary is, and store your rasters in it. With Python this is pretty simple, to make a dictionary that when you ask for an apple gives you a 'red apple' you could do:

>>> my_dictionary = {'apple': 'red apple'}
>>> my_dictionary['apple']
'red apple'

From this you want to build this dictionary, to do this you can add a banana to the dictionary:

>>> my_dictionary['banana'] = 'for scale'
>>> my_dictionary['banana']
'for scale'
>>> my_dictionary
{'apple': 'red apple', 'banana': 'for scale'}

After this you want to merge all the for loops together. Using a dictionary like above, we can drastically reduce the amount of code.

rasters = {}
for name, file_ext in [('CRP', '_CRP'), ('FOR', 'FOR'), ...]:
    list = rasters[name] = []
    for raster in arcpy.ListRasters("*" + file_ext + ".tif"):
        if arcpy.Exists(raster):
            CRP_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

Since you also want this to work when you loop through arcpy.ListWorkspaces("*") you can use collections.defaultdict to allow you to remove the need to create a list for each file extension. This would change the above to:

rasters = defaultdict(list)
for name, file_ext in [('CRP', '_CRP'), ('FOR', 'FOR'), ...]:
    list = rasters[name]
    for raster in arcpy.ListRasters("*" + file_ext + ".tif"):
        if arcpy.Exists(raster):
            CRP_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

Going further, you can use arcpy.env.workspace or another constant variable rather than writing "D:/A__P6_FINAL_TIFFs/" three times, this as if you want to change it you would have to do it twice at the moment. I would use str.format to simplify the formatting, so when another person reads it it's not as hard to know what's happening. And finally I would normalize your variable names, pick either CoName or co_name, as it's hard knowing what your variable naming convention is. This can get you:

import arcpy
import os
from collections import defaultdict

WORKSPACE = "D:/A__P6_FINAL_TIFFs"
arcpy.env.workspace = WORKSPACE

rasters = defaultdict(list)
for folder in arcpy.ListWorkspaces("*"):
    co_name = os.path.basename(folder).rsplit('_', 1)[0]
    env.workspace = os.path.join("{}/{}_FINAL".format(WORKSPACE, co_name))

    for name, file_ext in [('CRP', '_CRP'), ('FOR', 'FOR'), ...]:
        list = rasters[name]
        for raster in arcpy.ListRasters("*{}.tif".format(file_ext)):
            if arcpy.Exists(raster):
                list.append("{}{}_Final/{}".format(WORKSPACE, co_name, raster)


Your algorithm effectively combines two simple ciphers: a byte substitution cipher performed by XorByte(), and something that is similar in spirit to xoring with a poor-quality pseudo-random key stream (except for the minor difference due to the use of additive operators instead of xor for the combining step).

Calling XorByte() for each byte is wasteful; you get the same effect by calling XorByte(0, password) once, caching the result and xoring every byte with that. There's a lot more random stumblings in the dark like that. E.g.

int num002 = (session_id | i) >> (i + 1);

There's no need for oring i into the first operand since it will get shifted out completely anyway (unless operator >> implicitly performs a modulo op on its right operand, they way shift instructions do on Intel CPUs).

int index = getIndex(i, password.Length);
...
int num003 = function(i, session_key, password[index]);

This will crash if the input size approaches or exceeds three times the password size, because getIndex() returns half the arithmetic mean.

You tried to make your key stream generator look complex but it is actually very poor. As a result you have one simple cipher (byte substitution, indirectly defined by the password) on top of a complicated but still poor one.

This algorithm will be very safe as long as it doesn't protect anything of interest. As soon as it does, it will get torn to shreds.

Don't forget that your adversaries won't necessarily hobble themselves by using an application-glue language like C#; they could use C++, effectively load all cores of their processors, and process multiple streams on each core via vector instructions (MMX/SSE). Or they could get even more performance by offloading the stuff into their graphics cards (CUDA, OpenCL). IOW, cracking performance could exceed the performance of your own code by five to ten orders of magnitude, especially when combined with a bit of math fu.

Summary: if you randomly throw stuff in a pot then what you get is a right hash.

Post scriptum: Since there weren't any other takers for reviewing this code, a few more considerations and a bit more detail.

It is rarely a good idea to feed passwords and session ids directly into cryptographic computations, because their individual bits are usually not very random (regardless of whether they contain sufficient entropy or not). The standard way of dealing with this is to distill the entropy from password and session id by running them through a hash function (or, more precisely, to apply a password-based key derivation function like PBKDF2). This effectively spreads the entropy over all bits of the resulting hash, which makes it easier to use in further processing. As a first approximation - for testing and experiments - any good hash function will do, even the trusty old MD5 (still my favourite as a general hash function, even though it can't be used for strong crypto anymore).

As was said earlier, one part of the algorithm works pretty much like a stream cipher except for the use of additive operators for the combining step instead of xor. In the following I'll gloss over the resulting differences since they are insignificant, and using xor makes epxlanations easier.

An important consideration for stream ciphers is that key streams must never be reused. If two messages are encrypted with the same key stream then a simple xor of the two cipher texts yields the xor of the two plain texts. I.e.

P  ^ S = C
P' ^ S = C'
C ^ C' = (P ^ S) ^ (P' ^ S) = P ^ P'

A cryptanalyst (attacker) can glean lots of invaluable information from something like that, just like when unhashed passwords are fed directly into crypto algorithms.

Consequently, stream cipher keys must never be reused. That is usually accomplished by adding a salt or nonce when hashing the password to produce the session key; the nonce - which could be a simple counter, or a unique timestamp (i.e. a timestamp plus unique identifying information like machine, process id, thread id and so on), or both. The salt/nonce must be stored with the encryption header, since it is necessary for decryption.

Also, I strongly recommend encapsulating the whole key stream generation in its own class, so that it becomes easier to use and - most importantly - easier to put through rigorous testing independent of other parts. Such a class would yield the key stream byte for byte, and perhaps also in other convenient ways.

Using 'Soopr' as placeholder for the name of the as yet anonymous algorithm, a typical use for en/decipherment might look like this:

var session_key = SooprKDF(password, session_id, nonce);
var key_stream = new SooprKeyStream(session_key);
byte xor_byte = XorByte(0, session_key);

foreach (byte b in input)
   output = b ^ xor_byte ^ key_stream.next_byte();

An important quality indicator for cryptographic algorithms is diffusion. As a simple rule of thumb, flipping a single bit in the key material should affect every output bit with probability 50%. This applies not only to the algorithm as a whole, but most specifically to your key stream generator. Put in a different way: the output of your key stream generator should pass all standard quality tests for pseudo-randomness (most famous: Georgio Marsaglia's Diehard suite). Passing such tests is not sufficient for a good crypto algorithm, but it is necessary.

If you have your key stream generator as a separate class then you easily run some tests to get an impression of its diffusion capability. E.g. create a random session key, generate a number of key stream bytes, flip a bit in the session key, and generate the same number of key stream bytes again. Then you can count the bits that have flipped between the two stream samples.

Let your computer run a whole bunch of such random tests (with varying key stream sample lengths) - perhaps over night - and then look at how often each bit did flip for each key bit, separate per sample length. Every stream bit should have flipped about 50% of the time, for every sample length and every key bit. Tests like this make it easy to find unintended regularities that bleed through, like certain bits that never flip, or not often enough, or too often (which means they are correlated to certain parts of the key - something that shouldn't happen).


Reducing lock contention for a caching utility, or make it totally lockless but threadsafe

Definitely do not lock on the ConfigProxy instance. Somebody else could acquire a lock on it and then you'd be up the creek. Only lock on private instances that you have the only copy of.
Strictly speaking, you could use putIfAbsent and get rid of the lock altogether, but then you're potentially seeing multiple Redis calls for the same key. You should check both outside and inside the synchronized block to see if the key is there yet. If two threads both hit that barrier in the else, the first one will put a value in the map .. then the second one will go do it again. The first check keeps you out of the synchronized block, and the second one lets you exit it early.
I'm not entirely convinced that a Concurrent map buys you anything here, since you're managing the puts using synchronization. I might be wrong - there may be black magic around gets that I'm unaware of.
Random convention stuff - Java doesn't use underscores to indicate instance variables. Always use curly braces. Make everything final that you can.


transform columns to binary encoded columns in R

If we test on larger vector your approach is quite slow:
test_vec <- 1:1e5
system.time(v1 <- encode_binary(test_vec, name = "binary_x1_"))
#  user  system elapsed
# 22.23    0.08   22.37

Based on this SO question
I managed to write code that performs a lot faster:
encode_binary2 <- function(x, name = "binary_") {
  m <- sapply(x, function(x) rev(as.integer(intToBits(x))))
  tm <- t(m)
  # remove empty bit cols
  i <- which(colSums(tm) != 0L)[1]
  tm <- tm[, i:ncol(tm)]
  # save to data.frame
  d <- as.data.frame(tm)
  rownames(d) <- NULL
  colnames(d) <- paste0(name, 1:ncol(d))
  d
}

system.time(v2 <- encode_binary2(test_vec, name = "binary_x1_"))
# user  system elapsed
# 0.61    0.02    0.63

# test that results are equal:
all.equal(v1, v2)
# [1] TRUE


Reading in different datatypes from a file

This part hardly makes sense to me:

    player[idx].fullname[0] = malloc(20);
    player[idx].fullname[1] = malloc(20);
    player[idx].racketBrand = malloc(20);

If you are always allocating 20 bytes for your strings, why bothering with a dynamic allocation? Simply declare your strings as char whatever[20];. If you want your dynamically allocated strings to actually allocate as much memory as is needed, things will go far more complicated (see my old answer here, although you'll need to adapt it).

Your code does not allow for a tennis player to have more than one name and one surname, but I'll assume that this is on purpose. However, if we assume that your data file is not broken in a very specific way (i.e., having one player's data spread across more than one line), we could simply do this (assuming we also abandon dynamic memory allocation):

while (fscanf(file, "%19s %19s %d %lf %19s", player[idx].fullname[0], player[idx].fullname[1], &player[idx].age, &player[idx].rating, player[idx].racketBrand) == 5) idx++;

Unless there is a reason to assume that there are at most MAX_PLAYERS in the file, it would be better to dynamically allocate player (the main array), using realloc. This is, of course, more complicated than your attempt, but it is also less limiting for the user.

If you want to keep the limit on the number of players, you should also check it when reading the data, i.e., you should replace idx++ with

if (idx++ >= MAX_PLAYERS) break;

And a minor technical notion. You can replace

struct player {
    char *fullname[2];
    int age;
    double rating;
    char *racketBrand;
}; typedef struct player tPlayer;

with

typedef struct player {
    char *fullname[2];
    int age;
    double rating;
    char *racketBrand;
} tPlayer;

I am all for using typedef, but it is fair to warn you that there are some disagreements about it.


Circular Linked List implementation in C++

Design

With a singly linked list it is O(n) to find the end (assuming you store the beginning). So it is often nice to track both the beginning and end of the list inside the list object.

Personally I would have gone with a doubly linked list (next/prev). That way you can store just the head but finding the tail (on a circular list) is simply getting the link before the head.

// Head of a list
list->head

// Tail of a list (doubly linked)
list->head->prev;

Another thing you should consider is a sentinel link. This is a link in the list that does not contain data but is always there. Note: The list is empty when it only contains the sentinel element. The advantage to using a sentinel node is that you don't have to worry about nullptr when traversing the list. This drastically reduces the amount of code you need to write.

So from that long description two changes I would make.

Doubly linked list next/prev
Add a sentinel node.

Code Review

Move and Copy

I see you deleted the copy/move operations. Fine if you are still working through it. But in the end you will need to implement these. These are actually quite simple when you learn the tricks (idioms).

As a simple helpping hand:

circular_linked_list(const circular_linked_list& cll)
// This you need to implement in full.
// I leave the details to you (but a full deep copy of the list is needed).

// The assignment operator is easy.
// It is implemented in terms of the copy constructor.
// And the swap operation.
circular_linked_list& operator=(const circular_linked_list& cll)
{
    circular_linked_list    copy(cll);   // Make a copy.
    swap(copy);                          // Call the swap method.
    return *this;
    // Small improvement can be made (look up copy and swap idiom).
}

// Move is easily implemented using a swap.
circular_linked_list(circular_linked_list&& cll) noexcept // dont forget the noexcept
     // Dont forget to initialize the members correctly.
 {
     // Swapping implements the requirements of move.
     // It also provided deferred deletion (which is a nice side affect)
     // allowing potential reuse of memory. But usually the object
     // will be correctly and normally destroyed.
     // It also provides the strong exception guarantee.
     swap(cll);
 }

 circular_linked_list& operator=(circular_linked_list&& cll) noexcept
 {
     swap(cll);
     return *this;
 }

 void swap(circular_linked_list& other) noexcept
 {
     using std::swap;
     // Implement the swap of all members for other into this.
 }

 friend void swap(circular_linked_list& lhs, circular_linked_list& rhs)
 {
      lhs.swap(rhs);
 }

Don't need an explicit constructor here.

  struct Node
  {
    T data;
    Node * next;
    Node(T value) : data(std::move(value)), next(nullptr) {}
  };

If you use the brace initializer you don't need an explicit initializer as long as you use put the members in order.

  Node* node = new Node{ 12, nullptr };

But you may want to explore some alternative constructors.

  // copy Cosntruct node.
  Node(T const& value);        // Pass by const reference and copy in
  Node(T&& value);             // Pass by r-value ref and move in
  template<typename... P>
  Node(P&&... args);           // Pass using the arguments that constructor
                               // T allowing construction in place.

Printing

This is fine.

  void print_list();

But in C++ we usually print using the operator<<. So it is nice to define this operator for your class. Also std::cout is not the only stream you can print too (Files/Strings are two that pop out but lot of things are emulated like streams).

  void print_list(std::ostream& str = std::cout) const;
  friend std::ostream& operator<<(std::ostream& str, circular_linked_list const& data)
  {
       data.print_list(str);
       return str;
  }

Perfectly good search.

  struct Node *search(T value)
  {
    Node *node = head;
    while(node->next != head)
    {
      if(node->data == value)
        return node;

      node = node->next;
    }

But this may have been easier to write as a for loop:

    for(Node *node = head; node->next != head; node = node->next)
    {
      if(node->data == value) {
        return node;
      }
    }

Insert

Both insert operations have a lot of shared code.
It would be better if you factor out the shared code into a separate function.

As noted in the design section. The code can be highly simplified by using a sentinel node. Also the loop to find the end should be removed by either using an end marker in the list or by using a doubly linked list.

Quick exit from delete.

If this returns nullptr then is there any reason to continue?

  Node *node = search(value);

Lot of extra work in delete.
I don't think you actually need tail.

Bug in print.

If the list is empty then your print is going to hit several places where it de-references a nullptr.

Destructor can be simplified.

You only need to loop over the list once to delete it. You don't need to unlink the tail from the head to make it work. Comparing pointers will still work after a pointer has been deleted. You just can't de-reference it after deleting.

template <class T>
circular_linked_list<T>::~circular_linked_list()
{
    Node* last = nullptr;
    Node* next
    for(Node* loop = head; loop != last; loop = next) {
        last = head;
        next = head->next;
        delete loop;
    }
}


First of all, the parenthesis around LocalDateTime.now() are useless.

Now, let's see what we're really doing here:

return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));

We're creating a unique LocalDateTime each time, but I am assuming that you always use the same format, and therefore the DateTimeFormatter.ofPattern(format) object will always be the same.

I would recommend not creating a method for this and instead extract a constant for the format:

private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("ssmmHHddMMMuu");

And then each time you need it, you just do

LocalDateTime.now().format(FORMAT);

A method named getTodaysDateInFormat provides exactly the same information as the above piece of code, therefore the method does not really provide any additional value.

I don't consider LocalDateTime.now().format(FORMAT) as duplicated code. Or rather: I'm considering just as much code duplication as a call to getTodaysDateInFormat().


That is basically what promises, and monads in the general sense, do. If you take the abstraction one step forward, you can generalize the idea of a continuation into a monad interface (using the FantasyLand spec):

function Cont(run) {
  this.run = run
}

Cont.of = function(a) {
  return new Cont(function(next) {
    next(a)
  })
}

Cont.error = function(msg) {
  return new Cont(function(_, error) {
    error(msg)
  })
}

Cont.prototype.chain = function(f) {
  return new Cont(function(next, error) {
    return this.run(function(a) {
      return f(a).run(next, error)
    }, error)
  }.bind(this))
}

Now your functions would have to return objects in that monad:

var msg = 'hello'
var msgErr = 'some error'

function f1(a) {
  console.log('f1', a === msg)
  return Cont.of(a)
}

function f2(a) {
  console.log('f2', a === msg)
  return Cont.error(msgErr)
}

// won't execute
function dummy() {
  console.log('dummy')
}

Then you can chain the continuations, and run the final computation, providing a callback for the success case, and an optional callback for the error case:

var chain = f1(msg).chain(f2).chain(dummy)

// chain.run(success, error)
chain.run(console.log, console.log)
// f1, true
// f2, true
// some error

Once you have this in place you can abstract regular callback-based functions to use the monad:

var cc = function(f) {
  return function() {
    var args = Array.prototype.slice.call(arguments)
    var cb = f.bind.apply(f, [null].concat(args))
    return new Cont(function(next, error) {
      cb(function(err, value) {
        if (err) return error(err)
        next(value)
      })
    })
  }
}

function f1(a, cb) {
  console.log('f1', a === msg)
  cb(null, a)
}

function f2(a, cb) {
  console.log('f2', a === msg)
  cb(msgErr)
}

var chain = cc(f1)(msg).chain(cc(f2)).chain(cc(dummy))

chain.run(console.log, console.log)
// f1, true
// f2, true
// some error

Of course you could apply cc as a decorator, instead of inline:

var f1 = cc(function(a, cb) {
  console.log('f1', a === msg)
  cb(null, a)
})

var f2 = cc(function(a, cb) {
  console.log('f2', a === msg)
  cb(msgError)
})


window.innerWidth - workaround for when it returns the wrong value

I have never seen innerWidth or innerHeight report the wrong value. There are a few bugs listed for chrome and firefox but they are all closed.
Could you provide any evidence?
UPDATE
Media query matches down to fractions of a CSS pixel while innerWidth returns integer CSS pixel values. This is a problem when devicePixelRatio !== devicePixelRatio | 0
I tried to find a cover all solution, but too much time need to complete so I withdraw the answers content.


Improving time complexity of cheapest travel route algorithm

I find it a little bit confusing that the title of your question doesn't seem to match its content. That is, you mention you're looking for the cheapest route, and your code sort of references fares, but your algorithm is a BFS that pays no attention whatsoever to the costs.

That said, the question you actually asked has a fairly simple answer. Change this bit of code:

if (!stationsExplored.contains(adjacentStation.getKey()) && !stationsUnexplored.contains(adjacentStation.getKey())) {
    stationsUnexplored.add(adjacentStation.getKey());
}

To this:

if ( !stationsExplored.contains(adjacentStation.getKey()) ) {
    stationsUnexplored.add(adjacentStation.getKey());
    stationsExplored.add(adjacentStation.getKey());
}

You'll also have to add a stationsExplored.add(1) around the top and you should remove the stationsExplored.add(currentStation) from the bottom. (That was wrong anyway I think. It ought to have been currentStation.getKey())

All you want is to add everything to the Queue exactly once, and this accomplishes that just as well as what you had before. It doesn't matter to your code if you mark the station as explored as soon as you add it to your Queue or if you wait until you pop it off, and by adding it early, you allow yourself to use only the faster Set contains method.