Any simpler and more efficient way of writing this code? I've noticed I've got quite a few repeated lines in my code.

$start = mktime(0, 0, 0, 3, 1, 2014);
$rate = 1 / 30;
$amount = number_format(floor((time() - $start) * $rate));

$id = array(
    array("42706686", "rebel2america"),
    array("100004055720670", "marquez.candace"),
    array("100000756492404", "vince.goode.3"),
    array("100007763585373", "laura.allen.75491"),
);

// 70% chance of red an 30% of green
$status = array(
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("green", "yes"),
    array("green", "yes"),
    array("green", "yes")
);

$online = range(7, 21);

// create and assign a 'seed' value that changes
// every $duration and assign to mt_srand
$duration = 5;
$mins = date('i', strtotime('now'));
$seed = $mins - ($mins % $duration);
mt_srand($seed);

// use mt_rand to build an 'order by'
// array that will change every $duration
$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($id)));

// sort $ids against $orderBy
array_multisort($orderBy, $id);

$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($status)));
array_multisort($orderBy, $status);

$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($online)));
array_multisort($orderBy, $online);

for($i = 0; $i < 10; $i++) {
    $results1 = array_pop($id);
    $results2 = array_pop($status);
    echo "                            {$results1[0]}	\n";
    echo "                            {$results1[1]}	\n";
    echo "                            {$results2[1]}	\n";
}

This part is duplicated:

$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($id)));
array_multisort($orderBy, $id);

You apply the same logic to $id, $status, $online.

To eliminate duplication, you can move this common logic to a function with one parameter:

function reorder(&$arr) {
    $orderBy = array_map(function() {
        return mt_rand();
    }, range(1, count($arr)));
    array_multisort($orderBy, $arr);
}
reorder($id);
reorder($status);
reorder($online);

Note that we pass the array by reference (&$arr), because array_multisort does the same, and modifies the content of the array anyway.

UPDATE

As other answers and comments have pointed out, you could also eliminate the magic numbers and duplication when creating the $status array, for example like this:

$color1 = array("red", "no");
$color2 = array("green", "yes");
$num_color1 = 7;
$num_color2 = 3;
$status = array_fill(0, $num_color1, $color1)
          + array_fill($num_color1, $num_color2, $color2);


Easily registering WordPress custom post types and taxonomies I am developing a library to easily register WordPress custom post types and taxonomies.

But the problem is I can't use one instance of object because of adding the object in WordPress hooks.

So what I have done as a solution is to re instantiate the class every time when you want to register a custom post type. Is that okay according to the modern PHP development?

 /**
     * @return PostType
     */
    public static function getInstance(){
        // don't need singleton due to wordpress hooks :( sadly i need to learn wp more.
        return new PostType();
    }

    /**
     *
     */
    public function register(){
        // Hook into the 'init' action
        add_action( 'init', array($this,'hookInWordPress'), rand() );
    }

    /**
     * callback of hook in init action
     */
    public function hookInWordPress(){
        $this->toSlug();
        if($this->newTaxonomy){
            $tax = $this->newTaxonomy->register($this);

            $this->addTaxonomy($tax->slug);
        }
        $args = $this->buildArgs();
        $args['labels'] = $this->buildLabels();
        if($this->icon) {
            $args['menu_icon'] = $this->icon;
        }

        register_post_type( $this->slug, $args);
        flush_rewrite_rules();
    }

Full project on GitHub

Of course it's ok. You will have 1 object per post type. GetInstance is called factory method.
I have noticed two strange things in your code:

PostType.php Line 116

Why do you use random here? It will be ok if you leave default priority param.

PostType.php Line 123
You call toSlug function before slug usage but it's better to call it when name was setted up here PostType.php Line 380

This way you will never forgot to call toSlug before slug usage.


SqlConnection Transaction Management Approach I am currently working on a SharePoint 2013 project with custom application pages development. On one of those pages, there are multiple insert / update to database table operations. Here are the sample code I am working with:

Product.cs

class Product
{
    public int ProductId { get; set; };
    public string ProductName { get; set; };
}

Here is the helper class which handle CRUD of products:

ProductFacade.cs

class ProductFacade
{
    public static Product Save(Product productObject)
    {
        Product product;
        using(SqlConnection conn = new SqlConnection(DatabaseHelper.ConnectionString)) // The connection string is retrieved from other helper class
        {
            SqlCommand cmd = new SqlCommand("SaveProduct", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            conn.Open();

            // Parameters setting and execute query operations here..
        }
        return product;
    }
}

In the application pages, I used the method like:

ApplicationPage.aspx.cs

public void SaveProducts()
{
    try
    {
        DataTable products = (DataTable)ViewState["Products"];
        if(products != null)
        {
            Product product;
            foreach(DataRow row in products.Rows)
            {
                product = new Product();
                product.ProductName = row["ProductName"].ToString();
                ProductFacade.Save(product);
            }
        }
    }
    catch(Exception ex)
    {
        LogHelper.WriteLog(Category.Unexpected, "Product Application Page", ex.Message + ", " + ex.StackTrace);
    }
}

All of the methods in that helper class work fine. But I am curious, how if I want to add transaction management, for example, if I want to add BeginTransaction, Commit, and Rollback operation on the above SaveProducts() method? Should I create and pass the SqlConnection object as a parameter to the ProductFacade.Save() method so it will be something like:

ProductFacade.cs

class ProductFacade
{
    public static Product Save(Product productObject, SqlConnection conn = null, SqlTransaction tran = null)
    {
        Product product;
        if(conn == null)
            conn = new SqlConnection(DatabaseHelper.ConnectionString);
        using(SqlCommand cmd = new SqlCommand("SaveProduct", conn))
        {
            if(tran != null)
                cmd.Transaction = tran;
            // The rest of the same code from before
        }
    }
}

And call the method with SqlConnection object passed like:

ApplicationPage.aspx.cs

public void SaveProducts()
{
    using(SqlConnection conn = new SqlConnection(DatabaseHelper.ConnectionString))
    {
        conn.Open();
        SqlTransaction transaction = conn.BeginTransaction();
        try
        {
            DataTable products = (DataTable)ViewState["Products"];
            if(products != null)
            {
                Product product;
                foreach(DataRow row in products.Rows)
                {
                    product = new Product();
                    product.ProductName = row["ProductName"].ToString();
                    ProductFacade.Save(product, conn, transaction);
                }
            }
            transaction.Commit();
        }
        catch(Exception ex)
        {
            transaction.RollBack();
            LogHelper.WriteLog(Category.Unexpected, "Product Application Page", ex.Message + ", " + ex.StackTrace);
        }
    }
}

Really appreciate any thoughts on this.

Don't add a the parameters to the save method. It adds unnecessary complexity to the api and it makes it a leaky abstraction because it forces knowledge of the underlying data store onto consumers.

Add a SaveAll method to your repository (why is it called a Facade?)

public static Product SaveAll(IEnumerable<Product> products)
{
    using (var scope = new TransactionScope())
    using (var conn = new SqlConnection(DatabaseHelper.ConnectionString))
    {
        conn.Open();
        foreach (var product in products)
        {
            Save(product, conn);
        }
        scope.Complete();
    }
}

// Used by both public `Save` and public `SaveAll`.
private static Product Save(Product product, SqlConnection conn)
{
    using (var cmd = conn.CreateCommand("SaveProduct"))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        // etc.
    }
}

I haven't written raw ADO.Net code for several years so I apologise if the above is massively incorrect. You should explore a product like Entity Framework (full ORM) or Dapper (more lightweight) to simplify a lot of this repetitive code.


Allowing googlebot to crawl a password protected page The below I have put together as an experiment, I have profiles on my site that are password protected. I would still like them to be crawled by google.

The script is taken from here and basically does a reverse dns lookup to verify if a googlebot is real or fake. I am then using this logic to allow google entry to my dynamic page by skipping the 'restrict-access.php' include which checks to see if someone is logged in or not.

My question is..
1. Is this viable?  2. is the code solid/safe?

<?php
function validateGoogleBotIP($ip)
{
    $hostname = gethostbyaddr($ip); //"crawl-66-249-66-1.googlebot.com"
    return preg_match('/\.googlebot\.com$/i', $hostname);
}
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Google') !== false) {
    if (validateGoogleBotIP($_SERVER['REMOTE_ADDR'])) {
        // its google - let them in
    } else {
        exit('You are not authorised to view this page');
    }
} else {
    require_once('php-includes/restrict-access.php');
    if (isset($_GET['user_id'])) {
        if (!ctype_digit($_GET['user_id']))
            exit('You are not authorised to view this page');
    } else {
        exit('You are not authorised to view this page');
    }
}
?>

Is this viable

Of course it is viable but as I am pretty sure somehow everyone can fake a googlebot without a detection by your script I don't recommend it. Another aspect is mentioned by 200_success. Google policies dislike such behaviour and it is highly recommend to follow their recommendations. At the end of the answer is a sample of my idea of implementation

Is this code solid/safe

General

It looks like you are developing procedural which is not recommend. OOP (object orientend programming) is the better way to go as it is a modular approach of developing software. In oop there are classes and each has specific task to solve. Wikipedia - Object-oriented-programming

Closing php tag

In the embedded source code you close the php tag which is not recommend. It might happen that a space is after a closing php tag and if you receive a headers already sent error it can be time consuming to identifiy the file where a space is after a closing php tag.

My idea of implementation

Independent of the google policies and that only x of y details should be indexed I would not make a google check but display the x of y details always and the z of y only if a function (e.g. userHasAccess($userid); ) returns true.

Sample

<!DOCTYPE HTML>

        <title>Detail</title>
        <meta name="robots" content="index">

User: John Doe

            A description about John Doe.

        <?php
            if (userHasAccess(2))
            {
                echo "
Age: 18
";
            }
        ?>

Such an implementation allows other search engines to crawl the x of y details while the z of y details are hidden for every search engine. You don't have to implement a googlebot verfication either.

Of course this sample has to be extended.


Finding complementary pairs I've read the docs online explaining Log N and I do understand that the basic concept of it, but I'm still not sure I've managed to nail it.

  The problem

  This exercise is called "Complementary Pairs" and given an array A
  and an integer K, how many pairs of A, sum to K.

  For example, with this input:

k = 6 a = [1, 8, -3, 0, 1, 3, -2, 4, 5]

  we would have 7 possibilities, like i, j = (5, 5) to add 3 + 3, then the
  pairs that add 1 + 5 (and the reverse), etc.

  Naive solution

  A first very naive solution is to for a \$O(N^2)\$ complexity
  loop where you just bluntly search the array in two nested loops.

\$N * Log N\$ Solution

From my understanding a proper \$Log N\$ solution has to include a binary search like quicksort or mergesort, so I applied a divide and conquer algorithm where I split the array in two, until it's down to one element, then I assemble back again, and I for a \$N*N\$ search on array, checking which elements of the first added with the second add to constant K.

Although this is very similar to mergesort, it just doesn't feel a \$N * Log N\$ solution, because the worst case, the last recursion step, I'm doing \$N/2 * N/2\$ and for me that's just \$N*N\$ over time.

Here is the working solution:

var complementary_pairs = function (input, k) {

  // Base scenario
  if (input.length == 1) {
    return input[0] * 2 == k ? 1 : 0
  }

  // Recursion
  var middle = Math.ceil(input.length / 2)
    , firstArray = input.slice(0, middle)
    , secondArray = input.slice(middle)

  var count = complementary_pairs(firstArray, k)
    + complementary_pairs(secondArray, k)

  // Problem condition
  for (var i = 0; i < firstArray.length; i++) {
    for (var j = 0; j < secondArray.length; j++) {
      if (firstArray[i] + secondArray[j] == k) {
        count += 2
      }
    }
  }

  return count

}

console.log(complementary_pairs([1, 8, -3, 0, 1, 3, -2, 4, 5], 6))

This is not O(n log n) algorithm, because this part is quadratic:

  for (var i = 0; i < firstArray.length; i++) {
    for (var j = 0; j < secondArray.length; j++) {
      if (firstArray[i] + secondArray[j] == k) {
        count += 2
      }
    }
  }

Denoting n = input.length, this has roughly (n/2)^2 = n^2/4 steps, which is O(n^2).

The rest of this answer is a result of a misread and is not directly related to the question. I'll leave it as a comment of a possibly extended exercise.

However, I'm not sure that O(n log n) algorithm does exist. Consider

a = [ 1, 2, 4, 8, ..., 2^n ] (for some n)

and k is a sum of all elements in a. Since you can repeat the numbers, and a[k] = 2*a[k-1] for all positive k, you'd have exponential number of sums, so no O(n log n) algorithm will solve this.

It is easy to show that the number of solutions is strictly bigger than 2^n. Just note that

k = (sum of ANY elements in a except a[0] = 1) + (sum of the remaining elements in a) * 1.

The first sum can be chosen in 2^n ways. Of course, there are other sums as well, but this is enough to show that you can have an exponential number of solutions, which is enough to show that no sub-exponential algorithm can find them all.

Of course, there may be a mathematical trick to compute only how many such solutions there are, but I don't know it.


Writing XML in C# from defined schema I'm creating an XML from a defined schema I need to follow.

This is my code:

using (XmlWriter writer = XmlWriter.Create(desktopPath + "\fatt.xml", settings))
{
  writer.WriteStartDocument();

  #region FatturaElettronicaHeader 1

  writer.WriteStartElement("FatturaElettronicaHeader");

  #region DatiTrasmissione 1.1
  writer.WriteStartElement("DatiTrasmissione");

  var statoAnag = statiRep.GetId(anagraficoCliente.stato);

  writer.WriteStartElement("IdTrasmittente");
  writer.WriteElementString("IdPaese",statoAnag.codice_iso);
  writer.WriteElementString("IdCodice",anagraficoCliente.codice_fiscale);
  writer.WriteEndElement();

  writer.WriteElementString("ProgressivoInvio", "0");
  writer.WriteElementString("FormatoTrasmissione",FORMATO_TRASMISSIONE);

  writer.WriteElementString("CodiceDestinatario",codiceSdi);

  writer.WriteElementString("PECDestinatario","prova@pec.it");
  writer.WriteEndElement();

  #endregion DatiTrasmissione 1.1

  #region 2
  ....
  #endregion 2

  writer.WriteEndDocument();
}

Basically I just have to read data from my db and then put in a xml file.

It works fine but I think is not really readable even if I used a lot of region to tidy up code.

What can I do to improve my code ? If there's any

When I had to create an XML file for one of my projects, I basically created a class for each element and passed along a class that contained all the data I needed to use in the XML.

It started with this class:

internal sealed class XmlCreator
{
    public static XElement Execute(RequestConfig requestConfig)
    {
        return ImportElementCreator.Execute(requestConfig);
    }
}

Which in turn used this class:

internal sealed class ImportElementCreator
{
    public static XElement Execute(RequestConfig requestConfig)
    {
        var element = new XElement("Import");

        element.Add(PersElementCreator.Execute(requestConfig));

        return element;
    }
}

etc etc etc. I'm sure you get the point.

Part of the reason was that the resulting XML file could differ, depending on the action in the request: an "Update" required more data than a "Delete", and thus some classes contained some logic:

    public static XElement Execute(RequestConfig requestConfig)
    {
        var element = new XElement("Access-Rule",
            new XAttribute("id", requestConfig.Position ?? 1),
            new XAttribute("operation", requestConfig.RequestType.ToString().ToLowerInvariant())
            );

        if (requestConfig.RequestType != RequestType.Update)
        {
            return element;
        }

        element.Add(RuleElementCreator.Execute(requestConfig.AccessRuleId));

        element.Add(StartDateElementCreator.Execute(requestConfig.StartDate));

        element.Add(EndDateElementCreator.Execute(requestConfig.EndDate));

        return element;
    }

The downside is that you might end up with a lot of small classes if you have a complicated XML file, and that you need to look out for duplicate class names.

Of course, if you look at XmlCreator, you end up with an XElement, not an XML file.

To actually write the XML file, I had this:

internal sealed class FileWriter
{
    private readonly string _localDirectory;
    private readonly XmlWriterSettings _xmlWriterSettings;

    public FileWriter(string localDirectory)
    {
        _localDirectory = localDirectory;

        _xmlWriterSettings = new XmlWriterSettings
        {
            Indent = true,
            OmitXmlDeclaration = false,
            Encoding = _idTechConfiguration.Encoding
        };
    }

    public string Execute(RequestConfig requestConfig, XElement content)
    {
        var xmlDirectory = Path.Combine(_localDirectory, "xml");
        Directory.CreateDirectory(xmlDirectory);

        var filePath = Path.Combine(xmlDirectory, GetFileName(requestConfig));
        using (var xmlWriter = XmlWriter.Create(filePath, _xmlWriterSettings))
        {
            content.WriteTo(xmlWriter);
        }

        return filePath;
    }

    private string GetFileName(RequestConfig requestConfig)
    {
        return string.Format("{0}_{1}_{2}_{3}_{4}.xml",
            requestConfig.ApplicationName,
            requestConfig.RequestType,
            requestConfig.UserData,
            DateTime.Now.AsYyyyMmDdDashed(),
            DateTime.Now.AsHhMmSsDashed());
    }
}


Parse a config-file and add to command-line-arguments using argparse in Python I am trying to parse the command line arguments using argparse, and if the user specifies a yaml file for the config-file, add those arguments to the args from argparse

import argparse
import yaml
from pprint import pprint

class CLI(object):

    def execute(self):
        self.create_parser()
        self.options = self.parse_args()
        pprint(self.options)

    def create_parser(self):
        self.parser = argparse.ArgumentParser()

        g = self.parser.add_argument_group('Device Targets')
        g.add_argument(
            '--config-file',
            dest='config_file',
            type=argparse.FileType(mode='r'))
        g.add_argument('--name', default=[], action='append')
        g.add_argument('--age', default=[], action='append')
        g.add_argument('--delay', type=int)
        g.add_argument('--stupid', dest='stupid', default=False, action='store_true')

    def parse_args(self):
        args = self.parser.parse_args()
        if args.config_file:
            data = yaml.load(args.config_file)
            delattr(args, 'config_file')
            for key, value in data.items():
                if isinstance(value, list):
                    for v in value:
                        getattr(args, key, []).append(v)
                else:
                    setattr(args, key, value)
        return args

cli = CLI()
cli.execute()

If my config-file has the following data:

name: [Jill, Bob]
age: [21, 33]
delay: 30

And I run my code like this:

python test.py --conf args.txt --name 'Mark'

I get this for the output:

Namespace(age=[21, 33], delay=30, name=['Mark', 'Jill', 'Bob'], stupid=False)

So, it works, but is it good code?

You don't need a class

In your current version of the code, it is hard to see what is stored in an instance and how the data flows around the different methods. If you do write a class, I find it clearer to have an init to define the different members but in your case, you could stop writing classes.

Removing the class, you get something like :

def execute():
    pprint(parse_args(create_parser()))

def create_parser():
    parser = argparse.ArgumentParser()

    g = parser.add_argument_group('Device Targets')
    g.add_argument(
        '--config-file',
        dest='config_file',
        type=argparse.FileType(mode='r'))
    g.add_argument('--name', default=[], action='append')
    g.add_argument('--age', default=[], action='append')
    g.add_argument('--delay', type=int)
    g.add_argument('--stupid', dest='stupid', default=False, action='store_true')
    return parser

def parse_args(parser):
    args = parser.parse_args()
    if args.config_file:
        data = yaml.load(args.config_file)
        delattr(args, 'config_file')
        arg_dict = args.__dict__
        for key, value in data.items():
            if isinstance(value, list):
                for v in value:
                    arg_dict[key].append(v)
            else:
                arg_dict[key] = value
    return args

execute()

The name execute probably needs to be improved for something more meaningful.

The right tool for the job

To add all the content from value to arg_dict[key], you shouldn't use àppend but extend.

        if isinstance(value, list):
            arg_dict[key].extend(value)
        else:
            arg_dict[key] = value


DbGeography calculation Given the following piece of code, can it be done better:

public object DistanceFrom(
    IEnumerable<Coordinate> coordinates) {
    IEnumerable<DbGeography> addresses = coordinates.Select(
        c =>
            DbGeography.FromText(String.Format("POINT ({0} {1})", c.Longitude, c.Latitude)));
    IEnumerable<VehicleGeography> vehicles = this.GPSInsightProvider.Query().Document.Placemarks.Select(
        p =>
            new VehicleGeography {
                DriverName = p.DriverName,
                Point = DbGeography.FromText(String.Format("POINT ({0} {1})", p.Point.Longitude, p.Point.Latitude))
            });
    ICollection<object> technicians = new List<object>();

    foreach (DbGeography address in addresses) {
        technicians.Add(vehicles.Select(
            v =>
                new {
                    DriverName = v.DriverName,
                    Distance = v.Point.Distance(address) / 1609.344
                }).Where(
            v =>
                v.Distance.HasValue).OrderBy(
            v =>
                v.Distance).Take(3).Select(
            v =>
                new {
                    DriverName = v.DriverName,
                    Distance = String.Format("{0:#.#}", v.Distance)
                }));
    }

    return technicians;
}

GPSInsightProvider parses a KML and returns its object representation. I then take that and convert it temporarily into a VehicleGeography so I can create a DbGeography property for it. I then loop through the addresses I'm checking against and the do a dirty-looking calculation to see which are the closest three vehicles to the address. At most I will be doing this for a maximum of three addresses at a time. I take the resulting object and return it as JSON to my web application.

I'm curious if there's a better way to perform that whole lookup/calculation/whatever-this-is?

Firstly, I really don't like your indentation, particularly with the method header, so I've pasted into Visual Studio and will be working from the code as it appears below:

    public object DistanceFrom(IEnumerable<Coordinate> coordinates)
    {
        IEnumerable<DbGeography> addresses = coordinates.Select(c =>
            DbGeography.FromText(String.Format("POINT ({0} {1})", c.Longitude, c.Latitude)));
        IEnumerable<VehicleGeography> vehicles = this.GPSInsightProvider.Query().Document.Placemarks.Select(p =>
            new VehicleGeography
            {
                DriverName = p.DriverName,
                Point = DbGeography.FromText(String.Format("POINT ({0} {1})", p.Point.Longitude, p.Point.Latitude))
            });
        ICollection<object> technicians = new List<object>();

        foreach (DbGeography address in addresses)
        {
            technicians.Add(
                vehicles
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = v.Point.Distance(address) / 1609.344
                        })
                    .Where(v =>v.Distance.HasValue)
                    .OrderBy(v =>v.Distance)
                    .Take(3)
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = String.Format("{0:#.#}", v.Distance)
                        }));
        }

        return technicians;
    }

My first question: Why does this return an object? I'm strongly against returning anonymous types, you really should be creating a class or struct for this data combination. Secondly, you know that at the bare minimum, it returns a List of these anonymous types, so at the least your should return a List<object>

Secondly:

ICollection<object> technicians = new List<object>();

Why are you specifically reducing the functionality that you're returning? Require least on parameters, return most.

Use var on variable declarations where the right-hand-side makes the type obvious. This saves you extra typing when you want to change that variable's type later.

e.g.

ICollection<object> technicians = new List<object>();

becomes

var technicians = new List<object>();

Is there a special reason you return only the top 3 results from your query? If so, that magic number should be a const somewhere with a reasonable name. If not, it should be a variable somewhere, again with a reasonable name.

The same goes for 1609.344. I'm guessing that's a conversion from meters to miles, but it doesn't make a ton of sense on its own.

I think your LINQ is doing a little bit too much. I'd recommend splitting it up a bit so it's clearer what it's doing. Afterall, you're already looping through addresses, so split it up a little.

            technicians.Add(
                vehicles
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = v.Point.Distance(address) / 1609.344
                        })
                    .Where(v =>v.Distance.HasValue)
                    .OrderBy(v =>v.Distance)
                    .Take(3)
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = String.Format("{0:#.#}", v.Distance)
                        }));

maybe becomes

            var vehiclesByDistance =
                vehicles
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = v.Point.Distance(address) / 1609.344
                        })
                    .Where(v =>v.Distance.HasValue)
                    .OrderBy(v =>v.Distance);

            technicians.Add(
                vehiclesByDistance
                    .Take(3)
                    .Select(v =>
                        new
                        {
                            DriverName = v.DriverName,
                            Distance = String.Format("{0:#.#}", v.Distance)
                        }));

Finally, I'm pretty sure your LINQ is breaking the Single Responsibility Principle. It appears to be performing distance unit conversion, sorting and formatting. It might be wise to split this up a bit.


Evaluating a series of Legendre polynomials The following function represents the electrostatic potential, in spherical coordinates, due to a ring of charge \$q=1\$ and radius \$R=1\$, placed in the plane \$x\$-\$y\$:

$$\phi(r,\theta) = \sum_{n=0}^\infty \frac{r_\min^n}{r_\max^{n+1}} P_n(\cos\theta) P_n(0) $$

where \$P_n\$ are the Legendre Polynomials of degree \$n\$, \$r_\min = \min(r,1)\$, and \$r_\max = \max(r,1)\$.

I wrote a code in python to plot this function, with the sum truncated to \$0\leq n \leq 35\$, in a cartesian grid of 50x50 points. But this takes several minutes to complete. The same code in other languages gives almost instantaneous results in mi computer.

This is the code I want to improve:

import matplotlib.pyplot as plt         # plotting routines
import scipy.special as sp              # legendre polynomials
import numpy as np
from timeit import default_timer as timer

# Potential from a ring of radius c=1 and charge q=1
#    phi(r,th) = \sum_{n=0}^\infty (rmin^n/rmax^{n+1}) P_n(cos(th)) P_n(0.0)
#
# where rmin=min(r,1) and rmax=max(r,1).
# The potential is normalized with respect to q/c, where q is the charge of the ring.
# The radii is normalized with respect to c.

def phi(x, z):
    r = np.sqrt(x**2 + z**2)
    costh = z/r

    rmin = min(r,1)
    rmax = max(r,1)

    dr = rmin/rmax

    suma = 0.0
    for n in range(0,35):
        suma += dr**n * sp.legendre(n)(costh) * sp.legendre(n)(0.0)

    return suma/rmax

phivec = np.vectorize(phi)

# grid for plotting
X, Y = np.meshgrid( np.linspace(-2,2,50),
                    np.linspace(-2,2,50) )

# evaluating phi(X,Y)
start = timer()

Z = phivec(X,Y)

end = timer()
print "time = ", end-start

# plotting phi
plt.figure()
CS = plt.contour(X, Y, Z)
plt.clabel(CS, inline=1, fontsize=10)
plt.title(r'$\psi(r,\theta) = \sum_{\ell=0}^\infty \frac{r_<^\ell}{r_>^{\ell+1}} P_\ell(0) P_\ell(\cos\theta)$', y=1.03)
plt.xlabel(r'$x/c$', fontsize=20)
plt.ylabel(r'$z/c$', fontsize=20)

plt.show()

Here is the result:

Compute legendre(n) once per loop iteration instead of twice.
Use np.hypot instead of np.sqrt(x**2 + z**2).
Don't use phivec, just pass the arrays X and Y directly to phi, which is already almost vectorized. The only change that's needed is to use np.minimum and np.maximum instead of min and max respectively.

Revised code:

def phi(x, z, nlimit=35):
    r = np.hypot(x, z)
    costh = z / r
    rmin = np.minimum(r, 1)
    rmax = np.maximum(r, 1)
    dr = rmin / rmax
    suma = 0.0
    for n in range(nlimit):
        Ln = sp.legendre(n)
        suma += dr**n * Ln(costh) * Ln(0.0)
    return suma / rmax

X, Y = np.meshgrid(*[np.linspace(-2, 2, 50)] * 2)
Z = phi(X, Y)

I find that this takes about 0.05 seconds, which ought to be fast enough for you.


A game called Bocce played on a Cartesian grid You may know Bocce, so you should know that I've tweaked the rules a little. Three types of balls are thrown: a red type, a blue type, and single black ball called the jack.

These are all on the Cartesian coordinate system. The coordinates of the jack are given, and also distances of an equal amount of red and blue balls from the origins of the system (0, 0). If a ball's distance is larger than the distance of the jack, and if the distance of this ball is larger than the distance of its peer, it's a score. The team with the highest score wins.

Here's the code:

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <cmath>
#include <array>
#include <algorithm>

typedef std::map<std::string, std::vector<int>> bocce_balls;
typedef std::vector<int> int_vec;
typedef std::array<int, 2> int_arr;

std::string bocce(bocce_balls balls, int_arr jack)
{
    auto distance = std::sqrt(std::pow(jack[0], 2)+std::pow(jack[1], 2));
    int red_count = 0;
    int blue_count = 0;

    int_vec red = balls["red"];
    int_vec blue = balls["blue"];

    if (blue.size() != red.size())
    {
        std::cerr << "Balls were different numbers!" << std::endl;
        return "Fail!";
    }

    std::sort(blue.begin(), blue.end());
    std::sort(red.begin(), red.end());

    for (int i = 0; i < blue.size(); ++i)
    {
        if (red[i] > distance && red[i] > blue[i])
            ++red_count;
        else if (blue[i] > distance && blue[i] > red[i])
            ++blue_count;
    }

    if (red_count > blue_count)
        return "Red Wins!";
    else if (blue_count > red_count)
        return "Blue Wins!";
    else
        return "Draw!";

}

int main() {

    bocce_balls insert;
    insert["blue"] = {2, 9, 3, 4, 5, 1, 10, 2};
    insert["red"] = {20, 11, 3, 4, 3, 1, 2, 3};
    int_arr dist = {2, 2};

    std::cout << bocce(insert, dist) << std::endl;
    return 0;
}

Bocce, as far as I know it, counts all the balls of one player that are closer to the jack than the closest one of his opponent.

That would mean that the distances from origin are irrelevant, instead, you need the distances from the balls to the jack:

auto dx = ball.x - jack.x;
auto dy = ball.y - jack.y;
auto distance2 = dx*dx + dy*dy;

Note that I avoided std::pow in favour to multiplying with itself, as std::pow inefficient for this purpose.

Note, too, that as the root function is strictly monotonely rising, you don't need to calculate it, but you can compare the squares as well and still will get the same results.

I personally strongly recommend that you create a class Ball containing three members: x, y for the coordinates and distance for the distance to jack:

class Ball
{
     int x, y;
     int distanceToJack2;
};

I'm not too happy with int as data type - it depends on the range of valid coordinates, though, if it is suitable or not. Assuming we have 32-bit int, then if the valid ranges for x and y can be covered with 16 bit, you will be safe from overflow while multiplying (this would yield undefined behaviour!), otherwise you'd need to calculate in next larger data type. For selecting the correct data types more safely, you might prefer the data types from <cstdint> header, e. g.:

 int32_t x, y;
 int64_t distanceToJack2;

Or you simply have coordinates and distance in double right away. Be aware that with double, you can quickly get issues due to rounding, so if you compare for one value being less than the other, you should consider them only so if difference is larger than some yet to be defined epsilon value (minimum distance for two values for not considering them equal). You could get some hints to from this question. Sure, it is java, but as long as both C++ and Java follow IEEE 754 for floating point values, it applies for both languages equally. On the other hand, you could then use std::hypot for calculating the distances in a very safe manner (thanks Toby for the hint).

Then you might add:

 void Ball::calculateDistance(Ball const& jack)
 {
     uint64_t dx = static_cast<uint64_t>(x) - jack.x;
     uint64_t dy = static_cast<uint64_t>(y) - jack.y;
     distanceToJack2 = dx*dx + dy*dy;
 }

Finally, you can sort your balls according to the distances to jack and select all balls from one vector of which the distance is smaller than the distance of the first element in the respective other vector.

One last point: std::string is a rather bad key type for the map if you only have two fix values (beware of typos, additionally, map mangement is rather expensive). You might prefer an enum instead: enum class Color { RED, BLUE }; and use this one as key instead. Even better: don't use a map at all, instead:

std::string bocce(std::vector<Ball>& red, std::vector<Ball>& blue, Ball const& jack);

Note that as you need to calculate the distances, which are stored in the balls, you cannot have const references for the two vectors (which otherwise would have been preferrable). From point of view of design, this is at least questionable (but at least, it's quite some improvement already). Ideally, the design would allow to pass in const vectors, but that would require some overhead, so for pragmatism, we might decide to live with the current design...


Quicksort in JavaScript, using nested functions I come from Java/Swift environment. So, I'm used to show the user of my code only "what is necessary".

For JavaScript I use Visual Code.

When I try to use the Intellisense feature, it shows all my functions/methods when I import it.

So, to hide the unnecessary functions, I opted for using nested functions.

Check out this quicksort code:

/**
 * Sorts the Array in-place
 *
 * @param {Array.<Number | String>} array Array to be sorted
 */
function sort(array) {
    quickSort(array, 0, array.length - 1);

    /**
     * Quicksort implementation
     *
     * @param {Array.<Number | String>} array
     * @param {Number} start Start index of the array for quicksort
     * @param {Number} end End index of the array for quicksort
     */
    function quickSort(array, start, end) {
        if (start < end) {
            let pivot = partition(array, start, end);
            quickSort(array, start, pivot - 1);
            quickSort(array, pivot + 1, end);
        }

        /**
         * Partitions the array for Quicksort
         *
         * @param {Array.<Number | String>} array
         * @param {Number} left Starting index of starting of array/sub-array
         * @param {Number} right Ending index of starting of array/sub-array
         * @returns {Number} Returns pivot index
         */
        function partition(array, left, right) {
            let pivot = array[right];
            let i = left - 1;
            for (var j = left; j < right; j++) {
                if (array[j] <= pivot) {
                    i++;
                    let temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;
                }
            }
            let temp = array[i + 1];
            array[i + 1] = array[right];
            array[right] = temp;
            return i + 1;
        }
    }

}

Is this nesting appropriate? Because I(beginner) feel like if the nested functions are big, the readability(I mean like figuring out what the code is doing) is an issue.

Or should I just follow the classic _ before the function names to indicate it as a private or not meant to be used by the user?

A simple code breaking example:

  For the user of the sort(), partition() and quickSort() is an
  unnecessary functions. Which in-turn can cause collisions if the user
  names their function partition() (because I might not have mentioned
  partition() in my API as it is not usable on its own).

And also any advice to improve the above code is welcome.

Nesting functions
There is nothing wrong with your approch, a few years back and I would have not said so as some browsers would parse functions within functions each time they were call, with the obvious performance hit. That is a thing of the past and functions are parsed then cached for use next time the function is called.
Modules to keep global scope clean.
Modern JS has modules that let you define exports and then import them as needed in other modules
Each module has its own top level context and thus does not add to the global scope.
Use the export token to define what can be imported.
The only way to access items in the module is via the import token, and only those items explicitly exported.
Modules also use strict mode by default.
Thus you can flatten you code without worrying about name conflicts.
If you create a default export in a module you can also import it under another name.
Example of a module, and flatting your quick sort.
/* in file quickSort.js */
export default function sort(array) {
    quickSort(array, 0, array.length - 1);
}

function quickSort(array, start, end) {
    if (start < end) {
        let pivot = partition(array, start, end);
        quickSort(array, start, pivot - 1);
        quickSort(array, pivot + 1, end);
    }
}

function partition(array, left, right) {
    let pivot = array[right];
    let i = left - 1;
    for (var j = left; j < right; j++) {
        if (array[j] <= pivot) {
            i++;
            let temp = array[j];
            array[j] = array[i];
            array[i] = temp;
        }
    }
    let temp = array[i + 1];
    array[i + 1] = array[right];
    array[right] = temp;
    return i + 1;
}

To access it from another module
import sort from "quickSort";
sort([4,3,6,3,7,8]);

Or use another name, but only for the default export.
import qSort from "quickSort";
qSort([4,3,6,3,7,8]);

Note that modules must be in files for both export code and import code, and the script element must be of type "module" eg <script type="module" src="quickSort.js"></script>
Also as a convention not a requirement modules have the extension .mjs rather than .js and some will use .es.mjs. They all have the same MIME type text/javascript
Singleton
Before modules it was common to use the singleton (AKA immediately invoked function) to reduce or completely eliminate any intrusion to the global scope.
Example of a singleton
const sort = (() => {
    function sort(array) {
        quickSort(array, 0, array.length - 1);
    }

    function quickSort(array, start, end) {
        if (start < end) {
            let pivot = partition(array, start, end);
            quickSort(array, start, pivot - 1);
            quickSort(array, pivot + 1, end);
        }
    }

    function partition(array, left, right) {
        let pivot = array[right];
        let i = left - 1;
        for (var j = left; j < right; j++) {
            if (array[j] <= pivot) {
                i++;
                let temp = array[j];
                array[j] = array[i];
                array[i] = temp;
            }
        }
        let temp = array[i + 1];
        array[i + 1] = array[right];
        array[right] = temp;
        return i + 1;
    }

    return sort;
})();

sort([4,3,6,3,7,8]);


Spreadsheet function that gives the number of Google indexed pages I've developed this spreadsheet in order to scrape a website's number of indexed pages through Google and Google Spreadsheets.

I'm not a developer, so how can I improve this code in order to have less code, to use less resources, or to go faster?

I've explained everything here.

//-------------------------------------------
//   scrape a website's number of indexed pages through Google and Google Spreadsheets.
//-------------------------------------------
function indexedpages(myUrl)
    {
    var request = "http://www.google.com/search?&hl=en&q=site:http://" + unescape(myUrl); // Google Request for indexed pages

    var sourcecode = UrlFetchApp.fetch(request).getContentText(); // scrape the page content

    Utilities.sleep(1000); // 1000ms pause to prevent spam

    var codebefore = '
About '; // the code before the number we want

    var codeafter = ' results<'; // the code after the number we want

    var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want

    var theresult =  theresult.replace(",", ""); // delete the ","

    if (isNaN(theresult)) // if the result is not a number

    {
        var codebefore = '
'; // the code before the number we want

        var codeafter = ' result<'; // the code after the number we want

        var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want

        if (isNaN(theresult)) // if the result is not a number

        {
            var codebefore = '
'; // the code before the number we want

            var codeafter = ' results<'; // the code after the number we want

            var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want

            if (isNaN(theresult)) // if the result is not a number (0 result)

            {
                return 0; // returns 0
            }

            else

            {
                return theresult; // returns the number we want
            }
        }

        else
        {
            return theresult; // returns the number we want
        }

    }

    else
    {
        return theresult; // returns the number we want
    }

}

Comments

Never place them between the closing parenthesis and the opening bracket of the statement.
Comments are meant to be read, and not set aside. Here are suggestions for cleaner comments:

//Before the lines concerned, like this one
someObject.someFunction();

//Inside blocks of statements
if(foo){
  //If foo, then call foo
  foo();
} else if(bar){
  //If bar, then call bar
  bar();
}

Prettify Code

To make your code a bit readable, but save yourself the hassle of formatting it manually, use a prettifier. An example is jsbeautifier.

Code

function indexedpages(myUrl) {

  // JavaScript doesn't have block scope like C. Variables declared in blocks
  // other than functions are pulled up and declared in the nearest scope.
  var i;
  var codeBefore;
  var codeAfter;
  var result;

  // So I assume your code was about looking for numbers between a certain set
  // of strings. It's a repetetive task, we'll use an array to store these set
  // of strings and a loop that accesses them using an index.
  var wrappers = [
    ['
About ', ' results<'],
    ['
', ' result<'],
    ['
', ' results<']
    //add more wrappers if you want
  ];

  var wrappersLength = wrappers.length;

  // Make the request
  var request = "http://www.google.com/search?&hl=en&q=site:http://" + unescape(myUrl);
  var sourceCode = UrlFetchApp.fetch(request).getContentText();

  Utilities.sleep(1000);

  // Then loop through each of the wrappers and testing them
  for (i = 0; i < wrappersLength; ++i) {

    // Get the codeBefore and codeAfter from an entry in the array
    codeBefore = wrappers[i][0];
    codeAfter = wrappers[i][1];

    // Parse
    result = sourceCode.substring(sourceCode.indexOf(codeBefore) + codeBefore.length, sourceCode.indexOf(codeAfter)).replace(",", "");

    // Then check if the number is not NaN and if so, return which effectively
    // make the code break out of the loop and of the function as well.
    if (!isNaN(result)) return result;
    else return "0";
  }
}

When free of comments, it's just this short:

function indexedpages(myUrl) {
  var i;
  var codeBefore;
  var codeAfter;
  var result;
  var wrappers = [
    ['
About ', ' results<'],
    ['
', ' result<'],
    ['
', ' results<']
  ];
  var wrappersLength = wrappers.length;
  var request = "http://www.google.com/search?&hl=en&q=site:http://" + unescape(myUrl);
  var sourceCode = UrlFetchApp.fetch(request).getContentText();
  Utilities.sleep(1000);
  for (i = 0; i < wrappersLength; ++i) {
    codeBefore = wrappers[i][0];
    codeAfter = wrappers[i][1];
    result = sourceCode.substring(sourceCode.indexOf(codeBefore) + codeBefore.length, sourceCode.indexOf(codeAfter)).replace(",", "");
    if (!isNaN(result)) return result;
    else return "0"
  }
}


Matrix multiplication and dot-product Exercise 2.37.  Suppose we represent
  vectors v = (vi) as sequences of
  numbers, and matrices m = (mij) as
  sequences of vectors (the rows of the
  matrix). For example, the matrix

  is represented as the sequence ((1 2 3
  4) (4 5 6 6) (6 7 8 9)). With this
  representation, we can use sequence
  operations to concisely express the
  basic matrix and vector operations.
  These operations (which are described
  in any book on matrix algebra) are the
  following:

  We can define the dot product as17

(define (dot-product v w)
(accumulate + 0 (map * v w)))

  Fill in the missing expressions in the
  following procedures for computing the
  other matrix operations. (The
  procedure accumulate-n is defined in
  exercise 2.36.)

(define (matrix-*-vector m v)
  (map <??> m))
(define (transpose mat)
  (accumulate-n <??> <??> mat))
(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map <??> m)))

I wrote the following solutions:

(define (accumulate op initial items)
  (if (null? items)
      initial
      (op (car items) (accumulate op initial (cdr items)))))

(define (accumulate-n op init seqs)
  (if (null? (car seqs))
      null
      (cons (accumulate op init (map (lambda (x) (car x)) seqs))
            (accumulate-n op init (map (lambda (x) (cdr x)) seqs)))))

(define (dot-product v w)
  (accumulate + 0 (map * v w)))

(define (matrix-*-vector m v)
  (accumulate-n +
                0
                (map (lambda (row)
                       (map (lambda (i j) (* i j)) row v)) m)))

(define (transpose mat)
  (accumulate-n (lambda (x y) (cons x y)) null mat))

(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map (lambda (m-row)
           (accumulate-n +
                         0
                         (map (lambda (col)
                                (map * m-row col))
                              cols))) m)))

(define m1 (list (list 1 2 3 4) (list 4 5 6 6) (list 6 7 8 9)))
(define m2 (list (list 10 20 30) (list 40 50 60) (list 70 80 90) (list 100 110 120)))

(define v1 (list 10 20 30 40))

What do you think?

Your definition of transpose is correct, although it can be written succinctly as:

(define (transpose mat)
  (accumulate-n cons null mat))

The remaining two definitions may be written more succinctly by using functions defined earlier.  Notice that multiplying a matrix to a vector is conceptually the same as obtaining the dot-product of the vector and each row of the matrix.  Thus, one may define matrix-*-vector as:

(define (matrix-*-vector m v)
  (map (lambda (row) (dot-product v row)) m))

The above definition satisfies the requirement of the exercise.

Similarly, matrix multiplication of A to B is the same as transposing B and performing a matrix-vector multiplication with each row of A.  Thus, one may define matrix-*-matrix as:

(define (matrix-*-matrix m n)
  (let
      ((cols (transpose n)))
    (map (lambda (row) (matrix-*-vector cols row)) m)))

If you wish to go farther than the exercise requires, you may consider using function currying.  Currying allows one to apply a function to arguments incrementally.  If your implementation of Scheme provides the curry function, you may write:

(define (matrix-*-vector m v)
  (map (curry dot-product v) m))

(define (matrix-*-matrix m n)
  (map (curry matrix-*-vector (transpose n)) m))


Merge sort algorithm written in Python def merge_sort(mslist):

    if len(mslist) < 2:
        return mslist

    left = mslist[:int(len(mslist)/2)]
    right = mslist[int(len(mslist)/2):]

    left = merge_sort(left)
    right = merge_sort(right)

    return merge(left, right)

def merge(left,right):

    result = []

    while len(left) > 0 or len(right) > 0:
        if len(left) > 0 and len(right) > 0:
            if left[0] <= right[0]:
                result.append(left[0])
                left.pop(0)
            else:
                result.append(right[0])
                right.pop(0)
        elif len(left) > 0:
            result.append(left[0])
            left.pop(0)
        elif len(right) > 0:
            result.append(right[0])
            right.pop(0)

    return result

def main():

    mslist = [-9,1,1,2,3,2,7,3,6,4,5,4,3,5,6,7,8,9,0,0]
    print(merge_sort(mslist))

if __name__ == "__main__":
    main()

Please give me some comments about the actuall algorithm, i used the pseudo code from the wikipedia page as a reference.
Please give me some Pythonic advice or any other general coding paradigm you  feel should be followed.

I already made changes to my code regarding the amount of times len(direction) is done.

Here:

if len(mslist) < 2:

I would write len(mslist) <= 1 because 1 is the interesting number here.

Here:

int(len(mslist)/2)

just write len(mslist)//2 which is explicit integer division.

Here:

            result.append(left[0])
            left.pop(0)

you can write result.append(left.pop()) since pop returns the element removed.

The elifs in the merge function are not properly aligned.

Notice that the use of the pop method could alter algorithm complexity (because I think that pop is \$O(n)\$). It could be better to use two indices to keep track of the position in the two lists.


Small fast pseudorandom number generator in C++ I've been away from C++ for some time and I'd like to get back up to speed with modern practices, so I implemented a small random number generator described here.

Any advice on this piece of code?

    #include <cstdint>
    #include <cstddef>
    #include <limits>
    #include <random>

// implementation of Bob Jenkins' small prng https://burtleburtle.net/bob/rand/smallprng.html
namespace Random {
    namespace detail {
        using _rand32_underlying = uint32_t;
        using _rand64_underlying = uint64_t;

        template<size_t N> struct rand_type { using type = void; };
        template<> struct rand_type<32> { using type = _rand32_underlying; };
        template<> struct rand_type<64> { using type = _rand64_underlying; };

    }

    // public
    template <size_t N>
    using rand_t = typename detail::rand_type<N>::type;
    using rand32_t = rand_t<32>;
    using rand64_t = rand_t<64>;

    template <size_t N>
    inline rand_t<N> rot(rand_t<N> x, rand_t<N> k) noexcept { return ((x << k) | (x >> (N - k))); }

    template<size_t N>
    class SmallPrng
    {
        public:
            using result_type = rand_t<N>;
            inline rand_t<N> min() { return std::numeric_limits<result_type>::min(); }
            inline rand_t<N> max() { return std::numeric_limits<result_type>::max(); }

            rand_t<N> a, b, c, d;

            inline rand32_t prng32()
            {
                rand32_t e = a - rot<N>(b, 27);
                a = b ^ rot<N>(c, 17);
                b = c + d;
                c = d + e;
                d = e + a;
                return d;
            }

            inline rand64_t prng64()
            {
                rand64_t e = a - rot<N>(b, 7);
                a = b ^ rot<N>(c, 13);
                b = c + rot<N>(d, 37);
                c = d + e;
                d = e + a;
                return d;
            }

        public:
            explicit SmallPrng(result_type seed = 0xdeadbeef) noexcept
            {
                static_assert(!(N != 32 && N != 64), "You can only construct a small prng in 32 or 64 bit mode.");
                a = 0xf1ea5eed;
                b = c = d = seed;
                for(size_t i = 0; i < 20; ++i)
                    (*this)();
            }

            explicit SmallPrng(std::random_device &rd) : SmallPrng(rd()) {}

            inline rand_t<N> operator()() noexcept
            {
                if constexpr(N == 32)
                    return prng32();
                return prng64();
            }
    };
}

The SmallPrng(std::random_device &rd) constructor seems like an utility method. It spares the client a single call to seed = rd(), but forces an inclusion of (otherwise unnecessary) <random>. IMHO, this constructor is absolutely unnecessary.
The purpose of the

        for(size_t i = 0; i < 20; ++i)
            (*this)();

loop in the constructor is seems useless; it amounts to passing a different seed. In any case, use {} around the loop body.
An asymmetry between

        b = c + d;

in prng32() and

        b = c + rot<N>(d, 37);

in prng64() is striking. Needs a comment, at least.
As mentioned in comments, the static_assert(!(N != 32 && N != 64), ....) is equivalent to static_assert((N == 32 || N == 64), ....) which is IMHO much cleaner.


Python program that takes input and runs queries on a mySQL database on it I've been slowly learning Python so I want to know what the most Python-esque way of doing things are.

The scenario is that I'm connected to a database with a Customer and a SalesRep table in a database called sports2000. I also have a flat file containing a list of customer id's and salesrep names. My end goal is to update these customers to have these corresponding salesreps assigned to them. I want to do three things:

Display information about all the customers in this list.
Display information about the customers in the list in Massachusetts.
Update the customers to have their new sales representatives.

Any ideas or better ways to make this code more Python-esque would be great as I'm trying to write code that looks like it was written by a competent Python developer.

import MySQLdb as mdb

class PrimeCustomer:
    id = 0
    newRep = ""

with open('input.txt', 'r') as f:
    lines = f.readlines()

primeCustomers = []

for line in lines:
    words = line.split()

    tt = PrimeCustomer()

    tt.id = int(words[0])
    tt.newRep = words[1]

    primeCustomers.append(tt)

try:
    db = mdb.connect('localhost', 'root', '', 'sports2000')
    cur = db.cursor()

    # Create a string to use for the SQL IN operator
    customerNumbers = '('
    for prime in primeCustomers:
        customerNumbers += str(prime.id)
        customerNumbers += ', '

    # Remove the trailing comma and space and add ending parenthesis
    customerNumbers = customerNumbers[:-2]
    customerNumbers += ')'

    cur.execute("SELECT Name, custNum from customers where custNum in {}".format(customerNumbers))

    row = cur.fetchone()
    while row is not None:
        print ", ".join([str(c) for c in row])
        row = cur.fetchone()

    # Get a list of all the new salesReps for Massachusetts customers
    cur.execute("SELECT Name, custNum from customers where State = 'MA'")

    row = cur.fetchone()
    while row is not None:
        for prime in primeCustomers:
            if row[1] == prime.id:
                print row[0], prime.newRep

        row = cur.fetchone()

    # Go through each customer and assign them the sales rep
    # with the given name
    for prime in primeCustomers:
        cur.execute("UPDATE customer " +  \
                    "SET salesRep = " + \
                    "(SELECT salesRep FROM SalesRep WHERE repName = '{}' LIMIT 1) ".format(prime.newRep) + \
                    "WHERE customerNumber = {}".format(prime.id))

    db.commit()
except Exception as e:
    db.rollback()
    print e
finally:
    if cur:
        cur.close()
    if db:
        db.close()

A comment on this bit:

customerNumbers = '('
for prime in primeCustomers:
    customerNumbers += str(prime.id)
    customerNumbers += ', '

# Remove the trailing comma and space and add ending parenthesis
customerNumbers = customerNumbers[:-2]
customerNumbers += ')'

can be written as:

customerNumbers = '(' + ', '.join(str(x) for x in primeCustomers.id) + ')'

My final comment has to do with the use of fetchone() instead of fetchall(). Is there a reason you do it like that? Instead of having the while statements which you have to evaluate in every loop you can just fetch all results and process them in a less "expensive" for loop like that:

rows = cur.fetchall()
for row in rows:
    #do stuff with the results of every row.


Error-handling / Self-Validating mechanism The below idea seemed to look clean, to allow the object itself to validate its values for different scenarios.

For eg:

While creating the object, the value of Object1 and Object2 in SelfValidator object should be validated for not null.
At one scenario like inserting the SelfValidator object to Database, validation of value1 as non-zero has to be done, which is not necessary for an Update. A new validate function: validateForInsert(), which will validate and set the error data, can be included to SelfValidator class.

But I am sure, there might be some drawbacks, design flaws, which I would like to understand and improve.

ErrorInfo.java

public class ErrorInfo {
  String errorMessage = "";

  public void setErrorMessage(String errorMessage) {
    this.errorMessage = new StringBuffer(this.errorMessage).append("\n+").append(errorMessage).toString();
  }
}

SelfValidator.java

public class SelfValidator {

  String object1;
  String object2;
  int value1;
  ErrorInfo errorInfo;

  public ErrorInfo getErrorInfo() {
    return errorInfo;
  }

  public SelfValidator(String object1, String object2, int value1) {
    super();
    this.object1 = (object1 == "")?null: object1;
    validate(this.object1, "object1");
    this.object2 = (object2 == "")?null: object2;
    validate(this.object2, "object2");
    this.value1 = value1;
  }

  private void validate(String value, String dataMember) {
    if(value == null){
        if(errorInfo == null){
            errorInfo = new ErrorInfo();
        }
        errorInfo.setErrorMessage(dataMember +" value is invalid");
    }
  }
}

Demonstrator.java

public class Demostrator {
  public static void printValidOrNot(ErrorInfo errorInfo){
    if(errorInfo == null){
        System.out.println("Object valid");
        //Proceed with manipulating the object
    }else{
        System.out.println(errorInfo.errorMessage);
        // Break and handle the error.
    }
  }
  public static void main(String[] args) {
    SelfValidator selfValidatingObject1 = new SelfValidator("Test", "Test", 1);
    printValidOrNot(selfValidatingObject1.getErrorInfo());

    SelfValidator selfValidatingObject2 = new SelfValidator("", "", 1);
    printValidOrNot(selfValidatingObject2.getErrorInfo());
  }
}

isValid Method
If you have a validator, I would expect a method to check if it is valid.
If you add an isValid method, you would get rid of the errorInfo == null check, which isn't a good idea. It exposes how the validator works internally, and relies on this never changing.
errorMessage Type
Why is your error message a String? You are creating a new StringBuffer and calling toString every time an error is appended. Just make errorMessage a StringBuffer or StringBuilder and call toString when the error message is retrieved (which should be done via a getter, not direct access).
Naming
setErrorMessage: What this actually does is appendErrorMessage
Spacing
I know it's knit-picking, but please follow the general conventions regarding spacing. Before and after ?, :, and + should be a space.
General Idea
I'm not too sure what this is good for (maybe I'm missing something?). It doesn't seem like the SelfValidator class can be reused for any other data. The three fields and their types are hardcoded, as is the validation mechanism (no empty string and no null allowed). Couldn't all your code be replaced with something like this:
  private boolean isValid = true;

  public MyClass(String object1, String object2, int value1) {
    super();
    if (object1 == null || object2 == null || object1.equals("") || object2.equals("")) {
        this.isValid = false;
    }
  }

  public isValid() {
    return isValid;
  }

It seems just as flexible as your approach, but is easier to read.


JUnit test case to check that an exception of type javax.mail.MessagingException is not thrown I have a method which will send a text mail using JavaMail API and I am trying to write a test case for this method which will check if an Exception of type javax.mail.MessagingException is not thrown.

If a MessagingException type exception is thrown, the test will fail, else it will pass.

public void sendMail() throws MessagingException{
        final String smtpServer = "smtp.gmail.com";
        final String userAccount = ""; // Sender Account.
        final String password = ""; // Password/Application Specific Password.
        final String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
        final String smtpPort = "587";
        final String PORT = "465";

        final Properties props = new Properties();
        props.put("mail.smpt.host", smtpServer);
        props.put("mail.smtp.user", userAccount);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.debug", "false");
        props.put("mail.smtp.socketFactory.port", PORT);
        props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session connection = Session.getInstance(props, null);
        MimeMessage mimeMessage = new MimeMessage(connection);
        connection.setDebug(true);

        final Address toAddress = new InternetAddress(""); // toAddress
        final Address fromAddress = new InternetAddress(userAccount);
        mimeMessage.setContent("This is a test mail...", "text/html; charset=UTF-8");
        mimeMessage.setFrom(fromAddress);
        mimeMessage.setRecipient(javax.mail.Message.RecipientType.TO, toAddress);
        mimeMessage.setSubject("Test Mail...");
        Transport transport = connection.getTransport("smtp");
        transport.connect(smtpServer, userAccount, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    }

    public void testSendMailToCheckThatMessagingExceptionIsNotThrown() {
       try {
            genericTaskInterpreter.sendMail();
        } catch (MessagingException messagingException) {
            fail("A MessagingException is thrown..." + messagingException.getMessage());
        }
    }

Am I doing it correctly? How can I improve it?

JUnit will fail anyway if an (unexpected) exception is thrown, by creating an Error (instead of a simple failure). As you do not catch any other exceptions (which means every exception fails your test anyway), you can simply remove the try-catch block, as your test case will still fail then if the MessagingException is thrown.


Creating Sequential IDs I'm using SQL Server 2014 with Visual Studio 2013. When I add a new record, identity column (seed 1, increment 1) "ID" increases by 1, and record added to the database.

My table consist of two rows:

ID, set identity, seed=1, increment=1
Column1, int
Column2, nvarchar(10), Primary Key

    ID Column1 Date
1.  1  300     01.01.2001
2.  2  301     02.01.2001

My query is as follows:

insert into Table values(302,'02.01.2001')

Clearly it gives an error, because 02.01.2001 already exists.

This, however:

insert into Table values(302,'03.01.2001')

successfully inserts data.

But when I select:

select * from Table

the result is:

    ID Column1 Date
1.  1  300     01.01.2001
2.  2  301     02.01.2001
3.  4  302     03.01.2001

Sometimes after this unsuccessful attempts of inserting data, the ID increases but the data doesn't recorded to data, because I have made a mistake. (Like I show above.) Then, after a successful insert query, data records and ID jump to 4 instead of 3.

I have thought of a workaround (it works from my point of view):

declare @maxIDValue int
if exists (select ID from NVDB.dbo.V where ID=1) --check if table has its first record.
    begin
        if (select count(ID) from NVDB.dbo.V) >= 1
        set @maxIDValue = (SELECT MAX(ID) FROM NVDB.dbo.V)
    end
else set @maxIDValue = 1
if not exists (select Date from NVDB.dbo.V where Date='03.10.2010')
    begin
        dbcc checkident ('NVDB.dbo.V', RESEED, @maxIDValue)
        insert into NVDB.dbo.V values(300,'03.10.2010')
    end

SELECT * FROM NVDB.dbo.V

With this piece of code, I want my table in order and after the insertion attempts. It gives no error, and of course ID goes sequentially.

Is this a right approach? What is the best practice? Do we have a simple way to achieve this or did I write so much code?

Note: My table is small, so performance is not an issue. But when it becomes big, like 3000 records, does this code affect performance? (I'll be using these queries in my C# application.)

Minutia
A table called V ... really? Columns Column1 and Column2 .... why are you using example tables? In your setup you called it Table but in the code you called it V...
Normally we require that code is real code, not 'example' code. In this case, it seems your actual code is 'real', just the tables it works on is not.
IDENTITY columns
IDENTITY columns are generally there for one reason only, to create a unique field that is fast to use (insert/index/join/search).
These properties are guaranteed in all uses of the field, including concurrent modification of the data (two processes inserting data at the same time will each generate unique ID's still - guaranteed)
You want to have the added use for the column: to ensure there are no 'gaps' in the sequence. This is not what IDENTITY columns are for.
IDENTITY columns, for performance reasons, generally allocate a 'pool' of numbers to each process that's adding data, and as each number is used from the pool, the pool shrinks. If the pool is no longer needed, then the pool is 'returned' to the system and another process can continue with it.  If two processes are inserting data at the same time you will often get gaps between the numbers because the pools are different. Also, if there's a "hard crash" on the system, the pool is often completely 'lost', and you could have large gaps in the ranges.
This is the compromise that IDENTITY columns make. They sacrifice sequentialness for performance and concurrency.
Solution
There are two solutions, the easy one, and the hard one.
The easy one is to accept that there will be gaps, and move on. I strongly recommend that you revisit your requirements, and see if you can just use the IDENTITY column and move on.
The hard solution is to build your own system for number generation (although it will still not be perfect... if someone deletes a record, you will still have gaps).
Your solution is too simple, and also too slow. It is, essentially, broken.
If two processes run at the same time, they will allocate the same numbers for records, and you will have duplicate insert situations in to your table. This is because you do not have any transaction handling for your statements... they are all independent. You need to have a table-lock on the table so that no other process can add records while you are finding the max value. The lock is needed for the entire process of finding, and deciding, and inserting the value. You will need to read up on "with holdlock" for your select statements otherwise the lock will not be maintained: See the HOLDLOCK and other documentation on transactions.
Then, after the manipulation is done, you can commit the transaction.
Your performance will suck because you will be locking a lot of data, etc.
The better solution is to have a separate ID table for your key field. A simple table like:
create table VTableKey (
    nextid integer not null
)

insert into VTableKey values (1)

Now, with that table, you can:

begin a transaction
query-with-update-lock and update just that one record
insert into the V table
commit the transaction

In that way, you maintain the 'atomicity' of the transaction - the value only changes on a successful insert. I would consider using a stored procedure to encapsulate that logic.
Note that you are still vulnerable to someone deleting records, you will still end up with gaps.


More efficient way to loop through an object There's a part in my page where you can add, edit or delete school details, and it wasn't supposed to save entries to the database until the user hits Enter, so I save all data in an object first.

My object looks like this:

schooldetails : {
  "1": {
    "school_ctr":"schoolctr_1",
    "school":"Fiat Lux Academe",
    "course":"",
    "qualification":"High School",
    "date_grad":"06/04/2008",
    "notes":"*graduated with honors",
    "deleted":0
  },
  "2": {
    "school_ctr":"schoolctr_2",
    "school":"College of St. Benilde",
    "course":"Computer Science",
    "qualification":"Bachelor / College",
    "date_grad":"06/05/2012",
    "notes":"",
    "deleted":0
  },
  "3":{
    "school_ctr":"schoolctr_3",
    "school":"Siliman University",
    "course":"Information Technology",
    "qualification":"Post Graduate / Master",
    "date_grad":"06/06/2014",
    "notes":"",
    "deleted":0
  }
}

I passed it through AJAX and I was able to save info through this code:

if(!empty($school_details_new)){
  foreach($school_details_new as $key => $value) {
    foreach($value as $school_data => $data_values) {
      if($school_data == "school")
        $s_name = mysql_real_escape_string($data_values);
      if($school_data == "course")
        $s_degree = mysql_real_escape_string($data_values);
      if($school_data == "qualification")
        $s_type = mysql_real_escape_string($data_values);
      if($school_data == "date_grad")
        $s_enddate = mysql_real_escape_string($data_values);
      if($school_data == "notes")
        $s_notes = mysql_real_escape_string($data_values);
    }
  $sql = "INSERT INTO `SchoolDetails` (`personID`, `School`, `Type`, `End_Date`, `Degree`, `Notes`) VALUES ($id, '$s_name', '$s_type', '$s_enddate', '$s_degree', '$s_notes');";
  $res_sql = mysql_query ($sql);
  }
}

This is actually working fine with me.  I don't have any errors or anything but I do believe there is a more efficient way to do this without having a lot of if statements. Thoughts?

Indeed there is! Use prepared statements instead of manually escaping and inserting into your query!

  Please, don't use mysql_* functions in new
  code. They are no longer maintained and are
  officially deprecated. See the red
  box? Learn about prepared
  statements instead, and use
  PDO or MySQLi - this
  article will help you decide which. If you choose
  PDO, here is a good tutorial.

//mysqli connection somewhere around here...

if (!empty($school_details_new)) {
    $stmt = mysqli_prepare($conn, "INSERT INTO `SchoolDetails` (`personID`, `School`, `Type`, `End_Date`, `Degree`, `Notes`) VALUES (?, ?, ?, ?, ?, ?)";
    foreach ($school_details as $school) {
        mysqli_stmt_bind_param($stmt, "isssss", $id, $school["school"], $school["qualification"], $school["date_grad"], $school["course"], $school["notes"]);
        mysqli_stmt_execute($stmt);
    }
}


Check for length in a string I have this logic that seems complicated checking the length and adding a colon. I'd like to see if any of you C# experts can help me simplify it. If the replace remove the full text then I am just adding the word Result. If it removes the make then I am just displaying the model.

Is there a way I can remove the if statement and combine into one?

namespace DupName
{
    public class Program
    {
        static void Main(string[] args)
        {
            StringBuilder childName = new StringBuilder();

            List<Item> items = new List<Item>()
                .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A3 Premium Plus" })
                .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "Audi" })
                .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi" })
                .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S5 Premium Plus 3.0 TFSI quattro" })
                .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S3 Premium Plus 3.0 TFSI quattro" });

            foreach (var item in items)
            {

                string temp = item.ChildName.Replace(item.Name, "").Trim();

                if (temp.Length == 0)
                {
                    Console.WriteLine(string.Format("{0}","Result"));

                }else
                {

                    Console.WriteLine(string.Format("{0}: {1} - {2}", "Result", temp, item.Name));
                }
            }
        }
    }

    public static class Extensions
    {
        public static List<T> AddAlso<T>(this List<T> list, T item)
        {
            list.Add(item);
            return list;
        }
    }

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ChildName { get; set; }
    }

Output

Result: A3 Premium Plus - Audi
Result
Result
Result: S5 Premium Plus 3.0 TFSI quattro - Audi
Result: S3 Premium Plus 3.0 TFSI quattro - Audi

If I understand correctly, your frustration is with the necessary computation for knowing whether to print Result or Result: temp - childname. That's because you're doing more steps than necessary.

Instead of:

Calculating the (ChildName - Name) string
Trimming any whitespaces in the resulting string
And then checking if this string is empty

You could just check if both the Name and ChildName are equal. If they are, your variable temp isn't used. Also, since result is written independently of such calculation, you could always print it.

So, I would suggest exchanging

foreach (var item in items) {
    string temp = item.ChildName.Replace(item.Name, "").Trim();
    if (temp.Length == 0) {
        Console.WriteLine(string.Format("{0}","Result"));
    } else {
        Console.WriteLine(string.Format("{0}: {1} - {2}", "Result", temp, item.Name));
    }
}

for

foreach (var item in items) {
    Console.Write("Result");

    if (item.Name != item.ChildName) {
        string childNameWithoutName = item.ChildName.Replace(item.Name, "").Trim();
        Console.Write(string.Format(": {1} - {2}", childNameWithoutName, item.Name));
    }

    Console.WriteLine();
}


This is Crossing river code Story
Niñez friends from Kakao Elementary School meet a stream with stepping stones on an autumn picnic with Ms. Ryan and are about to cross over to the other side. Ms. Ryan made the following rules so that Niñez and his friends can safely cross the river:

Stepping stones are placed in a row, and the number of times a kid may step on a stone is written on each stone.
The number on the stone decreases by one each time a kid steps on them.
When the number of stepping stones reaches 0, you can no longer step on them.
A kid can jump, skipping several stones. The maximum number of stones that a kid may skip is given as a parameter k.
If a kid jumps, you always jump to the nearest stepping stone that isn't 0.

The friends of Niñez are on the left side of the stream, and they must arrive across the right side of the stream to be counted as crossing the stepping stone.
How many kids can cross the river, given an array of initial values on the stones and the parameter k?
Constraints

The number of Ninez friends who must cross the stepping stone is considered to be unlimited.
The stones array has a size of at least 1 and has a maximum length of 200,000.
The initial value of each element in the stones array is a natural number between 1 and 200,000,000.
k is a natural number greater than or equal to 1 and less than or equal to the length of the stones.

Code review question
How should i revise my code? this is Kakao intern code test. I used loop to change stone numbers when stepped and repeat many times . It returns how many people could cross the river.
Original challenge (in Korean)
Example
stones = [2, 4, 5, 3, 2, 1, 4, 2, 5, 1]
k=3

After the first kid crosses, the stones have the following values:
stones = [1, 3, 4, 2, 1, 0, 3, 1, 4, 0]

The second kid makes it, making two jumps:
stones = [0, 2, 3, 1, 0, 0, 2, 0, 3, 0]

The third kid makes it, making four jumps:
stones = [0, 1, 2, 0, 0, 0, 1, 0, 2, 0]

Now it takes a jump of 4 stones to get to the other side, which is larger than k = 3. So the answer for this input is three kids, or simply 3.
def solution(stones, k):
    num=len(stones)
    answer=0
    for count in range(max(stones)):
        stat=-1
        for i in range(num):
            if stat==i-1:
                if stones[i]==0:
                    for j in range(i+1,num):
                        if stones[j]==0:
                            if j-stat>=k:
                                return answer
                            else:
                                pass
                        elif stones[j]!=0:
                            stat=j
                            stones[j]-=1
                            break
                elif stones[i]!=0:
                    stat=i
                    stones[i]-=1
        if stat+k>=num:
            answer+=1
        elif stat+k<num:
            return answer
    return answer

Try to avoid nested if and for loops
The structure of your code is a bunch of nested for and if-elif-else statements. Try to find a way to compact those by restructuring your code or logic. Some examples:
No need to use elif if else suffices.
if stones[i]==0:
    # code
elif stones[i]!=0:
    # more code

Can be rewritten as:
if stones[i]==0:
    # code
else:  # you can place a comment here like: stones[i]!=0
    # more code

Combine if statements with and or or:
if stat==i-1:
    if stones[i]==0:

Can be rewritten as:
if stat==i-1 and stones[i]==0:

No need to state and else if it does nothing:
else:
    pass

Can be omitted.
Try to use Python code style PEP8 and meaningfull variable naming
See PEP8. Some examples in your code that can be improved for consistent readability by other Pythonistas:
Use spaces around operators and comparisons. These (unrelated) lines:
num=len(stones)
range(i+1,num)
if j-stat>=k:
    pass

Becomes:
num = len(stones)  # spaces around '='
range(i+1, num)    # space after ',' in function arguments
if j - stat >= k:  # spaces around '-' and '>='
    pass

Use meaningfull function and variable names

solution() -> num_kids_crossing_river()
answer -> num_kids or simply kids
i -> current_stone
k -> max_leap
Etc.

Use docstrings and comments to clarify your code
Document your code. Place documentation below your function definition (a "docstring") like this:
def num_kids_crossing_river(stones, max_leap)
""" Return the number of kids that can pass the array of stones.
    <<some more text here; like in the text from the exercise>>

    Args:
        stones (list(int)): initial values on the stones.
        max_leap (int): maximum number of stones a kid can jump over/skip.

    Returns:
        int: the number of kids that can cross the river.

Use comments to document what you are doing, as far as it isn't clear from the code itself. Document the algorithm/idea and not the code itself.
For example:
# Maximum number of iterations is the maximum number on the stones
for count in range(max(stones)):
    etc.

Most importantly: rethink the problem
All of the above can be used to improve your code and coding style, but it does not really optimise your code. One important step in coding is to first think about what you are about to code and how to code it.
If you look at the example, you see that the numbers in the stone array decrease, until there are k or more zero's next to eachother.
So an other way to formulate the problem is: how many times can I subtract 1 from an array until I have k or more zero's next to eachother?
Now suppose k = 0 (no jumps). And stones = [5, 6, 7]. You can see/imagine that the number of kids that can pass is 5.
Now suppose k = 1 and the same stones. You can see/imagine that the number of kids that can pass is 6. The 5 becomes 0 first, but you can skip it. Next, the 6 becomes 0.
What we can do, is to iterate over the stones, and check each "window" of k stones. And check the maximum value in that window. After that number of steps, that window is all 0 and the game stops. So we need to find the window that first gets to 0.
So now we can rephrase the problem again, more in mathematical terms: what is the minimum value of the maximum value of all sequential windows of stones with length k?
Illustrated with the example give in the problem statement: k = 3; stones = [2, 4, 5, 3, 2, 1, 4, 2, 5, 1]
[2, 4, 5, 3, 2, 1, 4, 2, 5, 1]
+-------+                      # maximum = 5 for this window
   +-------+                   # maximum = 5 for this window
      +-------+                # maximum = 5 for this window
         +-------+             # maximum = 3 for this window
            +-------+          # maximum = 4 for this window
               +-------+       # maximum = 4 for this window
                  +-------+    # maximum = 5 for this window
                     +-------+ # maximum = 5 for this window

Now the minimum value of all those maximum values is 3, which is the answer.
You can see that the value of 3 exactly appears in the piece that goes 0 first and where the fourth kid is stuck.
Here, I give you two implementations. One uses basic Python concepts, like your code. The second uses the (intermediate level Python concept) list comprehensions.

def min_max_of_subsection(array, k):
    """ Returns the minimum value of the maximum value of each subsection of length k in array.

    Args:
        array (list): an array of values (can be anything that has an order)
        k (int): length of the sub section

    Returns:
        value from array
    """
    max_subsection = []
    for array_index in range(len(array) - k + 1):
       max_subsection.append(max(array[array_index:array_index + k]))
    return min(max_subsection)

def min_max_of_subsection2(array, k):
    """ Returns the minimum value of the maximum value of each subsection of length k in array.

    Args:
        array (list): an array of values (can be anything that has an order)
        k (int): length of the sub section

    Returns:
        value from array
    """
    return min(max(array[idx:idx+k]) for idx in range(len(array) - k + 1))

print(min_max_of_subsection([2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3))
print(min_max_of_subsection2([2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3))

Try it online!


Database of students in a social network This is sourced from the Stanford Coursera self study DB class SQL quizzes.

  Students at your hometown high school have decided to organize their
  social network using databases. So far, they have collected
  information about sixteen students in four grades, 9-12. Here's the
  schema:

Highschooler (ID, name, grade)

  English: There is a high school student
  with unique ID and a given first name in a certain grade.

Friend (ID1, ID2)

  English: The student with ID1 is friends with the
  student with ID2. Friendship is mutual, so if (123, 456) is in the
  Friend table, so is (456, 123).

Likes (ID1, ID2)

  English: The student with ID1 likes the student with
  ID2. Liking someone is not necessarily mutual, so if (123, 456) is in
  the Likes table, there is no guarantee that (456, 123) is also
  present.

  DB is here

  Prompt: Find the number of students who are either friends with
  Cassandra or are friends of friends of Cassandra. Do not count
  Cassandra, even though technically she is a friend of a friend.

My answer (which works) is below, but I am wondering if there is a more succinct way of accomplishing the same results. Any feedback would be appreciated.

select count(*)-1 from
(
select id2
from friend f, highschooler a
where a.name='Cassandra'
and a.id=f.id1
union
select id2
from friend f, highschooler a
where a.id=f.id1
and f.id1 in ( select id2
from friend f, highschooler a
where a.name='Cassandra'
and a.id=f.id1 ) )

Style

Indentation would make your query more readable.
Table names in MySQL may be case sensitive, depending on the underlying filesystem.  Therefore, it is safest to write the query using identifiers with the same case as stated in the problem.
SQL keywords are conventionally written in ALL CAPS, though some programmers object to that convention.
Single-letter names for table aliases are cryptic.  While I can somewhat understand friend f, I have a harder time accepting highschooler a.

Formulation

UNION, short for UNION DISTINCT, automatically deduplicates the result set.  If possible, prefer UNION ALL for efficiency.  However, in this case, you do need deduplication for the correct answer.
The two halves of the union seem repetitive.
Subtracting one from the final count is weird and risky.  I suggesting filtering out Cassandra herself from the result set.

Here's how I would write it:

SELECT count(Friend.ID1)
    FROM Highschooler AS Cassandra, Friend
    WHERE
        Cassandra.name = 'Cassandra'
        AND (
            Friend.ID2 = Cassandra.ID
            OR Friend.ID2 IN (
                SELECT Friend.ID1
                    FROM Friend
                    WHERE Friend.ID2 = Cassandra.ID
            )
        )
        AND Friend.ID1 <> Cassandra.ID;


C++/STL Prime tuples (twin, cousin, sexy) up to the given limit As I'm mastering STL I wrote a solution for generating all the prime tuples of the form (p1,p2) where "twin" means p2-p1=2, "cousin" p2-p1=4 and "sexy" p2-p1=6.

I'm interested in all the comments about the efficiency and style of this solution.

I use the following subroutine from utilities_template.h to print vector container:

template <class C>
void printContainer(C v, std::string msg = "Container", bool rowWise = true) {
  std::cout << msg << " " << std::endl;
  for (auto it = v.cbegin(); it != v.cend(); ++it)
    std::cout << std::setw(3) << *it << (rowWise ? " " : "\n");
  std::cout << std::endl;
}

And here is my solution:

#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <vector>
#include "utilities_template.h"

enum primeClassification { twin = 2, cousin = 4, sexy = 6 };

void removeElementsInListDivisibleByP(int p, std::list<int>& l) {
  l.remove_if([p](int n) { return n % p == 0; });
}

std::vector<int> getAllPrimesLessN(int n, bool debugMode = false) {
  using namespace std;
  list<int> l;
  for (int i = 2; i < n + 1; i++) {
    l.push_back(i);
  }
  int min_element = 2;  //
  vector<int> primes = {min_element};
  while (min_element != l.back()) {
    removeElementsInListDivisibleByP(min_element, l);
    if (debugMode)
      printContainer(
          l, "After divisible by " + std::to_string(min_element) + " removed:");

    min_element = *std::min_element(l.cbegin(), l.cend());
    primes.push_back(min_element);
  }

  auto temp_it =
      adjacent_find(primes.cbegin(), primes.cend(),
                    [](const int& a, const int& b) { return (b - a) == 1; });

  printContainer(primes, "Primes up to " + std::to_string(n));

  return primes;
}

std::vector<std::pair<int, int> > formPrimePairs(primeClassification pClass,
                                                 std::vector<int>& primes) {
  using namespace std;

  std::vector<std::pair<int, int> > pairs;
  for (auto it = next(primes.cbegin(), 1); it != primes.cend(); it++) {
    if (*it - *std::prev(it, 1) == pClass) {
      auto this_pair = make_pair(*prev(it, 1), *it);
      pairs.push_back(this_pair);
    }
  }

  return pairs;
}

void s4PrimePairs() {
  using namespace std;
  int n = 0;
  cout << "Please enter the limit: ";
  cin >> n;

  vector<int> primes = getAllPrimesLessN(n);

  printVectorOfPairs(formPrimePairs(primeClassification::twin, primes),
                     "\nTwin pairs (delta=2): ", true);

  printVectorOfPairs(formPrimePairs(primeClassification::cousin, primes),
                     "\nCousin pairs(delta=4): ", true);

  printVectorOfPairs(formPrimePairs(primeClassification::sexy, primes),
                     "\nSexy pairs(delta=6): ", true);
}

std::min_element is unwarranted. The list is initially sorted, and remove_if guarantees to maintain the order of remaining elements. A minimal element is *l.cbegin().
removeElementsInListDivisibleByP is very hard to read. Consider remove_multiples_of_P.
The list initialization loop really wants to be std::iota.
The sieving does work, but it seems less efficient than the classical one.
If an std::vector can be used, it performs better than std::list (mostly due to preferential locality and less memory overhead). You may want to experiment.
I don't see what adjacent_find is supposed to do. Is it a remnant of some debugging code, perhaps?


Targeting specific elements with CSS only This code below works as needed, but I am not sure if there is a more elegant way with pure CSS. I have a table with two columns, and 4+ rows. I'll actually upload a picture.  It's the first table in grey that I am messing with.

I want to select all the TDs--except for the first TD, because that first one has been changed to vertical text--and give them a 100% width and text align center. Any thoughts?

.greyBG tr:nth-of-type(1) ~ tr > td {
    width: 100%;
    text-align: center;
}

And the HTML:

               Landscape

               Lorum Ipsum

                Lorum Ipsum

                 Lorum Ipsum

                  Lorum Ipsum

Markup

If you have a td that you're giving a class that indicates that it is some sort of heading, you should be using a th instead.  The th element is allowed to appear in a tbody, it isn't restricted to thead.

When validated, this table will generate warnings regarding different numbers of cells in each row.  The correct structure should look like this:

            Landscape
            Lorum Ipsum

            Lorum Ipsum

            Lorum Ipsum

            Lorum Ipsum

Be consistent with your indentation.

CSS

Now that the markup is simplified, it's child's play to simplify the CSS

.greyBG td {
    width: 100%;
    text-align: center;
}

Demo:  http://codepen.io/cimmanon/pen/GqKcx


Reusing strings read from I/O I am working on an application that reads lots of data from the network and puts it in a grid.  I noticed that I could save some memory by reusing existing strings instead of always using the new strings that came off the wire.  So here is the class that I wrote to accomplish that.  It is simple and it works.  But I was wondering if this had a name and, of course, if the code could be improved. One thing that I don't like is that I'm storing two references to each string.

public class StringCollection
{
  private Dictionary<string, string> lookup_ = new Dictionary<string, string>();

  public string Reuse(string s)
  {
    if (s == null)
    {
      return null;
    }
    string existing;
    if (lookup_.TryGetValue(s, out existing))
    {
      return existing;
    }
    else
    {
      lookup_.Add(s, s);
      return s;
    }
  }

  public void Clear()
  {
    lookup_.Clear();
  }

  public int Count { get { return lookup_.Count; } }

}

You might want to look into string interning:

  The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

While it has some memory-related side-effects, you could avoid having to build up a dictionary like this and throw away allocated strings to keep it updated.


Swapping bytes of an integer in Java I have this tiny function that expects an int and returns an int with the bytes swapped:
public class Main {

    public static void main(String[] args) {
        int cafeBabe = 0xcafebabe;
        System.out.println(Integer.toHexString(cafeBabe));
        System.out.println(Integer.toHexString(byteSwap(cafeBabe)));
        System.out.println(Integer.toHexString(byteSwap(byteSwap(cafeBabe))));
    }

    public static int byteSwap(int a) {
        return ((a & 0xff000000) >>> 24) |
               ((a & 0x00ff0000) >>> 8)  |
               ((a & 0x0000ff00) << 8)   |
               ((a & 0x000000ff) << 24);
    }
}

Basically, we are switching between endianess. Now, is there a better/more efficient way of accomplishing the task?

Historical Note
The very first comment on the OP's question -- long before any answers were posted -- was a question asked by myself, and it very pointedly asked:

Without using Integer.reverseBytes(cafeBabe)?

The question was two-fold:

Point out to the OP that a built-in method exists, and is likely the most optimal way of doing this.
Ask if they are trying to reinvent-the-wheel.

That comment/question has been removed.  If the OP responded to it, the response has been deleted as well and I never saw it.
This answer is not advocating the OP reinvent-the-wheel.  The Java JVM / JIT will have implemented the most efficient way of performing the operation, using internal features (such as @HotSpotIntrinsicCandidate) that are not necessarily available to the end-user.
Reinventing the wheel
public static int byteSwap(int a) {
    return ((a & 0xff000000) >>> 24) |
           ((a & 0x00ff0000) >>> 8)  |
           ((a & 0x0000ff00) << 8)   |
           ((a & 0x000000ff) << 24);
}

This function uses 6 distinct constants, 4 AND operations, 4 shifts, and 3 OR operations.
There is no point with the AND operation in ((a & 0xff000000) >>> 24) or in ((a & 0x000000ff) << 24) since the 24 bits which are being masked are immediately shifted out anyway.  This removes 2 constants, and 2 AND operations, which reduces the code to:
public static int byteSwap(int a) {
    return (a >>> 24)               |
           ((a & 0x00ff0000) >>> 8) |
           ((a & 0x0000ff00) << 8)  |
           (a << 24);
}

By reworking the order of second operation, we can remove another constant, the 0x00ff0000, and instead reuse the 0xff00 constant.  This eliminates the loading of the third bit mask constant, saving additional JVM byte code instructions:
public static int byteSwap(int a) {
    return (a >>> 24)           |
           ((a >>> 8) & 0xff00) |
           ((a & 0xff00) << 8)  |
           (a << 24);
}

This reworked version is very similar to the built-in Integer.reverseBytes() code in the system library:
@HotSpotIntrinsicCandidate
public static int reverseBytes(int i) {
    return (i << 24)            |
           ((i & 0xff00) << 8)  |
           ((i >>> 8) & 0xff00) |
           (i >>> 24);
}

I don't know if the difference in ordering gains any additional speed, but (dollars to donuts) the @HotSpotIntrinsicCandidate annotation probably does - so just use the built-in function.