Iterate over list and valid email address

This is a method I've used without any problems so far.

bool IsValidEmail(string email)
{
    try
    {
        var addr = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch
    {
        return false;
    }
}

To check the validity and handle each case you could do this.

var emailChecklist = emails.Select(x =>
    new { IsValid = IsValidEmail(x.Trim()), Address = x });

foreach(var email in emailChecklist)
{
    if (email.IsValid)
    {
        email.BccRecipients.Add(email.Address.Trim());
        sbInfoLog.Append($"Email: {email.Address.Trim()}\n");
    }
    else
    {
        sbAlertLog.Append($"Not valid email address: {email.Address}\n");
    }
}

I left the trim in the loop because I noticed that you didn't trim on the invalid email log. I assumed that you were trying to preserve the original value.


Main Flaw
You have committed the biggest C++ sin. You have a class that contains an owned pointer SLL *head; but you have not done any of the resource management.
Please look up the rule of three.
Currently your code is just broken because you forgot this. Currently any copy of the object (through the compiler generated copy constructor or assignment operator) will mean both objects are using the same underlying list. Thus updates to one will update the other.
You don't have a destructor so your objects just leak memory when they go out of scope.
Interface
Why are you exposing the SSL internal object via a public API?
SLL* createNewNode()

This is just a bad idea. Your container contains int objects the user of your object does not need to know about SSL objects. This leakage of scope is a massive problem in terms of maintainability.
Code Review
Don't do this in header files.
using std::cout;
using std::endl;

If I include your header in my code you change the behavior for me. cout and endl may seem benign but it general it is a bad habit. If you want to do confine it to the closest scope you can.
Sure have a print method.
    void printLL()

But why not pass the stream you want to print on as a parameter (you can even default to std::cout).  But the main way to print in C++ is to use operator<<() so you should define this (and just make it call printLL).
Prefer "\n" over std::endl. The only difference is the extra flush. There is no need to flush any buffers. The default built in automatic flushing will flush ehenever you need. Any extra flushes that you do will just make the code less effecient.
        cout<<endl;

Your list seriously has a limit of 255 elements!
        insertAtPos(n,0xFF);//max position so that it will add to end

also 0xFF is not the maximum value that an int can hold. You may want to look up a better value.
Wht does SSL not have a constructor that takes the data value?
        SLL *newNode = createNewNode();
        newNode->data = n;

This could have been written much easier with:
        SSL* newNode = new SSL(n); // SSL constructor does the rest of the work.


Refactor's answer is excellent and captures most points. One thing in your code which sticks out is the overuse of if. E.g. consider

get_bounds xs = if null xs
    then (0, 0)
    else (length xs, length $ head xs)

I think

getBounds [] = (0,0)
getBounds xs = (length xs, length $ head xs)

is much clearer. Or this, which looks really strange:

make_population_transition from to condition image | image origin == from =
    if (condition . population_count) image
            then replace image origin to
            else image
make_population_transition from to test image | otherwise = image

You should write

make_population_transition from to condition image
     | image origin == from &&
       (condition . population_count) image = replace image origin to
     | otherwise = image


Testing whether sums of cubes are Fibonacci numbers

You could change the order of your loops.

Loop over the Fibonacci numbers - there is only O(log N) of these less than N.

Then loop down from to cbrt(N) to cbrt(N/2) looking for the highest of the two cubes in its sum.


You can use a Map :

Map<String,Integer> freq = new HashMap<String,Integer>();
for(String word : words) {
    String w = word.toLowerCase();
    if (freq.containsKey(w)) {
        freq.put(w,freq.get(w)+1);
    } else {
        freq.put(w,1);
    }
}


As has already been pointed out, creating a list is preferable as it avoids the concatenation of large strings. However neither of your solutions is the most pythonic solution possible:

Whenever you find yourself appending to a list inside a for-loop, it's a good idea to consider whether you could use a list comprehension instead. List comprehensions aren't only more pythonic, they're also usually faster.

In this case the body of the loop is a bit big to fit into a list comprehension, but that's easily fixed by refactoring it into its own function, which is almost always a good idea software design-wise. So your code becomes:

def int_to_fizzbuzz(i):
    entry = ''
    if i%3 == 0:
        entry += "fizz"
    if i%5 == 0:
        entry += "buzz"
    if i%3 != 0 and i%5 != 0:
        entry = i
    return entry

fizzbuzz = [int_to_fizzbuzz(i) for i in range(start, end+1)]

However, while we're at it we could just put the whole fizzbuzz logic into a function as well. The function can take start and end as its argument and return the list. This way the IO-logic, living outside the function, is completely separated from the fizzbuzz logic - also almost always a good idea design-wise.

And once we did that, we can put the IO code into a if __name__ == "__main__": block. This way your code can be run either as a script on the command line, which will execute the IO code, or loaded as a library from another python file without executing the IO code. So if you should ever feel the need to write a GUI or web interface for fizzbuzz, you can just load your fizzbuzz function from the file without changing a thing. Reusability for the win!

def fizzbuzz(start, end):
    def int_to_fizzbuzz(i):
        entry = ''
        if i%3 == 0:
            entry += "fizz"
        if i%5 == 0:
            entry += "buzz"
        if i%3 != 0 and i%5 != 0:
            entry = i
        return entry

    return [int_to_fizzbuzz(i) for i in range(start, end+1)]

if __name__ == "__main__":
    start = int(input("Start Value:"))
    end = int(input("End Value:"))
    for i in fizzbuzz(start, end):
        print(i)

(Note that I've made int_to_fizzbuzz an inner function here, as there's no reason you'd want to call it outside of the fizzbuzz function.)


list.Add(input + @"\" + file.Name);

Seems a bit pointless: file.FullName would get you the fully qualified name without throwing information away and reconstructing it. In fact, that method could be simplified with Linq to

static string[] getFiles(string input)
{
    DirectoryInfo dinfo = new DirectoryInfo(@input);
    return dinfo.GetFiles("*.txt").Select(f => f.FullName).ToArray();
}

I also note that the .Net convention for the name would be GetFiles with an initial uppercase letter.

for (int i = 0; i < files.Length; i++)
{
    using (StreamReader sr = File.OpenText(files[i]))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            sw.WriteLine(s);
        }
    }
}

Since you don't care about i you could simplify things with foreach; and the initial value of s is unnecessary, so you could have

foreach (var filename in files)
{
    using (StreamReader sr = File.OpenText(filename))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            sw.WriteLine(s);
        }
    }
}

But now we get to two key points of the requirements which aren't explicitly stated:

If the files don't end with newlines, this code will insert newlines. That may or may not be intended, and it may or may not be desirable.
This code is using an Encoding to parse the bytes to strings, then using an Encoding to convert the strings back to bytes. The particular encoding used is implicit. This isn't particularly efficient, but it does have some benefits:

If the files were generated by Microsoft tools, they are quite likely to start with BOMs (even if they're UTF-8). In the nasty case that they mix UTF-8-BOM, UTF-8, and UTF-16 then you rely on the encoding conversion.
Even if the files are consistent, you're going to avoid the appearance of BOMs embedded in the text that a straightforward byte-by-byte concatenation would give.

It also has at least one non-performance-related disadvantage:

Regardless of the encoding of the input files, the output file is likely to be UTF-8-BOM, which may be an undesirable side-effect if they were all UTF-8 or UTF-16.

If you wanted a straight byte-by-byte conversion then it would be more efficient to use

using (var strmOut = File.Create(newName))
{
    foreach (var filename in files)
    {
        using (var strmIn = File.OpenRead(filename))
        {
            strmIn.CopyTo(strmOut);
        }
    }
}

If you can guarantee that the input files are all UTF-8-BOM then it would be more efficient to use

using (var strmOut = File.Create(newName))
{
    foreach (var filename in files)
    {
        using (var strmIn = File.OpenRead(filename))
        {
            strmIn.Position = 3;
            strmIn.CopyTo(strmOut);
        }
    }
}

although that's not production-quality code (should check that there are 3 bytes and that they correspond to a BOM).


Numerical Python code to generate artificial data from a time series process

Is

scipy.dot(A1, data[i-1, :]) + scipy.dot(A2, data[i-1, :])

a bug or a copy-paste error? According to the spec, the second term should have i - 2.
A 90% lead-in seems arbitrary. In fact, any lead-in would be arbitrary, as long as you didn't quantify how much the initial condition should fade. In any case, I recommend to pass it as a parameter (either percentage to discard, or - preferably - the desired decay of the initial condition).


Django query ManyToMany for tagged items

You are, more or less, manually performing in Python what can be achieved in SQL using Q objects. Basically, you can chain Q objects to create an SQL query on the InventoryItems with one WHERE clause for each part of your HTTP query.

Also note that, on queryset operations that will be converted to a WHERE clause (like get, filter...) as well as Q objects, the keywords arguments are ANDed together. So there is no need in doing tags.filter(Q(key = k) & Q(value__startswith = v)) since tags.filter(key=k, value__startswith=v) performs the same query and is more readable.

Building the tags research query should already include the lookup that span relationship and can be something like:

relevant_tags = Q()  # Fallback, if the query is empty will select everything
for tag_searched in query_items:
    tag_searched = tag_searched.lstrip(':')
    try:
        tag_name, tag_value = tag_searched.split(':', 1)
    except ValueError:
        # tag_searched did not contain any :
        query = Q(tags__value__startswith=tag_searched)
    else:
        query = Q(tags__key=tag_name, tags__value__startswith=tag_value)

    relevant_tags = relevant_tags & query

And from there, we can retrieve objects we want in a single query:

items = InventoryItems.objects.filter(relevant_tags)

A few things to note:

if iterable just before for element in iterable is pointless as the for loop will be a no-op anyway if the iterable is empty;
you can use EAFP rather than LBYL, especially if you expect one path to happen more frequently than the other. I made a wild guess that the user will use the name:value syntax of the query more often than the simple value one. It is also to show an alternate syntax.
you can clean your query better in the list-comprehension to avoid an extra lstrip in the computation. Or you can avoid the list-comp and perform the whole cleanup in the for loop:

for tag_searched in query.split(','):
    tag_searched = tag_searched.strip().lstrip(':')
    if not tag_searched:
        continue
    ...

you never use start or count, you should remove them.


New to immediately-invoked function expression with JavaScript, curious about placement

In this case, it makes no difference at all.  This IIFE really has no reason for even being there because all it contains is a single function.  Your code does use any of the usual benefits of an IIFE (like a local and protected scope) or capturing the arguments in a closure.

So the additional code that doesn't have any local variables of its own and doesn't use the passed in argument does not benefit at all from being in the IIFE, but there is no harm in putting it in the IIFE either.


The first thing that I noticed that could be improved is to use find_each instead of all.

all will load all the records from the database at once, which can blow up your server. Using find_each instead, you'll load records in batches.

Also, another thing here is that you're using heavily object in queries, for instance: UserSegment.find_by(user: user_discount.user) instead of UserSegment.find_by(user_id: user_discount.user_id)

When using object references like that, if the object isn't loaded rails will perform a query to retrieve the object - therefore this code have a N+1 problem in it - meaning you end up loading those objects (such as user, discount and segment) even though have basically the same info in the parent object already loaded.

So always prefer to ids instead of objects for those type of queries.

If I understood your problem correctly I think you can simplify greatly its performance and syntax by just leveraging ActiveRecord query options. Instead of loading the objects in memory and using ruby to do the verifications for you, you can just instruct ActiveRecord to perform joins and whatnot and just return to you the information that you need.

Here's how I'd do it:

First, for removing invalid user discounts I'd create a query that return them to me, like so:

class UserDiscount < ApplicationRecord
  belongs_to :user
  belongs_to :discount

  def self.invalid_user_discounts
    UserDiscount.
      joins("INNER JOIN discount_segments ON user_discounts.discount_id = discount_segments.discount_id").
      joins("INNER JOIN user_segments ON user_discounts.user_id = user_segments.user_id").
      where("user_segments.segment_id <> discount_segments.segment_id")
  end
end

See how instead of loading multiple classes I just let the powerful SQL and rails do the job for me? This query isn't too complicated to understand and does the same job as the previous loop.

Once we have a query that returns invalid discounts, I can use find_each and remove them:

def self.clean_user_discounts
  invalid_user_discounts.find_each do |user_discount|
    user_discount.destroy
  end
end

For creating discounts, I use the same approach, I let AR and SQL do the heavy lifting in this case, and just use the final formatted response to iterate over the results, like so:

def self.create_user_discounts
  query = UserSegment.
    joins("INNER JOIN discount_segments ON user_segments.segment_id = discount_segments.segment_id").select(:id, :discount_id, :user_id)

  query.find_each do |user_and_discount_segment|
    UserDiscount.find_or_create_by(
      discount_id: user_and_discount_segment.discount_id,
      user_id: user_and_discount_segment.user_id)
  end
end

Rails allows us to merge the two tables UserSegment and DiscountSegment and as well to select just the fields from that query that we need, in this case: user_id, discount_id - making the creation of UserDiscount much easier.

Finally, you can see the usage of find_or_create_by - this is provided by Rails as well, so we don't have to issue two commands.

full source code: https://gist.github.com/jonduarte/c54146cb7e00f0045193aad739301c13


Range of all variables in List in Prolog

Once you will have to hardcode your list to include all the variables from A1 to I9. Then you can iterate through it:

foreach(X, Your_list) do between(1, 9, X).


Yes, your code can indeed be simplified, as Xiaoy312 already demonstrated:

// Obtain the Relations array:
return JObject.Parse(jsonString)["Relations"]
     // Take the categories of all relations, flattening them into a single enumerable:
    .SelectMany(relation => relation["Categories"])
    // Filter out duplicate category objects (JToken.EqualityComparer uses DeepEquals internally):
    .Distinct(JToken.EqualityComparer)
    // Materialize the results into a list:
    .ToList();

This is also more efficient:

Using dynamic means that several things (such as method overload resolution) cannot be done at compile-time but must be done at run-time, which involves additional work.
Distinct uses a set internally, so it doesn't need to compare a new category against all other categories found so far - an internal hashcode lookup is often sufficient.

dynamic can be useful, but it doesn't work with extension methods (which Linq heavily depends on), so in this case it's more of a hindrance. About the only benefit here is that relation.Categories is slightly easier to write than relation["Categories"], but you do pay for that at run-time, and it handicaps your tools (no compile-time checks, no automated refactoring). Also keep in mind that dynamic is 'contagious': any expression involving something dynamic also becomes dynamic.

Another problem is that dynamic code is less self-descriptive. Is category.Name a string, or could it be a { "name": "Identity", "id": "5" } object? That sort of uncertainty makes code more difficult to maintain, at least in my experience. Static typing can be more restrictive and cumbersome, but it gives you more guarantees and tells you more about what sort of data your program expects to handle. Unless you have a good reason to stick with dynamic (in that case, throw a .Cast<dynamic>() in just before the .ToList() call) I would recommend creating a Category class.

Finally, I would make the filename a parameter and rename Method to something more descriptive such as LoadCategoriesFromJsonFile, and I would put some thoughts into error handling (what if the file doesn't exist, or if it's corrupted).


For a problem like this, the interviewer is not actually looking for the most efficient/well-known algorithm possible. They want you to demonstrate that you can solve simple problems, using OO principles (encapsulation, inheritance, polymorphism), C# language features (Generics, LINQ, TPL etc) as well as industry standard patterns and practices like TDD, SOLID, DRY and so on.

The solution you have written is good in that it solves the problem and correctly uses recursion (probably eliminating 90% of the competition). I had some spare time today, so I've written an alternative solution that demonstrates some of the things I just mentioned. It is by no means, "the answer", just one of many possible solutions.

class Program
{
    static void Main()
    {
        var input = new[,]
        {
            {0, 1, 0, 0, 0},
            {0, 0, 1, 1, 0},
            {0, 0, 0, 0, 0},
            {0, 1, 1, 0, 0}
        };

        var locator = new ClustersLocator<int>(1);
        var clusters = locator.LocateClusters(input);

        foreach (var cluster in clusters)
            Console.WriteLine(cluster);

        Console.ReadKey();
    }
}

Coord

A 2D coordinate (struct) used by Matrix and Cluster.

public struct Coord : IEquatable<Coord>
{
    public Coord(int n, int m) : this()
    {
        N = n;
        M = m;
    }

    public int N { get; private set; }
    public int M { get; private set; }

    #region ToString() and Equals()
}

Cluster

A list of Coords that is equal to another Cluster if it has the same Coords.

public class Cluster
{
    public Cluster(IEnumerable<Coord> coords)
    {
        if (coords == null)
            throw new ArgumentNullException("coords");

        Coords = coords;
    }

    public IEnumerable<Coord> Coords { get; private set; }

    // Override Equals() and GetHashCode() to compare Coords
    #region Equals() and ToString()
}

Matrix

A 2D matrix of generic values. Implements IEnumerable<Coord> to allow for easy enumeration of all coordinates. Contains helper methods for getting adjacent coordinates.

internal class Matrix<T> : IEnumerable<Coord>
{
    private readonly T[,] _values;

    public Matrix(T[,] values)
    {
        _values = values;
    }

    public Matrix(int rows, int columns)
    {
        _values = new T[rows, columns];
    }

    public T this[Coord coord]
    {
        get { return _values[coord.N, coord.M]; }
        set { _values[coord.N, coord.M] = value; }
    }

    public int Rows { get { return _values.GetLength(0); } }
    public int Columns { get { return _values.GetLength(1); } }

    public IEnumerator<Coord> GetEnumerator()
    {
        for (var n = 0; n < Rows; n++)
            for (var m = 0; m < Columns; m++)
                yield return new Coord(n, m);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerable<Coord> GetEqualAdjacentCoords(Coord coord)
    {
        return GetAdjacentCoords(coord)
            .Where(a => this[a].Equals(this[coord]));
    }

    public IEnumerable<Coord> GetAdjacentCoords(Coord coord)
    {
        var adjacent = new[]
        {
            new Coord(coord.N - 1, coord.M + 1),
            new Coord(coord.N - 1, coord.M),
            new Coord(coord.N - 1, coord.M - 1),
            new Coord(coord.N + 1, coord.M + 1),
            new Coord(coord.N + 1, coord.M),
            new Coord(coord.N + 1, coord.M - 1),
            new Coord(coord.N, coord.M + 1),
            new Coord(coord.N, coord.M - 1)
        };

        return adjacent.Where(InRange);
    }

    public bool InRange(Coord coord)
    {
        return coord.N >= 0 && coord.N < Rows
            && coord.M >= 0 && coord.M < Columns;
    }
}

ClusterLocator

The main algorithm. Also generic, and can locate clusters of any value.

public class ClustersLocator<T> : IClustersLocator<T>
{
    private readonly T _clusterValue;

    public ClustersLocator(T clusterValue)
    {
        _clusterValue = clusterValue;
    }

    public IEnumerable<Cluster> LocateClusters(T[,] matrix)
    {
        if (matrix == null)
            throw new ArgumentNullException("matrix");

        return LocateClusters(new Matrix<T>(matrix));
    }

    private IEnumerable<Cluster> LocateClusters(Matrix<T> matrix)
    {
        var clusters = new List<Cluster>();
        var visited = new Matrix<bool>(matrix.Rows, matrix.Columns);

        foreach (var coord in matrix.Where(c => !visited[c]))
        {
            visited[coord] = true;

            if (!matrix[coord].Equals(_clusterValue))
                continue;

            var cluster = new ClusterBuilder<T>(matrix, visited).Build(coord);
            clusters.Add(cluster);
        }
        return clusters;
    }
}

ClusterBuilder

The recursive part of the algorithm. Uses a Matrix and a single member of a cluster to locate the other members in the same cluster.

internal class ClusterBuilder<T>
{
    private readonly Matrix<T> _matrix;
    private readonly Matrix<bool> _visited;

    public ClusterBuilder(Matrix<T> matrix, Matrix<bool> visited)
    {
        _matrix = matrix;
        _visited = visited;
    }

    public Cluster Build(Coord seed)
    {
        var clusterCoords = new List<Coord> {seed};
        Build(clusterCoords, seed);

        return new Cluster(clusterCoords);
    }

    private void Build(List<Coord> cluster, Coord current)
    {
        _visited[current] = true;

        var nextCoords = _matrix.GetEqualAdjacentCoords(current)
            .Where(c => !_visited[c]);

        foreach (var next in nextCoords)
        {
            cluster.Add(next);
            Build(cluster, next);
        }
    }
}

And most importantly, tests for the public API!

[TestFixture]
public class ClusterLocatorTests
{
    [Test]
    public void Throws_if_matrix_is_null()
    {
        var sut = new ClustersLocator<int>(1);

        Assert.Throws<ArgumentNullException>(() => sut.LocateClusters(null));
    }

    [Test]
    public void Returns_empty_collection_if_matrix_is_empty()
    {
        var sut = new ClustersLocator<int>(1);

        var clusters = sut.LocateClusters(EmptyMatrix);

        Assert.That(clusters, Is.Empty);
    }

    [TestCaseSource("GetLocatesClustersTestCases")]
    public void Locates_clusters(int[,] matrix, IEnumerable<Cluster> expectedClusters)
    {
        var sut = new ClustersLocator<int>(1);

        var clusters = sut.LocateClusters(matrix);

        Assert.That(clusters, Is.EqualTo(expectedClusters));
    }

    private static IEnumerable<ITestCaseData> GetLocatesClustersTestCases()
    {
        var testCase1 = new TestCaseData(Matrix1, Clusters1);
        testCase1.SetName("Large matrix of mixed clusters");

        // Add more test cases as needed
        return new[] {testCase1};
    }

    #region Test data
}


Animations when navigation items are clicked

Consider what you would do if JavaScript were unavailable.  You would probably have more semantic markup, with a menu like this:

home

over

een dag bij

werkzaamheden

contact

and page items like this:

over

such that clicking on a menu item would scroll to the relevant page item.

Then, it's just a matter of using jQuery to intercept that click and replace the behaviour with a more polished animation.

function scrollTo(selector) {
    var destination = $(selector);
    $('html, body').animate({scrollTop: destination.offset().top}, 'slow');
}

$("nav > ul > li > a").bind("click", function() {
    scrollTo($(this).attr('href'));
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});


Some issues:

Every instance of Clock gets its own instance of plus and minus rather than attaching these functions to the prototype.
Clock.at sets a global variable c.
Clock.prototype.toString creates the format function each time it is called; you can move this out of the function and into a different scope so it is only created once.
plus and minus do a lot of checking that could be moved into a single set function and then this can also be called from the constructor (so that the same checks and rounding is also done in the constructor).
24 and 60 appear as magic constants. In this context it is easy to understand what they are but it would be better to assign them to named constants (HOURS_PER_DAY and MINUTES_PER_HOUR) that identify why those magic numbers are being used.

My suggestions:

module.export = (function(){
    var Clock = function( hours, minutes ) {
      this.set( hours, minutes )
    }

    Clock.at = function(hours, minutes) {
      return new Clock(hours, minutes);
    }

    Clock.HOURS_PER_DAY = 24;
    Clock.MINUTES_PER_HOUR = 60;

    Clock.prototype.set = function( hours, minutes ){
        var hrs = Math.round( hours || 0 );
        var mns = Math.round( minutes || 0 );

        this.hour = ( hrs + Math.floor( mns / Clock.MINUTES_PER_HOUR ) ) % Clock.HOURS_PER_DAY;
        if ( this.hour < 0 )
        {
            this.hour += Clock.HOURS_PER_DAY;
        }

        this.minute = mns % Clock.MINUTES_PER_HOUR;
        if ( this.minute < 0 )
        {
            this.minute += Clock.MINUTES_PER_HOUR;
        }

        return this;
    }

    Clock.prototype.plus = function(minutes) {
     return this.set( this.hour, this.minute + minutes )
    },

    Clock.prototype.minus = function(minutes) {
     return this.set( this.hour, this.minute - minutes );
    },

    Clock.prototype.equals = function(other) {
     return this.hour == other.hour && this.minute == other.minute;
    }

    function format(n) {
        return n >= 10 ? n : "0" + n;
    }

    Clock.prototype.toString = function() {
          return format(this.hour) + ":" + format(this.minute)
    }

    return Clock;
})();


Setting PHP variables for 2 years back and 2 years in the future

Only three-four line code rquired for getting required result:-

<?php

$date = date("Y"); //current year

$date_range = range($date-2, $date+2);//get year range

//print_r($date_range); //print year range

echo implode(',',$date_range);//comma seperated date range

Output:- https://eval.in/944817


Load from dictionary or database if not found

Using ContainsKey() together with TryGetValue() seems a little bit too much. Just change it like so

if (_roomModels.TryGetValue(modelName, out model))
{
    return true;
}

which is much easier to read and faster for items which are in the dictionary.

If the columns in the database allow null values you should check first with Convert.IsDBNull() so the method doesn't blow in the users face at any of the Convert.ToXX() methods.

The Where clause of the sql query looks like it is not working.
You should at least let the columns have some space to breathe which makes the query easier to read.


Determining optimal weight lifting bar configuration

The layout of your program is non-standard.  You have:

main program part 1
function definitions
main program part 2

Keep your main program together, don't split it up by adding functions in the middle, at least, not without a compelling reason.

There is minimal error checking in the program.  If the target weight is less than the bar weight, this is not reported.

    for  i, weight in enumerate(weights):
        if int(remaining / weight) % 2 == 0:
            nweights.append(int(remaining/ weight))
        else:
            nweights.append(int(remaining/ weight) - 1)
        remaining = remaining - nweights[i]*weights[i]
        if remaining == 0:
            break

    listweights=zip(nweights, weights)

This code is duplicated in user_one(), user_two() and perfect_combo().  You should move this into a function.

The code computes the number of a specific weight, and then adds the number to a list if it is even, or 1 less if it is odd.  Presumably, this is because the weights have to be added in pairs, one on each side of the bar, but this is never spelt out.

Finally, the list is zipped with the original list of weight options, to create pairs of counts and weights.

Let's create the function which does this computation, but let's make it more general.  You might have different bar types, say a light weight bar and a heavy weight bar.  The light weight bar would be lighter, and perhaps uses a different set of weights, but the algorithm would remain the same.  So the available weights should be passed in:

def weights_in_pairs(added_weight, available_weights):

    """Compute and return list of numbers and sizes of weights to
    form the desired additional weight for bar-bell.  Also returns any
    excess weight that could not be added."""

    weights = []
    remaining = added_weight
    for weight in available_weights:
        pairs = int(remaining / (2*weight))
        if pairs  > 0:
            weights.append((pairs * 2, weight))
            remaining -= 2 * pairs * weight

    return weights, remaining

Instead of dealing with even/odd numbers, we double the weight and compute the number of pairs that can be added add.  Instead of zipping at the end, we add the (count, weight) tuple to the weights list; this allows us to omit the zero counts, to simplify printing later

    for weight in listweights:
        if weight[0] >= 2:
            print(f"{weight[0]} | {weight[1]}'s")

    if remaining !=0:
        print(f'the correct weight combination cannot be found,'
              f'the remaining weight is: {remaining} pound')

This code is also duplicated between user_one(), user_two() and perfect_combo().  Again, we'll move this into a function.

def print_weights(weights, remaining):

    """Print out the weights to be added to the bar-bell,
    and the amount of un-added weight, if necessary."""

    for n, weight in weights:
        print(f"{n} | {weight}'s")

    if remaining != 0:
        print(f'the correct weight combination cannot be found,'
              f'the remaining weight is: {remaining} pound')

Note that the for loop immediate extracts the tuple into two variables, with the names n and weight.  This allows us to use these named quantities in the body of the loop, instead of indexes like weight[0] and weight[1] where the reader will have to look elsewhere to determine what was stored in the different indexes.

Also, since we skipped added the zero-count weights, we didn't need the if weight[0] >= 2: statement.

We can combined the above two functions, to compute and print out the information displayed by user_one() and user_two().  Again, we'll pass in arguments for the desired weight, the bar weight, and the available weights:

def print_bar_configuration(target_weight, bar_weight, weights):

    """Compute and print bar-bell configuration for given weights."""

    listweights, remaining = weights_in_pairs(target_weight - bar_weight, weights)

    print(f'{bar_weight}lb bar')
    print(f'{target_weight}lbs')

    print_weights(listweights, remaining)

With the above functions, perfect_combo() can be simplified:

def perfect_combo(heavy_weight, light_weight):

    """Compute and print optimal additional weight configuration."""

    weight_difference = heavy_weight - light_weight

    print(f"Add {weight_difference}lbs for heavier weight")

    listweights, remaining = weights_in_pairs(weight_difference, weights)
    print_weights(listweights, remaining)

Note: This raise the question of "what happens if the first weight was lighter than the second?"  Perhaps your program should mention that requirement, and test for it.  Or adapt the reversed data input.

Using the above functions, we can simplify the main program, moving and combining the code at the top with the code at the bottom.  Also, renaming odd variables like target_weight1 to something more meaningful:

if prog_select == 1:
    target_weight = int(input('Enter weight: '))
    print_bar_configuration(target_weight, bar_weight, weights)
elif prog_select == 2:
    heavy_weight = int(input('Enter heavier weight: '))
    light_weight = int(input('Enter lighter weight: '))

    if heavy_weight - light_weight > 99:
        print("You might want to use separate bars...")
    else:
        print_bar_configuration(light_weight, bar_weight, weights)
        perfect_combo(heavy_weight, light_weight)
else:
    print("That's too many peeps on one bar!")


Singleton method for Redis connection in Python

The Singleton pattern is a way to work around the absence of global variables in Java. But Python has global variables, and it's usually possible to write shorter and simpler initialization code if you use them, for example:

import os

from redis import StrictRedis

_connection = None

def connection():
    """Return the Redis connection to the URL given by the environment
    variable REDIS_URL, creating it if necessary.

    """
    global _connection
    if _connection is None:
        _connection = StrictRedis.from_url(os.environ['REDIS_URL'])
    return _connection

Alternatively, you could memoize the function, for example using functools.lru_cache:

from functools import lru_cache
import os

from redis import StrictRedis

@lru_cache(maxsize=1)
def connection():
    """Return the Redis connection to the URL given by the environment
    variable REDIS_URL, creating it if necessary.

    """
    return StrictRedis.from_url(os.environ['REDIS_URL'])


A few minors really:

Standard C# naming convention for methods is PascalCase. So should be IsPristine.
If it's important (or nice) to know which specific sequence is yielding the false result then you should consider returning that from the method. Something like this:

public class PristineResult
{
    public readonly bool IsPristine;
    public readonly string OffendingSequence;
    public readonly string OffendingIndex;

    public PristineResult(bool isPristine, string offendingSequence = null, int offendingIndex = -1)
    {
        IsPristine = isPristine;
        OffendingSequence = offendingSequence;
        OffendingIndex = offendingIndex;
    }
}

static PristineResult IsPristine(string sourceCode)
{
    using (var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }))
    {
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" });
        parameters.GenerateExecutable = true;

        int length = sourceCode.Length;

        for (int i = 0; i < length; i++)
        {
            for (int j = 1; j < length - i; j++)
            {
                string sourceWithRemoval = sourceCode.Remove(i, j);
                CompilerResults results = csc.CompileAssemblyFromSource(parameters, sourceWithRemoval);

                if (results.Errors.Count == 0)
                {
                    return new PristineResult(false, sourceCode.Substring(i, j), i);
                }
            }
        }
    }

    return new PristineResult(true);
}


TamperMonkey Script to replace the YouTube favicon with the channel logo

img.style = "position: absolute; top: -100000px; left: -100000px;";
document.body.appendChild(img);

img.parentElement.removeChild(img);

This seems weird.  The canvas can be drawn from an unattached image and these lines can be removed.

  if(url.src) url = url.src;

  img.src = url;

A more idiomatic phrasing is img.src = url.src || url.

 .querySelectorAll("link[rel *= 'icon']");

Unless you have something specific in mind, I'd use [rel='icon'] here.  It's faster, and not clear that matching an exotic future variant like <link rel="BiscottiConfig"> is going to be desirable.

let

Except for the final loop, every use of let in your script can be replaced by const.  It's a good habit, even if the aesthetics are inferior to let or var.

const urlRegex = /https:\/\/yt3.ggpht.com\/a[/-]{1,2}[A-Za-z\d-_]+/;

roundImageToDataUrl(JSON.stringify(window.ytInitialData).match(urlRegex)[0]).then(setFavicon);

This looks like a misstep.  Youtube avatars have id=img; why not just roundImageToDataUrl( document.getElementById("img").src )?

Dealing with future changes to the host page is a constant challenge with userscripts.  There are many things that have to remain unchanged for this to work (the image host, the URL format, the name, content and encoding of ytInitialData) and I'll predict that some of them won't.  Selecting the avatar itself with semantic markup is likely to be less brittle, and easier to fix if the markup changes (assuming there will always be an avatar and it will always have some semantics attached to it).


Using something other than form field's value in Vue

This is not the Vue-way to do it. Vue does not recommend the use of $refs. And in this case, you can also avoid it.

Your current code is:

<select name="screw[type]" ref="screw_type_select" v-model="form.screw.type">
   <option value="My value" data-value=""></option>

I would recommend using v-for to loop through your options, and keep all your options in your data.

So for example: (This is how it is done in the Vue JS official documentation)

data() {
    return {
        options: [
             {
                 text: "<?php _e('My value', 'context'); ?>",
                 value: "My value"
             },
             ...
        ]
    }
}

And then:

<select name="screw[type]" v-model="form.screw.type">
  <option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
  </option>
</select>

Instead of using the watch, you can use a computed property.

computed: {
    selectedScrewType() {
        return this.options[this.form.screw.type].text;
    }
}

Then you can use {{ selectedScrewType }} in your template.


A Blum Blum Shub pseudorandom RNG implementation in JavaScript

You haven't declared cachedx, so it's implicitly global. Turn on strict mode (put 'use strict'; at the top of your script) to prevent this in the future. I'm not sure why cachedx would be necessary anyway, though:

/** Get next item from the random number generator. */
function next() {
    x = x * x % M;
    return x;
}

Also, there's no point in initializing things to undefined. That's the default. The chance that something might be uninitialized when you attempt to use it is a bad sign, though, and you're probably right that it would be better to be able to create instances of the generator:

function Random(p, q, seed) {
    var m = p * q;

    if (seed == 0) {
        throw new Error("The seed x[0] cannot be 0");
    } else if (seed == 1) {
        throw new Error("The seed x[0] cannot be 1");
    } else if (gcd(seed, m) != 1) {
        throw new Error("The seed x[0] must be co-prime to " + m);
    }

    this.m = m;
    this.state = seed;
}

Random.prototype.next = function () {
    var x = this.state;
    var next = x * x % this.m;

    this.state = next;
    return next;
};

noting that you don't need to call toString to concatenate a string and a number.


InputStream Wrapper that closes the stream once reading is done

The general idea of a wrapper stream that closes the inner stream automatically once its end is reached is fine, but your implementation leaves somewhat to be desired.

First, if you're going to wrap a stream, then do a complete job.

At minimum, do not fail to override close() properly.  I understand that you're trying to solve a problem of close() not being called, but you don't know for sure how instances will be used once you hand them off to another component.  If the wrapper is closed before the end of the inner stream is reached, then you want the inner stream closed, too.
It would be a very good idea to delegate the other InputStream methods, too, with the possible exception of read(byte[]).  That will provide the full capabilities of the underlying stream to the wrapper's consumer, including, but not limited to, efficient block reads.  For this purpose, you should consider inheriting from FilterInputStream instead of directly from InputStream.

Second, you have to consider how to handle exceptions.  With a proper close() method on the wrapper, you're not limited to having read close the inner stream when an exception occurs.  Nevertheless, that might still be a good strategy.

Third, your wrapper doesn't necessarily provide a complete solution to the problem.  No matter what you do, a situation could arise in which the wrapper is abandoned before the inner stream is closed.  If you want to attend to that, too, then your best option is to provide a cleanup strategy based on soft, weak, or phantom references.  If you don't already know how to do this then now is a good time to learn -- it's a useful skill to have.

On the other hand, you should also consider avoiding the non-closure problem differently, by using a stream for which that's a non-issue. ByteArrayInputStream is such a stream.  Using that would mean reading the original data into memory yourself, so you would have control over closing that stream.  Failing to close a ByteArrayInputStream is no big deal.


I know nothing about your business logic but you're trying to transpose matlab in Python and it doesn't look like anything: there are some useless parameters, you are building arrays only to take their size. I'll try to provide advices to clean up the code and maybe others will provide runtime improvements.

Remove unused variables like F_bottom or tend which is only an alias to years.
Replaces calls like arr = np.linspace(begin, end, size); var = arr.size with var = size if you don't plan on using the array at all.
Use slice assignment to eliminate visual clutter.
Remove update_bc_dirichlet as you already perform the same kind of operation directly in the loop: stay consistent and see previous point.
Remove linalg_solver as it only indirects a single function call. If you want to avoid lookups in the loop, create an alias as local variable.
Some of the constants should either be extracted out of the function as real constants or defined as parameter with default values.
0 * np.ones(..) is np.zeros(..)
Use docstrings instead of comments to document your functions.

I would also turn adv_diff into a generator, but only because I don't know numpy enough to come up with a more idiomatic code:

import numpy as np
import scipy as sp
from scipy.sparse import spdiags
from scipy import special
import numba as nb

@nb.jit
def adv_diff(D, w, years, L=30, phi=1, dx=0.1, dt=0.001):
    """What does this function do?"""
    N = int(L / dx) + 1
    C1 = np.zeros((N, 1))
    C1[0] = 1

    linalg_solver = np.linalg.solve
    AL, AR = AL_AR_dirichlet(D, w, phi, dt, dx, N)

    yield C1
    for _ in range(int(year/dt)):
        C1 = linalg_solver(AL, AR.dot(C1))
        yield C1
        C1[:2, 0] = 1, 1

@nb.jit
def AL_AR_dirichlet(D, w, phi, dt, dx, N):
    """AL_AR_dirichlet: creates AL and AR matrices with Dirichlet BC"""
    s = phi * D * dt / dx / dx #
    q = phi * w * dt / dx #
    e1 = np.ones((N, 1)) #
    AL = spdiags(np.concatenate((e1 * (-s / 2 - q / 4), e1 * (1 + s), e1 * (-s / 2 + q / 4)), axis=1).T, [-1, 0, 1], N, N).toarray()
    AR = spdiags(np.concatenate((e1 * (s / 2 + q / 4), e1 * (1 - s), e1 * (s / 2 - q / 4)), axis=1).T, [-1, 0, 1], N, N).toarray()

    AL[0, :2] = 1, 0
    AL[-1, -2:] = -s, 1 + s
    AR[0, :2] = 1, 0
    AR[-1, -2:] = s, 1 - s

    return AL, AR

if __name__ == '__main__':
    D = 0.5
    w = 3
    t = 10
    C = np.asarray(list(adv_diff(D, w, t)))


You can use a GROUP BY clause to group by JS_TITLE, then you must transpose the record into a column matrix:

SELECT
    JS_TITLE,
    count(EMP.JS_REF)
FROM EMP
LEFT JOIN JOB_STATUS ON EMP.JS_REF = JOB_STATUS.JS_REF
GROUP BY JS_TITLE


How about replacing "s" of plural with the word "List":

interface VegetablePresenterListFactory {
    List<VegetablePresenter> create(AllVegetables allVegetables);
}

Like you said, the s in the middle is indeed a problem.
The difference is too small: it can lead to errors, and it hurts readability.

The same is true for name vs names in this code snippet:

void printNames(List<String> names) {
    for (String name : names) {
        // ...
    }
}

Although errors may sound unlikely because name and names are completely different types,
it can still happen when there are methods with the same name that happen to work on both objects,
for example isEmpty.

In such cases I use the suffix List to disambiguate, so nameList.
It's true that the term "List" is a bit redundant.
But it's better to be redundant than ambiguous,
so the little redundancy is justified by the improved readability.

UPDATE

You mentioned in the comment that "List" is a bit unfortunate if in the future you change the interface to use a Set instead of a List.
I think that's a moot point.
Changing the interface is a big deal,
and must be done carefully.
If you change the method to return a Set instead of a List,
I think you should be careful enough to notice that the interface name should change as well.
In terms of migrating users of the API,
this should not be a significant additional burden.

That said, I do have an alternative offering, using the word "Items" instead of "List":

interface VegetablePresenterItemsFactory {
    List<VegetablePresenter> create(AllVegetables allVegetables);
}

The good thing about "Items" is that it's less technical.
It's vague enough to be flexible, but not too vague to be meaningless.
Perhaps there are even better synonyms, you get the idea.


Generating two .csv files from named parameters

Everything looked pretty good in general, until I got to the (let [output_directory ... part, then your indentation got all wonky! Part of the problem is that there are a couple of really long lines, and it's difficult to keep them short when you're nested so many layers deep into an S-expression. Shortening your lines and making sure that everything lines up from line-to-line in an intuitive way will solve this.

First of all, I believe it is idiomatic to include all your use/require/import statements within the namespace definition, like so:

(ns my_cli_clojure.core
  (:require [clojure.data.csv :as csv]
            [clojure.java.io :as io]
            [me.raynes.fs :as fs]
            [clojure.tools.cli :refer [cli] :as c]
            [clojure.string :as s])
  (:gen-class :main true))

Notice that I added [clojure.string :as s] -- this abbrevation will come in handy in shortening some of the later lines, in which you have a lot of fully-qualified references to clojure.string methods.

Next, just an aesthetic spacing tweak here:

(defn write-csv-data [& {:keys [data outfile] :or {data "", outfile ""}}]
  (csv/write-csv outfile data))

Your code was fine, I just find my version easier to read at a glance. I generally try to avoid using line-breaks whenever the code I'm writing looks sufficiently compact on less lines. When the lines start getting long, I will think more about where it would make the most sense to break them up. (I also renamed write_csv_data to write-csv-data; it's idiomatic in Clojure to name symbols using hyphens instead of underscores)

More spacing adjustments here:

(defn -main [& args]
  (let [[options args banner]
        (c/cli args
               ["-d" "-dome" "Dome Identifier" :default "dome1"]
               ["-p" "-principal" "Principal code" :default "kraft"]
               ["-o" "-output-directory" "Output file" :default "."]
               ["-h" "-help" "Show Help" :flag true :default false])]

Here is how I would tackle the part at the end:

(let [out-dir (:output-directory options)]
  (if-not (fs/exists? out-dir)
    (fs/mkdirs out-dir))
  (doseq [n (s/split (:dome options) #",")]
    (let [dome-id (first (s/split n #"-"))]
      (with-open [out-file (io/writer (str out-dir "/" dome-id ".csv"))]
        (write-csv-data :data [["dome_identifier" "name"]
                               [dome-id (last (s/split n #"-"))]]
                        :outfile out-file))
      (with-open [dome-principal-file
                  (io/writer (str out-dir "/dome_principal." dome-id ".csv"))]
        (write-csv-data :data [["dome_identifier" "principal_code"
                                "currency_code" "active" "latitude" "longitude"]
                               [dome-id (:principal options) "" "t" "" ""]]
                        :outfile dome-principal-file)))))))

Changes:

I shortened a few symbol names, like output_directory => out-dir and dome_identifier => dome-id.
I changed the two parts with the pattern like (s/join "/" [out-dir (s/join "." [dome-id "csv"])]) to (str out-dir "/" dome-id ".csv"), which is more concise and easier to read. Keep it simple!
I simplified (first (reverse (s/split n #"-"))) to (last (s/split n #"-")).
There's a part of your code where you created a list of strings by doing something like this: (s/split "first-string second-string third-string fourth-string" #"\s+"). That's clever, but the downside is that it leaves you with a long string that you can't break in order to shorten your lines. In this case, I think it makes more sense just to type e.g. ["first-string" "second-string" "third-string" "fourth-string"].

Hope that helps!


This looks pretty good. Some suggestions:

[[ is preferred over [ in Bash.
This script could benefit from set -o errexit -o nounset -o pipefail. You'll need to set cpu_cores=0 before referring to it in the loop, but that's just best practice.
Dividing by one isn't going to do much :)
The quotes are a cute feature, but I'd much rather see a summary of the point in them than the full sentences. Something like

  Treat 15 minute load average above 1 as critical.

A useful tactic I've found when dealing with comments is to think how you could name things to avoid comments altogether. Code can't lie, and names are very much like comments enshrined in code, so if you for example rename minute15 to quarter_load_average or something else human readable you should be able to remove the

  Find out a load was before 15 minutes.

comment above it.
Since you're only interested in one row from /proc/cpuinfo I would grep for it. Your goal of making the script stand-alone should be weighed against at least

maintainability, which will suffer greatly if you only use builtin commands,
speed, which is already not great for read, and
availability of grep, which is pretty much universal by now.

You can redirect a line to standard input using some_command <<< "$line" to avoid redundant echos. So echo "$quarter_load_average*100/1" | bc could instead be bc <<< "$quarter_load_average*100/1".


Use lodash to make Your iteration "readable".

And use async to handle end of asynchronous iteration to properly respond with "end of loop"

var _ = require('lodash');

var something = ['a','b','c'];
function asyncInIteration(skinArray)  {

   request("/someaddresshere", function (err, response, data)  {
      var functions = []; // array of functions that will be called

      // generating array of functions
      _.times(something.length,
          function() {
              // pushing function to functions list
              functions.push(function(done){ // "next" is necessary to inform async module about finishing call
                  request("/someotheraddress", function (err, response, data) {
                      // doing something
                      console.log("\n--------");
                      console.log("RESPONSE:", data);
                      console.log("--------\n");
                      done();
                  });
              });
          });

      // can change to .series if You want to make it synchronous (not parallel)
      async.parallel(functions, function(){
          console.log('End of loop');
      });
   });
}

P.S. In fact my code looks like not so simple, but there is no another elegant way to control asynchronousity. Maybe Promise object will be easy to work, but I don't think it's suitable for current task.


Check if a type is of any from a list of types?

Here is a run-time and a compile-time approach. For the compile-time approach I only show how it works for 3 type parameters and for 20 type parameters to show the concept. You can easily add more methods/classes for the number of type parameters you need.

Scroll down to the bottom to see some usage examples.

public static class RuntimeTypeCheckExtensions
{
    public static bool IsAssignableToAnyOf(this Type typeOperand, IEnumerable<Type> types)
    {
        return types.Any(type => type.IsAssignableFrom(typeOperand));
    }

    public static bool IsAssignableToAnyOf(this Type typeOperand, params Type[] types)
    {
        return IsAssignableToAnyOf(typeOperand, types.AsEnumerable());
    }

    public static bool IsAssignableToAnyOf<T1, T2, T3>(this Type typeOperand)
    {
        return typeOperand.IsAssignableToAnyOf(typeof(T1), typeof(T2), typeof(T3));
    }

    public static bool IsAssignableToAnyOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(this Type typeOperand)
    {
        return typeOperand.IsAssignableToAnyOf(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13), typeof(T14), typeof(T15), typeof(T16), typeof(T17), typeof(T18), typeof(T19), typeof(T20));
    }
}

public static class CompileTimeTypeCheckUtils
{
    public static IsAssignableToAnyOfWrapper<T1, T2, T3> IsAssignableToAnyOf<T1, T2, T3>()
    {
        return new IsAssignableToAnyOfWrapper<T1, T2, T3>();
    }

    public static IsAssignableToAnyOfWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> IsAssignableToAnyOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>()
    {
        return new IsAssignableToAnyOfWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>();
    }
}

public class IsAssignableToAnyOfWrapper<T1, T2, T3>
{
    public void OperandToCheck(T1 operand) { }
    public void OperandToCheck(T2 operand) { }
    public void OperandToCheck(T3 operand) { }
}

public class IsAssignableToAnyOfWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>
{

    public void OperandToCheck(T1 operand) { }
    public void OperandToCheck(T2 operand) { }
    public void OperandToCheck(T3 operand) { }
    public void OperandToCheck(T4 operand) { }
    public void OperandToCheck(T5 operand) { }
    public void OperandToCheck(T6 operand) { }
    public void OperandToCheck(T7 operand) { }
    public void OperandToCheck(T8 operand) { }
    public void OperandToCheck(T9 operand) { }
    public void OperandToCheck(T10 operand) { }
    public void OperandToCheck(T11 operand) { }
    public void OperandToCheck(T12 operand) { }
    public void OperandToCheck(T13 operand) { }
    public void OperandToCheck(T14 operand) { }
    public void OperandToCheck(T15 operand) { }
    public void OperandToCheck(T16 operand) { }
    public void OperandToCheck(T17 operand) { }
    public void OperandToCheck(T18 operand) { }
    public void OperandToCheck(T19 operand) { }
    public void OperandToCheck(T20 operand) { }
}

Usages:

Type someType = ...

// Three example usages of run-time check (using generic types, params and IEnumerable):
if (someType.IsAssignableToAnyOf<string, int, double>())
{
}

if (someType.IsAssignableToAnyOf(typeof(string), typeof(int), typeof(double)))
{
}

IEnumerable<Type> enumerableOfAcceptedTypes = new Type[]
{
    typeof (string),
    typeof (int),
    typeof (double)
};

if (someType.IsAssignableToAnyOf(enumerableOfAcceptedTypes))
{
}

// Two example usages of compile-time check:
CompileTimeTypeCheckUtils.IsAssignableToAnyOf<string, int, long>().OperandToCheck(5); // <-- No compile-time error

CompileTimeTypeCheckUtils.IsAssignableToAnyOf<string, int, long>().OperandToCheck(5F); // <-- Compile-time error


Is this a sensible way to implement a model?

This smells slightly odd to me. Why would the class of customers know about what customers are actually participating in the model at the moment? Is there a need to even have knowledge of all the customers in the model overall? (Even in a simulation, you'd have that knowledge as part of the harness, not the customers themselves.)

No, I'd instead model the collection of all potential customers as an instance of another class (the catchment? the clientele?) and would avoid having public static methods in any class at all. That collection might well just be a simple wrapper around a core collection class instance, but I'd be making it a proper member of the model simply because the collection of customers is a model participant. (Well, if it isn't then you have no reason to keep a list of all customers at all.) The other advantage of working this way is that you  can then easily adapt to a growing business that opens a second shop far enough away from the first that virtually nobody goes to both shops…


I don't like this:

do
{
    printf("Card number: ");
    scanf("%lld", &no);
}

while(no<10);

That blank line makes it look like the while (); is a separate (possibly infinite) loop.  I recommend writing the while keyword straight after the closing brace, like this:

do {
    printf("Card number: ");
} while (scanf("%lld", &no) != 1);

(I've also changed the test so that we don't access an uninitialised no if the scanf() fails - it's still flawed, though, as any permanent stdin failure will lead to an infinite loop).

It's not clear why we have d_1, d_2, ..., etc. when all we do with them is to copy them into array members - why not just assign to the array members directly?

Instead of dividing no by successively bigger numbers each time, we could modify it as we go, like this:

d_16 = no % 10;
no /= 10;
d_15 = no % 10 * 2;
no /= 10;
d_14 = no % 10;

It's starting to become clear how to transform this into a loop.  The missing part is whether to multiply by 2 at each step; we can tell whether the loop index is even or odd, by considering it modulo 2.

Once we are considering the digits in a loop, we can perform the addition as we go, meaning that we no longer need all those local variables.


Notice in @alecxe's answer how he flipped the loops:
instead of iterating over tags and then lines,
he's iterating over lines and then tags.
This performs much better,
because only one BeautifulSoup is created per line,
in contrast with your implementation
where an instance is created for every tag and line pair,
which is many more instances of BeautifulSoup,
and wasted processing.

One more improvement over that could be using just one instance of BeautifulSoup,
if you can join all the lines into a single document,
instead of processing line by line:

soup = BeautifulSoup("\n".join(htmlist), "html.parser")

tags = defaultdict(set)
for tag in soup():
    tags[tag.name] |= set(tag.attrs)

for tag_name in sorted(tags):
    print("{name}:{attrs}".format(name=tag_name, attrs=",".join(sorted(tags[tag_name]))))

However this is not possible with the given lines,
because this line is invalid HTML and will mess up the document:

 '
<a href="/w/index.php?title=Special:Book&amp;bookcmd=render_article&amp;arttitle=Main+Page&amp;oldid=560327612',

If possible, I suggest to fix this line, and use the above approach.

 '

',


Your animation isn't smooth because the ball is jumping 9 pixels for every frame. If you want smooth animation, change your "speed" to a much smaller number.

Animation is a set of trade-offs. The speed is a simple multiplier of how many frames you display each second times how many pixels you move in each frame. As the number of pixels you move goes up, the more jerky the animation will be. Likewise, the more often you update, the faster your animation will go. You need to decide which is more important: smoothness or speed.


After profiling your code as:

import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
for it in range(0,10000):
    getAlignmentData(source, sequence, sstart, tresholds)

pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()

You will get:

1370129 function calls (1370122 primitive calls) in 3.249 seconds

   Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
10000    1.003    0.000    3.249    0.000 test.py:71(getAlignmentData)
20000    1.071    0.000    1.684    0.000 test.py:38(getAllGaps)
20000    0.171    0.000    0.171    0.000 {numpy.core.multiarray.array}
20000    0.160    0.000    0.160    0.000 {method 'reduce' of 'numpy.ufunc' objects}
10000    0.018    0.000    0.121    0.000 {method 'min' of 'numpy.ndarray' objects}
400022    0.119    0.000    0.119    0.000 {method 'append' of 'list' objects}
180000    0.107    0.000    0.107    0.000 {method 'replace' of 'str' objects}
100000    0.106    0.000    0.106    0.000 {range}

You can use Cython or f2py to optimise memory management starting with getAllGaps, which is simpler, and then go for getAlignmentData.

Keep in mind that you need to deactivate outputs and take long runs to measure real speedup.

If you compile your code using nuitka you can get 9x speedup.

     110128 function calls (110121 primitive calls) in 0.355 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
20000    0.158    0.000    0.158    0.000 {method 'reduce' of 'numpy.ufunc' objects}
10000    0.011    0.000    0.101    0.000 /usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/_methods.py:28(_amin)
10000    0.022    0.000    0.096    0.000 /usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/numeric.py:141(ones)
20000    0.025    0.000    0.081    0.000 /usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py:192(compile)
10000    0.008    0.000    0.076    0.000 /usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/_methods.py:25(_amax)
20000    0.056    0.000    0.056    0.000 /usr/local/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py:230(_compile)
10000    0.037    0.000    0.037    0.000 {numpy.core.multiarray.copyto}
10000    0.037    0.000    0.037    0.000 {numpy.core.multiarray.empty}

All you need to do is install nuitka and run:

$ nuitka mycode.py

You also need a larger dataset to run a proper benchmark. Since it's easy to keep small data in cache, the profiler can provide misleading results.


Moving List View items from one list to another

Before thinking about how to write this in a more elegant way, you should first ask yourself: is this code actually correct? The “problem” with that code is that you're iterating the collection you're modifying. Quite often (for example in the case of List<T>), that's not allowed and your foreach would throw an exception. Fortunately for you, the enumerator of ListViewItemCollection iterates over a snapshot of the collection of the items, so your code will actually work fine (although I didn't find this behavior documented anywhere).

Now, if you want to refactor code like this, just have a look at what's the same and what's different. You can notice that the only different thing in the two branches is the source of the foreach. So, just create a local variable for it, set it correctly and then have common code that iterates it:

private static void MoveItem(ListView source, ListView dest, bool all)
{
    var items = all ? source.Items : source.SelectedItems;

    foreach (ListViewItem item in items)
    {
        source.Items.Remove(item);
        dest.Items.Add(item);
    }
}


Converting a region code (short string up to 4 characters) to a 32-bit integer

Even if the char array is not aligned, your *((uint32_t *)buf) will be correct: the compiler will ensure the necessary operations are performed.

Note that I used unit32_t: the C standard does not guarantee the size of an int.

One thing: since these are 4 byte integers, you can use an endianness-independent way of doing things by using htonl()/ntohl().


Changing html element with click event: how to restore default state of element using jQuery if/else statement

This is actually a pretty classic problem and I've addressed it in my code on numerous occasions. One of the simplest ways to do what you're doing is to just reset the state for all the elements and then correct it.

function txtResize() {
    var clicked = this.id;

    if ( clicked === "Text1" || clicked === "Text2" || clicked === "Text3" ) { //one of our text's were clicked
        $("#Text1, #Text2, #Text3").css("opacity", "0.2"); //reset them all to .2 opacity
        $(this).css("opacity", "1");//set this elements opacity to full
    } else { //its clearly not Text1/2/3
        $("#Text1, #Text2, #Text3").css("opacity", "1");  // return to default state
    }
 };

One nit-picky point is that we tend to prefer lower case in attributes for html. I would recommend text1, text2... or even better would be to give an id that better described what the element is on the page.


I can believe it when the replace is the problem... it's creating a mess of nested code that's creating a lot of intermediate string values.

There's not much I can see to improve, though. The nesting can be reduced by combining a few of replaces...:

replace(.... , '\n|&#xA', '\\n')

Doing the same for \t and \r will reduce six calls to just three.

Additionally, I would consider wrapping the entire replace function in a matches call, that matches any of the patterns you are searching for, so you only need to do the full replacement call stack on values that actually require it. A large matches for all replaced values will, depending on how often values are actually required to be replaced, save time.


Variables, references and pointers - Write the function set (…) so that the following code works correctly

You have too many variables. The ret is not needed.

Also, for testing I would like to see some actual testing, rather than just printing to the console and letting the user do it:

#include <cassert>

void test_set() {
    int x = 3;
    set(x) = 3;
    assert(x == 0);
    set(x) = 4;
    assert(x == 3);
    // etc.
}

(Or, you could use an actual unit testing framework. But assert works for this simple case.)


Made a monster array for a text based game with a class constructor C++

Don't write using namespace std;.
You are passing std::string by value, which copies the string.  Generally you want to pass as const std::string&, or better yet std::string_view.  (Though in the case of a properly written constructor (see below) you might want to do something more advanced here.)

enemies = MonsterCluster(0, "Goblin", 20, 5);
enemies = MonsterCluster(1, "Wraith", 50, 10);
enemies = MonsterCluster(2, "Legionare", 80, rand() % 60+20);

You are assigning values to the same variable, overwriting the previous.
I think you're confusing the meaning of monsterList inside the class with uses of the entire class.  Each instance you create is populating a different element in the array, but you don't understand that these calls are creating different instances and not updating the previous instance!  You throw away the first two instances you create and only keep the third.
Have a Monster class with a constructor.  You don't show your Monsters but it appears to be a plain struct without a constructor, from how you're using it.
Then you don't need a class that's nothing but a collection of 3 Monsters.  That's just an array.
Something like:
Monster enemies[] = {
   { "Goblin", 20, 5 },
   { "Wraith", 50, 10 },
   { "Legionare", 80, rand() % 60+20 }
};

Note that each line is three parameters for the Monster constructor.


Many improvements are possible.

First, you shouldn't use ReadS and other rudumentary Prelude parsing function for anything but exercises. Use parsing libraries from Hackage instead. parsec is a good library to start with, if you are not sure of which one to use.

Second, if it is an exersise, you can avoid long chains of Nothing matches by using Maybe monad. I reimplemented read2Vec2 for example:

read2Vec2 :: String -> Maybe (((Integer, Integer),(Integer,Integer)), String)
read2Vec2 s = do
    ((a,b), r1) <- readVec2 s
    ((c,d), r2) <- readVec2 r1
    Just (((a,b),(c,d)), r2)

Third, you can avoid passing unparsed input around by keeping it in the State monad. At this point our code will do what parsec does :) except parsec does it better.

If you want to stay with your current approach then readBrackets can be shortened:

readBrackets :: ReadS a -> ReadS a
readBrackets g r = do
    ("[", s) <- lex r
    (x,t)    <- g s
    ("]", u) <- lex t
    return (x,u)

Here is full parser using parsec:

{-# LANGUAGE NoMonomorphismRestriction #-}
import Text.ParserCombinators.Parsec
import Control.Applicative

data Mat2x2 = MkMat2x2 Integer Integer Integer Integer
  deriving (Show, Eq)

parseMat2x2 = parse mat2x2 "(unknown)"

nat = read <$> many1 digit

mat2x2 = do
    string "[["
    d1 <- nat
    char ','
    d2 <- nat
    string "]["
    d3 <- nat
    char ','
    d4 <- nat
    string "]]"
    return $ MkMat2x2 d1 d2 d3 d4

main = print $ parseMat2x2 "[[2,2][3,4]]"

The parser can be made less strict if necessary. For example, current parser doesn't accept any whitespace. And for a better performance you could try parsec with a lexer stage (current code avoids lexer altogether).

For ultimate performance you should use alex and happy tools, which are haskell's lex and yacc respectively.


Your variable names are bad, s, data, all of these could be better, input, romanNumerals and so on.

Your formatting is a little bit off, consider using an autoformatter.

Also your method will spectacularly fail when handed invalid input.

put("I", 1);

Be aware of Autoboxing.

for (String val : edge) {
    if(s.isBlank()) {

Have the if outside the loop, so that you don't even need to start the loop just to bail out immediately.

sum += data.get("" + c);

I'm absolutely not a friend of such casts. Most of the time, they mask what you actually wanted and depend on implementation details, especially with numbers.

Otherwise it seems to work. What you could do is split the initial Map into two, romanNumerals and compoundRomanNumerals, that would simplify the overall logic and would remove the duplication you have with the edge array.

If you can help it, try to avoid string operations, they will always consume a lot of memory, for example:

String c = a + b;

Will result in:

Allocate c with enough memory to hold a and b
Copy a into c
Copy b into c

So if a and/or b is large, and I mean large, your memory usage will spike.

What you could do instead, is to copy the String into a StringBuilder, as that one will internally work on an array and will not create immutable instances with every change.

And you should handle error cases, null as input, Hello World! as input, such stuff. Would be a great exercise for writing unittests.


Squaring the two digits in the middle of a four-digit number

Some thoughts:

1) I would add a check to ensure that the number being passed in, is positive.

2) You don't need to use the return statement in your first if, in fact the first if does nothing. You could simply add a ! to the if statement and if it passes over it the method will terminate anyway.

// Repeat until an equal number is in the ArrayList
if (!numbers.Contains(current)){
    numbers.Add (current);
    this.generateNumbers(current);
}

3) If you decided to go with a larger number and square using more digits you could potentially run into a StackOverflowException since this uses recursion. I would use a helper method to do the actual calculation which would return a number and instead of an if statement use a while. (Of course if you're checking a cap on the number this could never happen since there can only be 100 numbers that will be added.)

How the code could look:

ArrayList<int> numbers = new ArrayList<int> ();

public void generateNumbers (int number) {

    if (number < 0 || number > 9999) {
        throw new ArgumentOutOfRangeException ("Number must be greater than 0 and less than 10,000");
    }

    // Repeat until an equal number is in the ArrayList
    do  {
        number = helper(number);
        numbers.Add(number);
    } while (!numbers.Contains(number))

}

private int helper(int number) {
    // Remove the thousands and get the times 10 fits in (you've only the two numbers in the middle left)
    return (int) Math.Pow(number % 1000 / 10, 2);

}

Now (with a bit of editing) you could extend the method to take as high of a number as the person wants and always square whats in the middle.


Reading a certain pixels color from a window

You'll actually need to wrap the Bitmap in a using as well because its base class, Image, implements IDisposable:

public static Color GetPixel(IntPtr hwnd, int x, int y)
{
    using (Bitmap screenPixel = new Bitmap(1, 1);
    {
        using (Graphics gdest = Graphics.FromImage(screenPixel))
        {
            using (Graphics gsrc = Graphics.FromHwnd(MemoryHandler.GetMainWindowHandle()))
            {
                IntPtr hsrcdc = gsrc.GetHdc();
                IntPtr hdc = gdest.GetHdc();
                BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y, (int)CopyPixelOperation.SourceCopy);
                gdest.ReleaseHdc();
                gsrc.ReleaseHdc();
            }
        }

        return screenPixel.GetPixel(0, 0);
    }
}

Further, the garbage collector works almost immediately. Or more simply put, if you use a memory allocation tool like MemProfiler, the memory will get cleaned up by GC faster than you can collect it with a snapshot. The Bitmap is likely where you are seeing the little tick.

It may also be worth wrapping the API call in a try ... finally:

IntPtr hsrcdc = gsrc.GetHdc();
IntPtr hdc = gdest.GetHdc();

try
{
    using (Graphics gsrc = Graphics.FromHwnd(MemoryHandler.GetMainWindowHandle()))
    {
        BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y, (int)CopyPixelOperation.SourceCopy);
    }
}
finally
{
    gdest.ReleaseHdc();
    gsrc.ReleaseHdc();
}

to ensure the ReleaseHdc gets called.


Determining if a C-style string is alphabetic

The main problem with your code (in terms of performance) is that it processes every character in the string regardless. It's probably better to actually exit early if you find a non-alpha character, with something like:

bool isStrAlpha (const char *chPtr) {
    // if (*chPtr == '\0') return false;
    while (*chPtr != '\0')
        if (! isalpha (*chPtr++))
            return false;
    return true;
}

And just a couple of extra notes:

This code works fine even for zero-length strings, assuming the intent is to ensure whatever characters are in the string are all alpha. In other words, it considers an empty string valid because it contains no non-alpha characters. If you want to ensure the string has to have at least one alpha, just reinstate the commented-out line at the start of the function.
Your second assumption is superfluous. A series of characters that are not terminated with \0 is not actually a string in C.
Whether alpha characters are likely to be consecutive is not relevant in my opinion, I usually prefer correct, portable code over speed. But, in any case, you can be reasonably certain that the people who created your implementation will have optimised the wazoo out of the character classification stuff.


Filtering DbContext data dynamically by user input in WPF applications

Reducing your code to what I think is the core of your question:

private System.Linq.IQueryable<Multi.Model.clients> FilterClients(optisysEntities db, System.Linq.IQueryable<Multi.Model.clients> clients)
{

    if (!String.IsNullOrWhiteSpace(textBoxName.Text))
        clients = db.clients.Where(c => c.name.Contains(textBoxName.Text) || c.phone.Contains(textBoxName.Text));

    if (!String.IsNullOrWhiteSpace(search.Email))
        clients = clients.Where(u => u.Email.Contains(search.Email));

    if (search.UsertypeId.HasValue)
        clients = clients.Where(u => u.UsertypeId == search.UsertypeId.Value);

    return clients;
}

Yes, this is one of the better ways to do dynamic filtering.

I would suggest abstracting the data retrieval into a separate layer. You don't want your form logic handling your underlying ORM directly.

This is exacerbated by the fact that you've put the FilterClients() method by itself. Your UI form therefore contains a method whose reponsibility has nothing to do with the UI.

However, I get the feeling that this application is either tiny, or has only just been developed. So I can understand that this abstraction is something for a later stage. I would suggest doing it immediately to make it less painful in the future, but that's your choice.


Helper class to send emails with attachments on Android

I'd change a few things to make your code cleaner.

Your send method does three different things: it extract the message from the context, it creates the intent and it finally launches the email app. What about introducing a Message class, a Message decodeMessage(Context context, String deviceName), and an Intent createIntent(Message message) methods?

getPackageInfo is definitely to arrow-shaped. I'd refactor it to separate the logic of creation of the package info string String formatPackageInfo(PackageInfo packageInfo) and the code to retrieve the PackageInfo instance.

private PackageInfo getPackageInfo(){
    String packageName = context.getPackageName();
    PackageManager manager = context.getPackageManager();
    if (manager == null)
        return null;
    try
    {
        return manager.getPackageInfo(packageName, 0);
    }
    catch (PackageManager.NameNotFoundException e)
    {
        Log.e(TAG, "Could not get package info", e);
    }
    return null;
}

private static String formatPackageInfo(PackageInfo packageInfo) {
        if(packageInfo == null)
            return "";
        return String.format("\n\n--\n[App: %s Version: %d/%s]",
                        packageName, info.versionCode, info.versionName);
}

In addAttachmentToIntent I'd probably move the declaration of dateFormat and of filename in the try block. You're not going to use them outside that scope so it could be a good idea to give them the smallest scope possible.


node.js library for extracting words from a text

The top part looks clean, personally I would

Not compare with null all the time, just check word.length and have word be an array at all times.
Not initialize word and words separately
Not use String.fromCharCode(code), I would use text[index] instead
I would use the ~ operator instead of comparing to -1
I would first deal with finding a match , and then with not finding a match ( switch the if blocks in other words ), my mind had to do a double take when I was reading your code
if would add a space to the end of text, so that I would not need the last if statement

All that would give me something like:

module.exports = function (text){
 text += " ";

 var words = [],
     word  = [],
     limit = text.length, code, index;

    for (index = 0; index < limit; index += 1) {
        code = text.charCodeAt(index);
        if (~_.indexOf(letters, code, true)) {
          word.push( text[index] )
        } else {
          if (word.length) {
            words.push(word.join(''));
            word = [];
          }
        }
    }
    return words;
};

Finally, I think collecting char-codes in the 2nd script, then taking chars, converting those to char-codes and then use the chars again might not be the best approach.

Personally, I would letters be an object where each letter ( not the char-code ) would be a property of the object set to true. No more char-code conversions, and most likely it would beat the sorted lookup table. ( To be tested.. )


TL;DR:

Don't repeat yourself. If you notice that code is very similar, ask whether you can use that similarity.
Express functions with other functions.
Avoid length in recursive calls, as it will add another factor n to your time complexity

Overall, still well done.

Naming and (time) complexity

Let's start by looking at the types. Well, you have type signatures at every top-level binding, which is a great start. I think that the name Solution is slightly misleading, since you call the variable b for Board. But naming is hard, so let's focus on other parts.

extend :: Solution -> Int -> Maybe Solution
extend b new = go 0 b
  where
    n = length b                                       -- 1
    go _ []  =  Just (b ++ [new])                      -- 2
    go i (x:xs)
      | x == new                      = Nothing
      | abs (i - n) == abs (x - new)  = Nothing
      | otherwise                     = go (i+1) xs

extend has two small problems. First, xs ++ [e] (see 2 above) is linear (\$\mathcal O(n)\$), whereas e : xs is constant (\$\mathcal O(1)\$). If possible, we  should prefer the second variant. And length b is also linear (see 1 above). But if we fix 2 we don't need n anymore:

extend :: Solution -> Int -> Maybe Solution
extend bs new = go 1 bs
  where
    go _ [] = Just (new : bs)
    go i (x:xs)
      | x == new           = Nothing
      | i == abs (x - new) = Nothing
      | otherwise          = go (i + 1)

Note that I've renamed b to bs, since the suffix s indicates multiple elements.

Don't repeat yourself

Although yout extend and extend' differ, the logic in go is almost the same. That's a sign that you can re-use the code, so let's try that:

placeable :: Int -> Solution -> Bool
placeable n xs = null [ x | (i,x) <- zip [1..] xs, x == n || abs (x - n) == i]
-- same as
placeable' :: Int -> Solution -> Bool
placeable' n xs = go 1 xs
  where
    go _ []     = True
    go i (x:xs) = x /= n && abs (x - n) == i && go (i + 1) xs

Now we can simplify extend and extend':

extend :: Solution -> Int -> Maybe Solution
extend bs new = if placeable new bs
                  then Just (new : bs)
                  else Nothing

extend' :: Solution -> Int -> [Solution]
extend' bs new = if placeable new bs
                   then [new : bs]
                   else []

Feel free to use guard syntax instead.

Reuse functions

If you have a function listToMaybe :: [a] -> Maybe a, you don't need to write extend:

extend :: Solution-> Int -> Maybe Solution
extend bs new = listToMaybe (extend' bs new)

We can do the same for nQueens and get rid of extend completely:

nQueens :: Int -> Maybe Solution
nQueens n = listToMaybe (nQueens' n)

But you need to be lazy enough for that.

Use knowledge you already have

In fullExtend, you'll check whether you already reached the correct length:

fullExtend :: Int -> Solution -> Maybe Solution
fullExtend n partialSolution
  | length partialSolution == n     = Just partialSolution             -- here
  ...

However, that's again \$\mathcal O(n)\$. But we know the length of our current solution; almost. It's the number of recursive calls:

  ...
    propose x Nothing   = extend partialSolution x >>= fullExtend n  -- one element more

Also n does not change. This calls for a go-like function:

fullExtend :: Int -> Solution -> Maybe Solution
fullExtend n = go n
  where
    go 0 partialSolution = Just partialSolution
    go k partialSolution = foldr propose Nothing [0..(n-1)]
      where
        propose _ (Just xs) = Just xs
        propose x Nothing   = extend partialSolution x >>= go (k - 1)

We now count down from n to 0 in go. Whenever we reached 0, we have all n elements. This removes the need for length. At this point fullExtend is almost the same as nQueens, so we can get rid of it:

nQueens :: Int -> Maybe Solution
nQueens n = go n []
  where
    go 0 partialSolution = Just partialSolution
    go k partialSolution = foldr propose Nothing [0..(n-1)]
      where
        propose _ (Just xs) = Just xs
        propose x Nothing   = extend partialSolution x >>= go (k - 1)

We can use the same approach for fullExtend'. First, get rid of length:

fullExtend' :: Int -> Solution -> [Solution]
fullExtend' n partialSolution = go n partialSolution
  where
    go 0 xs = [xs]
    go k xs = [0..(n-1)] >>= (\x -> extend' partialSolution x >>= go (k - 1))

Then rewrite nQueens':

nQueens' :: Int -> [Solution]
nQueens' n = go n []
  where
    go 0 xs = [xs]
    go k xs = [0..(n-1)] >>= (\x -> extend' xs x >>= go (k - 1))

By the way, this looks a little bit nicer with do notation:

nQueens' :: Int -> [Solution]
nQueens' n = go n []
  where
    go 0 bs = [bs]
    go k bs = do
              x  <- [0..(n-1)]
              xs <- extend' bs x
              go (k - 1) xs

But that's up to you to decide.

Your propose question

  Can the propose function be expressed in a more elegant way?

You can use Maybe's Alternative instance:

propose x solution = solution <|> (extend partialSolution x >>= go (k  -1))

However, that's not really necessary if you rewrite nQueens

All at once

If we also inline extend, we end up with the following code for the list variant:

import Data.Maybe (listToMaybe)

type Board = [Int]

nQueens :: Int -> Maybe Board
nQueens = listToMaybe . nQueens'

nQueens' :: Int -> [Board]
nQueens' n = go n []
  where
    go 0 bs = [bs]
    go k bs = concatMap (go (k - 1)) [ x : bs | x <- [1..n], placeable x bs]

    placeable n xs = null [ i | (i,x) <- zip [1..] xs, n == x || abs (n - x) == i]

We could rewrite go above also as

    go k bs = do
              x <- [1..n]
              guard (placeable x bs)
              go (k - 1) (x : bs)

or

    go k bs = [1..n] >>= (\x -> guard (placeable x xs) >> go (k - 1) (x : bs)

but that's only personal preference, they all work the same.


This program asks users to rank an item and validates the rank

Your getRank function could use a little flexibility. If the user inputs low, their input is rejected as incorrect. To solve this you can take the first character of the string passed. Since you index the string at 0, input like l will still work.
Your validation loop could also use some work. Since you're only checking if the users choice is in the valid input list, make the while loop represent that!
def getRank(choice: str) -> str:
    choices = ['l', 'm', 'h']
    choice = choice.lower()[0]
    while choice not in choices:
        print(f'Only enter a valid choice ({choices})')
        choice = input('Please enter a rank: ').lower()[0]
    return choice


Given a list and a number k return whether any two numbers from the list add up to k

These solutions have quadratic runtime.  You can store counts (in an object) and check the object for k-x, or sort the array, check values up to k/2 and binary search for k-x.  The second approach is asymptotically slower but constant storage.


Bottleneck encountered returning records for my grid

Obvious slowdowns

for each property of NameValueCollection which is set, the condition can ommit the ==0 check.
you are sorting the results 2 times
using .Count(), but this seems to be needed.
calling unneccessary .ToList() on parents
posibly unneccessary call of .ToList() on result. Here you should check if CustomerPaged.aaData can take an IEnumerable<MODIFIED_DATA>

Naming

result is an IEnumerable<MODIFIED_DATA> so the plural should be used -> results
the kind of hungarian notation you use is seen as bad practice
local variables should be named using camelCase casing

General

Consider to extract the "index" strings, like "sSearch_0", into class const variables


Rotate an N × N matrix 90 degrees clockwise

Are you up to date?

There is really not much to the problem and there are a variety of solutions.

It is also hard to know what the interviews are looking for. For some it is knowledge of latest language features, for others it may be judged on efficiency.

These very simple tests are generally just to see if you can actually write code. You would be amazed at how many people apply for jobs they are not able to do.

Assessing the code.

Looking at your code as a conservative HR interested in your code writing style, and up to date language knowledge.

It is a pass, you can code, you have the job but will have you in supervision for a while..You also need to catch up on the language as you are not using ES6 to the full.

General points

You need to use const for constants, and let for block scope variables.
You have not used any arrow functions.
I would question why you created the function using an expression, rather than a function statement, to make sure that you know the difference. (You should play it safe an use function statements)
Also maybe a little to much code, but not really an issue.
Code logic.. i would ask why you chose to duplicate the array rather than just create a new one as you went.

A quick rewrite

I am assuming the rotate is in place (original array) with new rows

function rotate(matrix) {          // function statement
    const N = matrix.length - 1;   // use a constant
    // use arrow functions and nested map;
    const result = matrix.map((row, i) =>
         row.map((val, j) => matrix[N - j][i])
    );
    matrix.length = 0;       // hold original array reference
    matrix.push(...result);  // Spread operator
    return matrix;
}

Some extras

The problem states "image" and "pixel" which give a hint that this may be judged on performance. They would tell you if it was. But if you get  a similar challenge and performance is important then its best to use good old for loops, avoiding any iterators that use callbacks.

Also a performance oriented function would swap in place rather than create new arrays. If you had to do that realtime with images for modern displays your code would be making big GC hits (Garbage Collection).

An alternative

Another way it can be done by rotating 4 pixels at a time can reduce memory overheads and processing time. Destructing lets you swap 4 corners in one go without the need to create temp variables.

I would never recommend you submit the following unless there was a clear directive for performance, and thinking outside the box.

// Commented version

// N*N is square
// pixels are rotated inplace
// 4 by 4 rotated in 4 iterations
// 5 by 5 rotated in 7 iterations
function rotatePixels(image) {
    var x, y, x1, y1, edge;
    // Solve by swapping 4 at a time in rings from the outside in
    const N = image.length;  // size of array
    const N1 = N - 1;        // position of end item
    const N2 = N / 2;        // Half way position

    // x,y hold the a cell coordinate
    x = y = 0;

    // x,y hold the diagonally opposite cell
    x1 = y1 = N1;

    // length of current edge
    edge =  N1;

    // while not at the center
    while (y < N2) {
        // for each item on the current edge
        while (x < edge) { // rotate points at outer edge
            // swap 4 corner items
            // using array destructed assignment
            [
                image[x ][y1],
                image[y1][x1],
                image[x1][N1 - y1],
                image[y ][x ]
            ] = [
                image[y ][x ],
                image[x ][y1],
                image[y1][x1],
                image[x1][N1 - y1]
            ];
            x += 1;     // move top pos forward one
            x1 -= 1;    // move bottom pos back one
        }
        y += 1;         // diagonally into array
        x  = y;         // x same as y
        y1 = x1 = N1-x; // and diagonal opposite
        edge -= 1;      // shorten the end
    }
    return image;
}

// How I would present it

function rotatePixels(image) {
    var x, y, x1, y1, edge;
    const N = image.length;
    const N1 = N - 1;
    const N2 = N / 2;
    x = y = 0;
    edge = x1 = y1 = N1;
    while (y < N2) {
        while (x < edge) {
            [image[x][y1], image[y1][x1], image[x1][N1-y1], image[y][x]] =
            [image[y][x] , image[x ][y1], image[y1][x1]   , image[x1][N1-y1]];
            x += 1;
            x1 -= 1;
        }
        x  = y += 1;
        y1 = x1 = N1-x;
        edge -= 1;
    }
    return image;
}

// At time of writing I was unsure as to the performance of the swap using destructuring
// Turns out it is very bad
// The next version is a more conventional swap and runs 3 time faster than the above version
// and 8 times faster than the conventional solution at top of answer

function rotatePixels(image) {
    var x, y, x1, y1, edge;
    const N = image.length;
    const N1 = N - 1;
    const N2 = N / 2;
    x = y = 0;
    edge = x1 = y1 = N1;
    while (y < N2) {
        while (x < edge) {
            const a = image[y][x];
            image[y][x]      = image[x1][N1-y1];
            image[x1][N1-y1] = image[y1][x1];
            image[y1][x1]    = image[x][y1];
            image[x][y1]     = a;
            x += 1;
            x1 -= 1;
        }
        x  = y += 1;
        y1 = x1 = N1-x;
        edge -= 1;
    }
    return image;
}


I think you have written your code well! Here are some steps you can have in mind when coding:

Always comment the code, even though it is self-explanatory, it might not be in 1-5 years later. Comment so that you and others trying to help you understand what your goal was.
You can always improve your code, one way is follow DRY mindset, which is Don't Repeat Yourself. You can use functions to wrap your code, instead of using the same code in multiple places.
Learn as you go, watch others how they organize your code, and implement their structure into your code.