I think the code is incomplete. It's possible to build a Graph but there is no way to process it as there are no methods returning the state of a Graph.

To be able to evaluate the shown code I'm going to extend it by two methods:

/**
 * Returns true if a node with the given name was added.
 */
public boolean hasNode(String name) {
    return nodes.containsKey(name);
}

/**
 * Returns true if an edge form source node to destination node (identified by their names) was added.
 */
public boolean hasEdge(String src, String dest) {
    HashSet<String> adjList = nodes.get(src);
    return adjList != null && adjList.contains(dest);
}

Let's use a simple example to show some shortcomings:

public static void main(String[] args) {
    Graph g = new Graph();
    g.addNode("A");
    g.addEdge("A", "B");

    System.out.println(g.hasNode("A")); // true
    System.out.println(g.hasNode("B")); // false
    System.out.println(g.hasEdge("A", "B")); // true
}

egdes to missing nodes
The method addEdge verifies that a source node is already present. But it doensn't verify if the destination node is present, too. Thus it's possible to addEdge from an already added node to an unknown node.
Whereas hasNode("B") will state that there is no node "B" in the Graph g, hasEdgde("A", "B") will return true which is at least misleading. I think  it's inconsistent as I would expected this implies there is a node "B" also present in the Graph g.

directed graph
Since addEdge adds an edge from a source node to a destination node it's more precise to speak of a directed graph. Otherwise

g.hasEdge("B", "A");

needs to return true. But actually it isn't.

readding a node is possbile
Another point: It's possible to add already added nodes again.

g.addNode("A");

This results in replacing the current node by a new one. There is no exception and hasNode("A") will still return true. But all edges from the previous node to other nodes are lost.

System.out.println(g.hasEdge("A", "B")); // false

This should be prevented.

readding an edge
Readding an edge doesn't throw an exception. But it doesn't add an edge actually. It's impossible since a node is storing it's edges in a Set. A Set will not add an already present element once again. As long as there is no need to know how many times an edge from a node to another was add this isn't severe.

Some further hints:

You can declare nodes as Map<String, Set<String>>. Since you're using interface methods only, there is no need to use the implementation types.
When adding a node calling first nodes.containsKey(name) and then on success calling nodes.put(name, new HashSet<String>()) has double complexity as the element within the map has to be looked up twice. But sinnce adding a node several times shouldn't be possible we can write

instead:

public void addNode(String name) {
    Set<String> node = nodes.get(name);
    if (node != null)
        throw new RuntimeException("addNode - node already exist");
    nodes.put(name, new HashSet<String>());
}


We should understand what's happening when we do string-related operations in Java. When we concat strings in java, like

 String result = "";
 for(int i=0; i<100; i++){
    result += i+","; // bad, because each string + string creates new string
 }

Strings are immutable, so its bad to += them, instead, StringBuilder is used.
Here's another way to solve this task:

public class ReplaceSpace {

  private static final String REPLACE_SPACE = "%20";
  private static final String SPACE = " ";

  public static void main(String[] args) {
    String input = "Just    some input     string to perform stuff     !";
    System.out.println(replaceString(input));
  }

  private static String replaceString(String input) {
    StringBuilder sb = new StringBuilder();

    int lastPoint = 0;
    int foundIndex;
    int maxIndex = input.length() - 1;
    while ((foundIndex = input.indexOf(SPACE, lastPoint)) != -1 && foundIndex <= maxIndex) {
        sb.append(input.substring(lastPoint, foundIndex - 1));
        sb.append(REPLACE_SPACE);

        lastPoint = foundIndex;
    }

    sb.append(input.substring(lastPoint));

    return sb.toString();
    }

}


There are a couple of inconsistencies which you could tidy up. You're toggling classes to show/hide the div but using show/hide directly on the triggers. You're using chaining in one onClick but not in the other. And you're using the class to reference the accordion contents in one case, but the element name in the other.

$('.more').hide();

var learnMore = $('.learn-more'),
    close = $('.close');

learnMore.click(function() {
   $(this).hide().next('.more').show();
});

close.click(function() {
    $(this).parent().hide().prev('.learn-more').show();
});

Fiddle

is one possible way of making everything consistent, although you may prefer to always toggle classes instead (or to add animations).


Portable C++98 thread class akin to std::thread

You can put the unsafe_args in a auto_ptr so RAII can delete them safely. This is safe because you will not be copying it around.

static PORTABLE_THREAD_FUNC_DECL thunk(void *unsafe_args)
{
    std::auto_ptr<TThunkArg> args(reinterpret_cast<TThunkArg*>(unsafe_args));
    args->Self->m_func(args->Arg0);

    return 0;
}

Also don't worry about having to new the args; you are creating a new thread, this is much more expensive than a quick malloc call.


You have decided your ranges are inclusive:

sort(v,0,v.size()-1);

So low=>lowest member, high=>highest member.
Most C++ code uses the one past the end system (see iterators). Not a huge deal. It just means you need to use operator<= rather than operator< and you have to sprinkle a couple of +1 around.

Your main merge loop is easier to write if you concentrate on what it is supposed to do (Compare items from the two ranges).

while(i <= mid && j <= high) {
    if (old[j] < old[i]) {
        v[x++] = old[j++];
    } else {
        v[x++] = old[i++];
    }
}

At this point one of the ranges is exhausted, so all the elements must come from the other range. So just copy them.

while(i <= mid) {
   v[x++] = old[i++];
}
while(j <= high) {
   v[x++] = old[j++];
}

But we can also replace manual loops using algorithms:

std::copy(&old[i], &old[mid+1],  &v[x]); x+= (mid-i)+1;
std::copy(&old[j], &old[high+1], &v[x]);

Also, you are copying the whole array into old when you are only going to alter a subset of it. Say the vector contains 10,000 elements. But this merge you are merging low=>5, mid=>6, high=>7 that seems like a lot of extra copying.

I would simplify this and sort into an external array, then copy only the sorted elements back.

std::vector<T>  sorted(high-low+1);
while(i <= mid && j <= high) {
    if (old[j] < old[i]) {
        sorted[x++] = v[j++];
    } else {
        sorted[x++] = v[i++];
    }
}
std::copy(&v[i], &v[mid+1],  &sorted[x]); x+= (mid-i)+1;
std::copy(&v[j], &v[high+1], &sorted[x]);

std::copy(sorted.begin(), sorted.end(), &v[low]);

Since we are in the era of C++14, we can do a lot better than copying the array. We can introduce the concept of a move and move the elements around. For integers there is no difference, but if T is a big object, we would rather move it if we can.

        sorted[x++] = v[j++];

        // becomes.

        sorted[x++] = std::move(v[j++]);

Rather than passing the index and the container, just pass iterators (now it becomes easier to use the one past the end metaphor). Also, we can generalize the container to a C so that you can pass any container.

The result is:

template<typename I>
void merge(I low, I mid, I high) {
    I i   = low;
    I j   = mid;

    typedef typename I::value_type  value_type;
    std::vector<value_type> sorted(std::distance(low, high));
    auto x = sorted.begin();

    while(i < mid && j < high) {
        if (*j < *i) {
            // Use move semantics. So we don't copy expensive T object around.
            (*x) = std::move(*j); ++j;++x;
        }
        else {
            // Put the ++ inline to show difference in readability.
            // Prefer the above to this.
            (*x++) = std::move(*i++);
        }
    }
    // Don't use a manual loop when you can use an already optimized algorithm
    x = std::move(i, mid,  x);
    x = std::move(j, high, x);

    // Now move the sorted values back.
    std::move(std::begin(sorted), std::end(sorted), low);
}

template<typename I>
// requires std::RandomAccessIterator<I>           // Proposed C++17 syntax for concepts.
//       && std::LessThanComparable<typename I::value_type>>
void sort(I low, I high) {
    size size = std::distance(low, high);
    if(size <= 1) {
        return;
    }
    I    mid(low)
    std::advance(mid, size/2);
    sort(low, mid);
    sort(mid, high);
    merge(low, mid, high);
}

template<typename C>
void sort(C& v) {
    sort(std::begin(v), std::end(v));
}


Cook and Felderman analysis to perform data reduction on heated surfaces

I suggest the following replacement for function CandF():

def CandF3(dT, time, fac):
sqrt = np.sqrt
sumdata = np.zeros(len(time))
for n in range(len(time)):
    tn = time[n]
    # precompute sqrt(tn-time[0])
    last_sq = sqrt(tn - time[0])
    sum_n = 0
    for j in range(1, n + 1):
        sq_j = sqrt(tn - time[j])
        sum_n += dT[j] / (sq_j + last_sq)
        last_sq = sq_j
    sumdata[n] = sum_n
return sumdata * fac

The most rewarding idea here was that from the 2 square roots per innermost loop one is the second is computed repeatedly and can be saved for the next loop (here: last_sq). Halving the number of np.sqrt() calls nearly halves the runtime for large numbers of time steps (len(time)).
More optimizations are the use of a local variable for a loop-invariant (tn), use of a scalar when indexed variable is not indexed incrementally (sum_n), and precomputing the final constant sqrt(rho*c*k*2.0) in the caller. This seems natural as the contributing constants are all defined there.


I don't know any Spanish so it was a bit difficult to understand exactly what was going on (I recommend you provide English translations/descriptions of non-English class names and string literals as comments next time).

Why do you create a temporary variable that is only use to set another variable on the very next line instead of just setting it directly? (iDependencias & depClient).
You close the channel if it's a DependenciasClient but don't clear the reference to it. svcDependencias is visible outside this method and having it hold a reference to a closed connection may be a problem.
You don't check to see if svcDependencias is already set before setting it to a new connection. I don't know if you can re-use the connection, but you should at least close the existing connection before you loose the reference to it.
I noticed that you only close the channel factory if the channel is not a DependanciasClient. While this will probably work ok if the channel factory never returns a DependanciasClient, I think a null check would be a clearer solution.

if(customChanelFactory != null)
{
    customChanelFactory.Close();
}

Instead of using the 'is' operator followed by a cast, you should use the 'as' operator and check for null.

DependenciasClient client = svcDependencias as DependenciasClient;

if (client != null)
{
    client.Close();
}

If svcDependencias only exists at the class level for the benefit of GenerarDependenciasDeFormulariosFmb then personally I would prefer to pass it in as an argument rather then use a class field.


mitchell is the only function with a docstring. What do all the other functions do? How do I call them? What do they return?
A function's name should describe what it does, or what it returns, rather than the name of algorithm it uses (which is typically an implementation detail). So I would use a name like point_cloud instead of mitchell.
Your implementation picks the random sample that is closest to all the other points, but the algorithm described in Mitchell's 1991 paper "Spectrally optimal sampling for distribution ray tracing" picks the random sample that is furthest away from any other point (see section 4, "Sequential Poisson-Disk Sampling"). This is so different that I think it would be better not to use the name "Mitchell" to describe the algorithm.
It would make the code easier to use if RANDOM_POINTS_PER_GENERATION were a keyword argument to mitchell, rather than a global variable. Consider a program that tries to determine a good value for this parameter, or a program with two pieces of code that need different values for the parameter.
mitchell(0) returns a list of one point, but surely this should return a list of no points?
Instead of:

while len(points) < number_of_points:

write:

for _ in range(number_of_points - 1):

since you know that each iteration adds exactly one point.
The function average is built into Python under the name statistics.mean.
The function distance is misleadly named: it actually calculates the squared distance between points. Similarly, distance_to_points returns the mean square distance to the points.
The function nearest doesn't need to take the average: since seen_point has the same length in every case, the sum of the squared distances would be just as good.
Instead of creating a temporary list that gets thrown away immediately:

average([distance(point, seen_point) for seen_point in seen_points])

use a generator expression:

sum(distance(point, seen_point) for seen_point in seen_points)

At each stage nearest finds the average squared distance from a candidate point to each point in the cloud, making the overall runtime \$ O(kn^2) \$. However, it's possible to do better than that. For each candidate point \$ q \$, the value that needs to be computed is the sum of squared distances, $$ \sum_j \left|p_j - q\right|^2. $$ Using the dot product we can expand the square, getting $$ \sum_j (p_j - q)·(p_j - q). $$ Multiplying out, we get $$ \sum_j p_j·p_j - 2q·\sum_j p_j + q.q \sum_j 1. $$ Since we taking the minimum of this value over all the candidate points \$ q \$, we don't need the first term \$ \sum_j p_j·p_j \$ as this is the same for all \$ q \$ and so cannot affect the result.

What this means is that if we keep a running sum \$ \sum_j p_j \$ then we can find the candidate point with the minimum sum of squared distances to all the points in the cloud in \$ O(k) \$, bringing the runtime down to \$ O(kn) \$.

To implement this, we need a representation of vectors that supports sums and dot products. Here I'm using NumPy arrays:

import numpy as np

def point_cloud(n, k=6):
    """Generate a point cloud with n points. At each step k (default 6)
    candidate points are generated and the one whose sum of squared
    distances to the other points is smallest is used.

    """
    if n == 0: return
    p = np.random.random(size=2)
    yield p
    sum_p = p.copy()
    for i in range(1, n):
        # Generate k candidate points.
        q = np.random.random(size=(k, 2))

        # Sum of squared distances from each candidate point to all
        # the points generated so far, less the sum of squares of the
        # points generated so far (as this doesn't affect the minimum,
        # we don't need it here).
        s = i * (q * q).sum(axis=1) - 2 * (q * sum_p).sum(axis=1)

        # Pick the candidate that's closest to the points generated so
        # far.
        p = q[np.argmin(s)]
        yield p
        sum_p += p


This question of leap years is an interesting one... and seems to be a rite-of-passage (when you do Zeller's Congruence, you should get that reviewed too... ;-)

In Java, (and other languages), it is common to return-early. You can use this to your advantage to reduce code-nesting, by choosing whether to do a negative, or positive test in if conditionals. You have done this a couple of times in your code, but not always. For example, your code contains:

// No leap years occured before 1582 because that is when they were added to the calendar
if(year > 1582)
{
    // All code past here only executed when year mod 4 is true
    if(year % 4 != 0)
    {
        return false;
    }

You have a lot of code inside that "if" condition block, but, if you reverse the logic:

// No leap years occured before 1582 because that is when they were added to the calendar
if(year <= 1582) {
    return false;
}

// All code past here only executed when year mod 4 is true
if(year % 4 != 0)
{
    return false;
}

You have immediately 'un-nested' a large portion of your code, which makes readability better.

When you write code to match a specification, like you have here, it is valuable to include the specification you used inside your code, which, you have also done... but, do that before the code, not after it.

If you have an if-else block, and the if-side (the true side) always does a return, then there is no need for the else. This can simplify the code further....

Performing these changes, we get to:

private boolean isOPLeapYear() {
    /*
     • A year that is not divisible by 4. - NOT LEAP YEAR
     • A year that is divisible by 4 but not divisible by 100 or 400. - LEAP YEAR
     • A year that is divisible by 4 and 100 but not 400. - NOT LEAP YEAR
     • A year that is divisible by 4 and 100 and 400. - LEAP YEAR
     • A year prior to 1582 that is a leap year. - NOT A LEAP YEAR
     • A year prior to 1582 that is not a leap year. - NOT A LEAP YEAR
     */

    // No leap years occurred before 1582 because that is when they were
    // added to the calendar
    if (year <= 1582) {
        return false;
    }
    // All code past here only executed when year mod 4 is true
    if (year % 4 != 0) {
        return false;
    }

    // Makes sure that it does not register the beginning of centuries as
    // leap years
    // unless they actually are.
    if (year % 100 == 0 && year % 400 != 0) {
        return false;
    }
    // Also is the same as checking for mod 4 and mod 100, since they are
    // factors of 400
    if (year % 400 == 0) {
        return true;
    }
    return true;

}

Once we have the code like that, it is apparent that the last % 400 check is unnecessary, and since the comments are repetitive (the // comments duplicate much of what the spec and code say), they can be mostly removed, reducing the code to:

private boolean isOPLeapYear() {
    /*
     • A year that is not divisible by 4. - NOT LEAP YEAR
     • A year that is divisible by 4 but not divisible by 100 or 400. - LEAP YEAR
     • A year that is divisible by 4 and 100 but not 400. - NOT LEAP YEAR
     • A year that is divisible by 4 and 100 and 400. - LEAP YEAR
     • A year prior to 1582 that is a leap year. - NOT A LEAP YEAR
     • A year prior to 1582 that is not a leap year. - NOT A LEAP YEAR
     */

    if (year <= 1582) {
        return false;
    }

    if (year % 4 != 0) {
        return false;
    }

    if (year % 400 == 0) {
        return true;
    }

    if (year % 100 == 0) {
        return false;
    }

    return true;

}

The above code is the same logic as yours, but.... more readable, that's all.


Rails model for aggregate data instead of a real table

I agree with you that this does not really fit a service nor a model. This might be more like a Query object.
class MonthlyUsageQuery
  def intialize(relation: Project.all)
    @relation = relation
  end

  def all
    relation.select(select_monthly_data_and_dates)
      .group('year', 'month', '"projects"."id"')
  end

  private

  attr_reader :relation

  def select_monthly_data_and_dates
    <<~SQL.squish
      "projects"."id" AS "project_id",
      SUM("usages"."usage") AS "monthly_usage",
      date_part('year', "usages"."timestamp")::INT AS "year",
      date_part('month', "usages"."timestamp")::INT AS "month"
    SQL
  end
end

MonthlyUsage.all
MonthlyUsage.new(relation: Project.where(name: 'Stackoverflow')).all

https://medium.com/selleo/essential-rubyonrails-patterns-part-2-query-objects-4b253f4f4539
https://medium.flatstack.com/query-object-in-ruby-on-rails-56ea434365f0


By putting the CSV exporting logic into the spider itself, you are re-inventing the wheel and not using all the advantages of Scrapy and its components and, also, making the crawling slower as you are writing to disk in the crawling stage every time the callback is triggered.

As you mentioned, the CSV exporter is built-in, you just need to yield/return items from the parse() callback:

import scrapy

class TorrentSpider(scrapy.Spider):
    name = "torrentdata"
    start_urls = ["https://yts.am/browse-movies?page={}".format(page) for page in range(2,20)] #get something within list

    def parse(self, response):
        for record in response.css('.browse-movie-bottom'):
            yield {
                "Name": record.css('.browse-movie-title::text').extract_first(default=''),
                "Year": record.css('.browse-movie-year::text').extract_first(default='')
            }

Then, by running:

scrapy runspider spider.py -o outputfile.csv -t csv

(or the crawl command)

you would have the following in the outputfile.csv:

Name,Year
"Faith, Love & Chocolate",2018
Bennett's Song,2018
...
Tender Mercies,1983
You Might Be the Killer,2018


I see a few things that may help you improve your code.

Add some error checking

Many of the calls used in the code, including fstat and malloc can fail.  It's generally better to check for and handle such errors instead of ignoring them.  Even though your main concern is performance, these calls are only made once and so will add almost nothing to the runtime.

Here's an alternative main showing how that might look:

int main() {
    struct stat sb;
    char *data;
    if (fstat(STDIN_FILENO, &sb) != 0 || (data = (char *)mmap(0, sb.st_size, PROT_READ, MAP_SHARED, STDIN_FILENO, 0)) == nullptr) {
        perror("Error reading stdin");
        return 1;
    }
    std::cout << sum(data, sb.st_size) << '\n';
}

Avoid the use of global variables

The data variable is used within read_data and the poorly named process().  It's generally better to explicitly pass variables your function will need or declare them within the appropriately smallest possible scope rather than using the vague implicit linkage of a global variable.

Avoid premature optimization

On my machine, omitting the use of the unlikely macro and the alignas(16) made no difference in the resulting speed of the program.  Generally, I only resort to such things if there is a measurable effect and performance is more important than portability.  Perhaps you've already measured and made this determination and perhaps the results are different on your machine.

Consider an alternative algorithm

An alternative algorithm, which yields times very similar to the ones with your original, might be employed here.  In particular, we could process the file from the end to the beginning instead of the usual direction.  This allows us to efficiently convert each number, only adding the converted number when encountering a newline.  Note that this also essentially throws away the first number (which is the count of numbers to follow) which is the correct behavior in this case, since that number is not intended to be included in the sum.  Here's one version of the sum routine for that algorithm:

int sum(const char *test, std::size_t len) {
    int result{0};
    int n{0};
    int mult{1};
    // start from the back and add digits
    for (const char *ptr = test+len-1; ptr >= test; --ptr) {
        switch(*ptr) {
            case '\n':
                result += n;
                n=0;
                mult=1;
                break;
            case '-':
                n = -n;
                break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                n += mult * (*ptr - '0');
                mult *= 10;
                break;
            default:
                std::cerr << "Malformed input\n";
                exit(1);
        }
    }
    return result;
}


A matrix-vector multiply parallelized using boost::MPI

An obvious way to improve the code is to use standard containers to manage memory instead of raw pointers.

For this code, I would choose std::vector<double> for vector and result, and probably std::vector<std::vector<double>> for matrix (though note that this isn't the most cache-friendly choice for a 2-d matrix).  Remember, we can refer to a std::vector's elements as a plain array using the data() member if needed (here, the iterators should be sufficient).

That allows us to eliminate all the delete[] operations, as destructors will take care of that for us - including the non-local exits where new[] throws std::bad_alloc.

This loop looks wasteful:

    for(unsigned j = 0; j < N; j++){
        if(i==j) {matrix[i][j] = i+j;}
    }

As the body is conditional on i==j, that's simply equivalent to

        matrix[i][i] = i+i;

I don't have experience with MPI, so not commenting on its use.  It's probably worth making N be const, and possibly also defining a useful variable:

auto const chunk_size = N/world.size();

Is the variable env needed?  If constructing a boost::mpi::environment has some useful side-effect, it may be worth an explanatory comment, as it currently looks like an unused variable (if this is something obvious and expected in MPI, then disregard this comment).


1. Review

There are no docstrings. What do these functions do? How am I supposed to use them?
The use of the alarm mechanism means that the timeout occurs asynchronously with respect to the timed out function, and so data structures may be left in an inconsistent state. It's important to warn the user about this: it's hard to write functions that are safe against timeouts of this kind.
The functions and classes could have better names: I suggest TimedOutExc → TimedOut (it's clear that it's an exception because of its superclass); TimedOutFn → call_with_timeout (following PEP8); timed_out → with_timeout.
There's no need to give the exception class its own __init__ and __str__ method: the Exception class already has these methods.
The implementation of the timed_out decorator is almost identical to TimedOutFn. It would be better for new_f to call TimedOutFn instead of repeating the code.
The decorator copies __name__ from the original function, but what about __doc__ and __module__ and __qualname__? It would be better to use the built-in functools.wraps.
I think it's slightly better for call_with_timeout to take the timeout argument first. That way the function and its arguments are adjacent.
In call_with_timeout, there are two state changes that need to be reverted: the updating of the signal handler, and the setting of the alarm. But only one of these is protected by a try: ... finally: ....
There's a lot of duplicated code in the test cases. This could be refactored into methods.
The test cases don't actually tell you whether the tests passed or failed (you have to know what the output is supposed to be in each case). It would be a good idea to use the facilities in the unittest module.

2. Revised code

import functools
import signal

class TimedOut(Exception):
    pass

def call_with_timeout(timeout, f, *args, **kwargs):
    """Call f with the given arguments, but if timeout seconds pass before
    f returns, raise TimedOut. The exception is raised asynchronously,
    so data structures being updated by f may be in an inconsistent state.

    """
    def handler(signum, frame):
        raise TimedOut("Timed out after {} seconds.".format(timeout))
    old = signal.signal(signal.SIGALRM, handler)
    try:
        signal.alarm(timeout)
        try:
            return f(*args, **kwargs)
        finally:
            signal.alarm(0)
    finally:
        signal.signal(signal.SIGALRM, old)

def with_timeout(timeout):
    """Decorator for a function that causes it to timeout after the given
    number of seconds.

    """
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            return call_with_timeout(timeout, f, *args, **kwargs)
        return wrapped
    return decorator


Get list of the executables in the current directory

I wouldn't import System.Directory qualified, it doesn't export anything that could clash with standard names.

import Control.Applicative
import Control.Monad
import System.Directory

main :: IO ()
main = do
    files <- getDirectoryContents =<< getCurrentDirectory
    exes <- filterM (liftA executable <$> getPermissions) files
    print exes

You can toss out the Functor and Applicative stuff and just compose Monads.

import Control.Monad
import System.Directory

main :: IO ()
main = do
    files <- getDirectoryContents =<< getCurrentDirectory
    exes <- filterM (liftM executable . getPermissions) files
    print exes

You could also get rid of reverse bind and use the forward version, it's maybe more familiar?

import Control.Monad
import System.Directory

main :: IO ()
main = do
    files <- getCurrentDirectory >>= getDirectoryContents
    exes <- filterM (liftM executable . getPermissions) files
    print exes

I'd eliminate the explicit use of bind entirely though, then it becomes easier to turn this into a function that can work on directories other than the current one.

import Control.Monad
import System.Directory

main :: IO ()
main = do
    dir <- getCurrentDirectory
    printExecutables dir

printExecutables :: FilePath -> IO ()
printExecutables dir = do
    files <- getDirectoryContents dir
    exes <- filterM (liftM executable . getPermissions) files
    print exes


You could use Enumerable#count:

string.chars.count { |char| vowels.has_key?(char) }

You very rarely need to declare a variable (i in this case), and then modify it form inside a block; there's almost always a better way in Ruby.

So while calling count and passing a block is the most direct, you could also have done something like:

string.chars.select { |char| vowels.has_key?(char) }.count

Same idea, just written out in separate filter/count steps.

You can also skip the return since that's implied at the end of a method.

I'd also use a plain array for the vowels. Looking up hash keys is faster, sure, but does it really matter that much? Nah. "Premature optimization is the root of all evil" and all that.

vowels = %w(a e i o u) # same as ["a", "e", "i", ...]

and then the block becomes:

vowels.include?(char)

If you keep the vowels array sorted, you can use bsearch if you want to speed it up a little. Or you can construct the hash in code, instead of typing all that => 0:

list = %w(a e i o u)
vowels = Hash[list.zip(list)] # => { "a" => "a", "e" => "e", ... }

Of course you could also do something funky like this: Remove all the vowels and see how much shorter the string is afterward:

def count_vowels(string)
  string.length - string.gsub(/[aeiou]/, '').length
end

This is also easily made case-insensitive:

string.length - string.gsub(/[aeiou]/i, '').length

Or instead of gsub you can use tr:

string.length - string.tr('aeiou', '').length

(or 'aeiouAEIOU' for case-insensitivity.)

Alternatively, you could extend/monkey-patch the String class a little. I wouldn't recommend it for production code, though. This is just illustrate some Ruby features:

class String
  def vowel?
    self =~ /\A[aeiou]\z/ ? true : false
  end
end

def count_vowels(string)
  string.chars.count(&:vowel?)
end

The &x syntax is a shorthand meaning "invoke x on each element in the collection", so it's equivalent to { |e| e.x }.

Again, this is mostly for fun. I just thought it made the count_vowels method nice and short. And of course, count_vowels could itself be monkey-patched onto String, so you could just call some_string.count_vowels. But again, monkey-patching - while fun - shouldn't be the first thing you reach for. Just illustrating the principle.


Finding the difference between the estimated value and the true value in a reward task

Using list comprehensions instead of numerous .append calls is
often times faster and more readable.

A list of rewards should be called rewards instead of reward. Same goes for values and true_values.

We don't need to enumerate rewards, since we don't need the index itself. We can simply iterate over rewards.
def loopfunction(alpha, rewards, true_values):

    values = [0.5]
    for reward in rewards:
        values.append(lever_update(alpha, values[-1], reward))

    values.pop(0)

    return [abs(value - true_value) for value, true_value in zip(values, true_values)]

I sadly can't test performance right now, but I would assume the first for loop takes up most of your runtime. This is what I'd focus on for further improvements. In general, making code more concise and readable also allows for easier refactoring / performance improvements in the future.

We can also make lever_update more concise:
def lever_update(alpha, value, reward):
   return value + alpha * (reward - value)


Your code is fine, except for three small quirks

You don't need overloads if you provide default arguments
You don't need constant Ts
You don't need to check the length of your collection (except for begin == end).

template<typename InputIt>
std::string join(InputIt begin,
                 InputIt end,
                 const std::string & separator =", ",  // see 1.
                 const std::string & concluder ="")    // see 1.
{
    std::ostringstream ss;

    if(begin != end)
    {
        ss << *begin++; // see 3.
    }

    while(begin != end) // see 3.
    {
        ss << separator;
        ss << *begin++;
    }

    ss << concluder;
    return ss.str();
}

You only need to check whether you have an empty range. If you don't, you start with the first one, and then stream the separator before the next element:

(0 elements case) <concluder>
(1 element  case) <element> <concluder>
(2 elements case) <element> <separator> <element> <concluder>
(3 elements case) <element> <separator> <element> <separator> <element> <concluder>

As you can see, except for the first element, you will always get <separator> <element> for any other element. This adds a little bit more logic to the empty case, but you don't need to traverse your range twice, and this method makes your algorithm eligible for input iterators.

Other than that, the only other thing I would change is to use an ostringstream instead of an stringstream. This prevents you from accidentally using >>. And global using std::*** isn't my cup of tee either. You can, however, move that into your main.

But here's a little exercise: you can just use an <iterator>:

template<typename InputIt>
std::string join(InputIt begin,
                 InputIt end,
                 const std::string & separator =", ",  // see 1.
                 const std::string & concluder ="")    // see 1.
{
    std::ostringstream ss;

    using value_type = typename std::iterator_traits<InputIt>::value_type;

    std::copy(begin, end, std::ostream_iterator<value_type>(ss, separator.c_str()));

    ss << concluder;
    return ss.str();
}

However, as you've noted, it does not yield the same result as your variant. Here's the exercise, though: write an iterator that provides your behavior.


Implementation of an UniqueIdentifier class

I think this one screams for usage of generics.

ie.

public class UniqueIdentifier<T> {
    T theValue;
    public UniqueIdentifier( T t ) {
        theValue = t;
    }
    public T getValue() {
        return theValue;
    }
}

Can even be extened with a nice factory method.


Currently you are comparing all part against all parts, so you have a squared complexity which causes trouble for bigger numbers.

In the case that you can create your part list as sorted list (i.e. TreeSet in Java, not sure what is available in your language ) you can do the comparison in linear time by stepping through both lists in parallel.

An other idea is to use something like the HashSet in Java where the containsObject don't cost linear time as with the array or a simple list.


Are there any issues in this `Lazy` implementation?

Four notes:

It's not thread-safe. init.apply() could be called multiple times from different threads. (I don't know whether it is an issue or not.)
The constructor should check null inputs. (Effective Java 2nd Edition, Item 38: Check parameters for validity)
You should use append instead of String concatenation:

StringBuilder sb = new StringBuilder();
sb.append("Minimum required Java version is: ").append(minimumRequiredJavaVersion.get()).append("\n");
sb.append("Your system has ").append(JAVA_SPECIFICATION_VERSION).append(".");
return sb.toString();

Instead of the anonymous Prerequisite inner class I'd use a named top-level class (for example, MinimumRequiredJavaVersionPrerequisite). I think it's easier to read, naming it helps readers to understand the purpose of the class.


Excerpt from a brute force Rubik's Cube algorithm

when the program is searching all the for loops are nested for the brute search

That sounds like the first thing to fix. The brute force search should use recursion or an iterative approach which builds up a data structure (a stack or queue).

  then I have this test() which looks is responsible for testing out all the possible combinations of the nested for loop to find the the combination entered by the user of the program

Each of the six basic moves is a permutation. They could be represented as a two-dimensional array, and then a single method could apply an appropriate one by selecting the appropriate permutation from the array.

Moreover, the expanded moves are just iteration, and implementing them as iteration will give you much cleaner code.

public void applyMove(int move) {
    int iterations = (move % 3) + 1;
    int basicMove = move / 3;
    while (iterations-- > 0) {
        applyBasicMove(basicMove);
    }
}

public void applyBasicMove(int basicMove) {
    int[] permutation = basicPermutations[basicMove];
    ...
}

If you were worried about performance (which you clearly aren't, given that you're using a brute force search across a group of about \$4 \times 10^{19}\$ elements), you could optimise slightly by pre-computing the powers \$F^2\$ and \$F^3\$ (i.e. \$F^{-1}\$, or Fi if you prefer).


Appending messages to hidden input fields

It would be much easier to store the code/message pairs in an object, then no loop is needed:

var messagesByCode = {
  "203294641": "A night costs 332 miles",
  "203294642": "The night is dark and full of terrors. Costs 32 miles."
  // etc.
};

$('input[name="code"]').each(function(){
  var inp = $(this);
  inp.closest('.plan').find('.loyalty').append('
' + messagesByCode[inp.val()] + '
');
});

If you can't change the structure, generate the better structure once at the beginning:

var messagesByCode = messages.reduce(function(object, item) {object[item.code] = item.message}, {});

EDIT: Some more remarks.

Another thing that should be considered is the point of this code. Why are you doing this? Why only once at the beginning? What is the bigger picture?

The reason I ask is, because this looks like something that should happen server-side. Do the input values change client-side? If yes you should structure your code in a way that allows you to update a single input.

What does your HTML look like? Why isn't the

 part of the existing HTML?

I'm not really fond of the hard coded "path" to the target element (....closest('.plan').find('.loyalty')...). I generally prefer to write JavaScript as generic (and reuseable) as possible, but without the bigger picture I can't think of a good alternative right now.


If you start with an array:

let certs = ["ncv", "cert", "express", "dealone", "iscustomer", "isecomm"];

then it reduces down to a for loop.

for (int i = 0; i < certs.length; i++) {
    if ($this.data(certs[i])) {
        console.log(certs[i] + " is true");
        $tabbedMenu.eq(i).removeClass('hidden-item');
        $certsDescription.eq(i).removeClass('hidden-item');
    }
    else {
        $tabbedMenu.eq(i).addClass('hidden-item');
        $certsDescription.eq(i).addClass('hidden-item');
    }
}


Simplified LogService (from concurrency in practice) with shutdown feature

Concurrency issue

I think one critical part is found here:

synchronized (LogService.this) {
    if (isShutdown && queue.isEmpty()) break;
}
--> ... <--
String msg = queue.take();
--> ... <--
writer.println(msg);

You query isShutdown and queue.isEmpty() but you cannot ensure this state anymore if you leave the monitor and access the queue afterwards.

After that you also cannot ensure the output order (println) that is specified by the queue.

Both should be done in the monitor.

GuardedBy obsolete

Furthermore I do not think that the GuardedBy annoptation is neccessary as isShutdown is already only requested and modified within the monitor (synchronized(this)).

@GuardedBy("this")
private boolean isShutdown;

Writer

I do not know if it is intended to close the PrinterWriter after the queue is empty. This will cause a problem when restarting the LogThread. Closed PrintWriters may not work anymore which depends on the underlying Writer that interpretes the "close()"-operation:

PrintWriter pw = new PrintWriter(new FileOutputStream("hello.txt"));
pw.close();
pw.println("Hallo"); // will produce no output in file

try with resources

If you want to close resources properly you should use following construct:

try (PrintWriter writer = new PrintWriter(...)) {
    ...
} catch (...) {
    ...
}

Another point is that you should have a symmetry in creating and closing a resource. Your LogService is now responsible to close the Writer but it doesn't create it. Either you provide a factory for the resource so the LogService is responsible for creating and closing it OR the user of the LogService that passes in the Writer should be aware of creation and closing. Nevertheless the maximum proximity for those operations is the goal.

State handling

Currently you micro manage the state handling (running/stopped). You should consider implementing a real state pattern as a great concept to make clear when which method is allowed to be called.

You have some semantic things I find confusing. Logging is allowed only when the service is not stopped but you may always start and stop the service.

Thread interrupt

Your thread should not be stopped through the interrupt method. Try to reformulate your communication with the thread to stop without using such harsh mechanism that throws an exception.

Restarting

You do allow starting the loggerThread although this will cause an exception. I would expect either NOOP or a domain specific exception as the caller is not interested in a thread specific exception. Should the caller even know that a thead is working? Another possibility is to start over with a new thread. You already handle state so the obvious functionality for calling the start()-method on a stopped LogService is to start it again.

Personal opinion

As this is I would trust neither one nor the other implementation as they are riddled with semantic ambiguities, concurrency issues and micro management of state. I suggest to rethink the concept with real state handling and a proper monitor definition.

Code

State

The state pattern will cover three methods:

private interface State {
    void start();
    void log(String message);
    void stop();
}

LogService

The LogService will delegate all public calls to the state pattern. It provides a queue that will buffer log messages.

Initially the LogService is in the state "StateStopped".

You see that we changed from a blocking queue to a normal queue that is not thread-safe. But that is ok as the LogService serves as a monitor around it beside the other two variables loggerThread and state.

LogTarget may be access concurrently but this is not our responsibility AND we can only ensure the correct implementation by convention.

public class LogService implements LogTarget, LogSource {

    // states
    ...

    private State state;

    private final Queue<String> messageQueue;
    private LogProcessorThread loggerThread;
    private final LogTarget logTarget;

    public LogService(LogTarget logTarget) {
        this.messageQueue = new ArrayDeque<String>();
        this.logTarget = logTarget;
        this.state = new StateStopped();
    }

    public void start() {
        this.state.start();
    }

    public void stop() {
        this.state.stop();
    }

    public void log(String message) {
        this.state.log(message);
    }

    public String getNextQueuedMessage() {
        synchronized (this) {
            return this.messageQueue.poll();
        }
    }

}

StateStopped

As the state pattern has a context object (here LogService) this context object will be used as the monitor (synchronized(LogService.this)).

My implementation accepts log messages put it will not notify any consumer.

Calling stop() will be a NOOP. If your flavour is to throw an exception do that.

Calling start() will instantiate a new thread and start it. After that the internal state is changed to be "StateRunning".

private class StateStopped implements State {

    @Override
    public void start() {
        synchronized (LogService.this) {
            loggerThread = new LogProcessorThread(LogService.this, logTarget);
            loggerThread.start();
            state = new StateRunning();
        }
    }

    @Override
    public void log(String message) {
        synchronized (this) {
            messageQueue.add(message);
        }
    }

    @Override
    public void stop() {
        // ignore or throw IllegalStateException... your choice
    }

}

StateRunning

As the state pattern has a context object (here LogService) this context object will be used as the monitor (synchronized(LogService.this)).

Calling start() will lead to a NOOP. Here you have the choice to throw an exception as well.

Calling log() will accept new log messages but as the service knows that a thread is available (StateRunning) that may wait for new messages it is notified.

Calling stop() will safely shutdown the thread by communicating a stop request.

We will change the internal state of the LogService within the monitor and waiting until the thread terminates outside the monitor.

private class StateRunning implements State {

    @Override
    public void start() {
        // ignore or throw IllegalStateException... your choice
    }

    @Override
    public void log(String message) {
        synchronized (this) {
            messageQueue.add(message);
            loggerThread.awakeOnWait(); // this is more a callback or an observer pattern
        }
    }

    @Override
    public void stop() {
        Thread lastBreath = null;
        synchronized (LogService.this) {
            lastBreath = loggerThread;
            loggerThread.requestStop();
            loggerThread = null;
            state = new StateStopped();
        }
        try {
            lastBreath.join();
        } catch (InterruptedException e) {
        }
    }

}

LogProcessorThread

This thread while refactoring seems to become more and more an artefact that will ask for log messages from somewhere and passes these log message to somewhere.

Here again: The thread itself is the monitor over "shouldStop" and the critical operations source.getNextQueuedMessage() and target.log(message) that should not be intercepted.

public class LogProcessorThread extends Thread {

    private LogTarget target;
    private LogSource source;
    private boolean shouldStop = false;

    public LogProcessorThread(LogSource source, LogTarget target) {
        this.target = target;
        this.source = source;
    }

    public void run() {
        boolean expectedMoreMessages = true;
        while (expectedMoreMessages) {
            expectedMoreMessages = logNextMessage();
        }
    }

    public synchronized void requestStop() {
        this.shouldStop = true;
        this.notify();
    }

    public synchronized void awakeOnWait() {
        this.notify();
    }

    public synchronized boolean logNextMessage() {

        boolean shouldStop = this.shouldStop; // keep the state stable in this method invocation

        String message = source.getNextQueuedMessage();
        if (message != null) {
            target.log(message);
        }
        if (message == null && !shouldStop) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException("unexpected", e);
            }
        }
        boolean expectMoreMessages = message != null || !shouldStop;
        return expectMoreMessages;
    }

}

LogSource, LogTarget

These are not neccessary but they show the inherent abstraction the thread makes use of. So A LogService is of course a LogSource but it can also be a LogTarget.

public interface LogSource {
    String getNextQueuedMessage();
}

public interface LogTarget {
    public void log(String message);
}


(1) For variable and function names, check_cave (underscore) rather than checkCave (camelcase) are standard in python.

(2) The line def chooseCave needs to be unindented

(3) Your main game loop could probably be neatened up:

while True:
    display_intro()
    check_cave(choose_cave())
    print("Would you like to play again? (yes or no)")
    if input() not in ('yes', 'y'):
        break

(4) conventionally you should put the main game loop in a function called main() and add

if __name__ == "__main__":
    main()

at the end.

(5) More a matter of taste, but I'd find it more elegant to write choose_cave like this:

def choose_cave():
    while True:
        print("Which cave will you choose? (1 or 2)")
        cave = input()
        if cave in ('1', '2'):
            return cave


What changes, if any, are required to make the following Perl eval bullet proof?

Ad. 1. Yes and no - there are still some pitfalls (please read further).

Ad. 2. You must remember about returning truthy value from eval block because it evaluates to last value in block unless some code died, in which case undef is returned, so 1; as last statement in eval block is important.

You also have to localize $@ somehow (my $error = $@ in your example) because it's a global variable which can be changed silently (see Conclusion).

Ad. 3. if ($@) can have one pitfall, i.e. it doesn't catch error when it's false:

eval {
  die '';
  do_something();
};
if ($@) {
  # ooops... we don't get here
}

while or do { } block will always be activated in case of exception

eval {
  die '';
  do_something();
  1;
} or do {
  # caught!
};

Conclusion:

I personally use "eval or do # process error" style of catching errors but common and widely used alternative, which eleminates boilerplate code, is to use Try::Tiny. It's a simple, 0-dependency CPAN module which addresses $@ issues. Its documentation (especially BACKGROUND section) is really worth reading as it answers some of your questions and with even more details.

See also this SO question.


Keeping a Count

You implemented range_iterator to keep a count which you use for equality comparisons. This works, but involves a really awkward formula for getting the count right. Instead, it would be simpler to just round end to be one past the last one, so that range(0, 11, 2) sets start to 0 and end to 12. This would make range_iterator only require two members, and operator!= to just compare the m_value's.

Wrong Type

range_iterator dereferences to int, but should be Int.

Usage

This is awkward:

for (auto i : range<>(start, end, step))
//                 ^^^

Rather than having it be up to the user to provide the correct type, you could instead take advantage of template deduction:

template <typename Int>
Range<Int> range(Int start, Int end, Int step) { ... }

You'll have to rename your class template to get this to work. Even better would be to make the function a friend of the class, and make the constructors private.

Keep begin() and end() simple

Once we rewrite range() to be a function template that returns an object, you can move all of the logical checking into it:

template <typename Int>
Range<Int> range(Int start, Int end, Int step) {
    if (step == 0) throw ...;

    if (start <= end) {
       if (step < 0) {
           return {0,0,0};
       }
       return {start, (end + step - 1) / step * step};
    }
    else {
       // etc.
    }
}

This means that begin() just returns range_iterator{m_start, m_step} and end() just returns range_iterator{m_end, m_step}.

Other Overloads

Python also allows for something like range(10), so that's just:

template <class Int>
Range<Int> range(Int end) {
    return {0, end, 1};
}

Iterator Interface

Even though it won't be fully utilized in the simple example of for (auto i : range(10)), you should prefer to provide a complete interface for range_iterator. You're missing operator== and postfix-increment. Prefix-increment (and postfix-increment) should return references to this.

Additionally, you should inherit from std::iterator<std::forward_iterator_tag, int, std::ptrdiff_t, int, int> just in case somebody wants to use range() as a normal container somewhere else.

For example, it'd be nice to support the following:

auto r = range(10);
std::vector<int> v(r.begin(), r.end());

which currently will fail to compile.


AutoList is for Node of Auto. The name AutoList is very confusing. I would name it as AutoNode so that a reader can know that it's a node element and not a List in itself.


I would change your method to use generics (so that the return value is meaningful) and not call .ToString() internally. This will enable you to use it in more scenarios.

public static T GetValueTernary<T>(this HtmlHelper html, object a, object b, T valueIfEqual, T valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}

Now you can use it like this as well and also it will enable you to use HtmlString-s as values.

...

You could also benefit (depends on your actual usage) from not using object for the compared values - by using a generic the compiler will complain if the types of the two are not compatible (for example, you are comparing string to int):

public static TReturn GetValueTernary<TValue, TReturn>(this HtmlHelper html, TValue a, TValue b, TReturn valueIfEqual, TReturn valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}


Project Euler Problem #3 - largest prime factor

If a number x (with x > 2) is not a prime number, there exists a prime p so that x is divisible by p and p < x.

This means to determine if a number is a prime number, you only have to test it against smaller primes (which you already know). We need one prime (2) to start this process, so we will begin to search for primes from 3 onward.

This technique is known as memoization, which you will find quite useful for many PE problems.

This would lead to the following code (incorporating the points of GameDroids):

int[] primes = new int[somethingSufficientlyLarge];
primes[0] = 2;
primeCounter = 1; // a "pointer" to the next prime

for (int n = 3; n < 10000; n += 2) { // only odd numbers can be primes (except 2)
  bool isAPrime = true;
  for (int i = 0; i < primeCounter; i++) {
    if (n % primes[primeCounter] == 0) {
      isAPrime = false;
      break;
    }
  }
  if (isAPrime) {
    primes[primeCounter] = n;
    primeCounter++
  }
}

Note that using a (Linked) List will make hardcoding the length of the prime array unneccessary. However, there may or may not be performance implications.

But you do not know that the largest prime factor is in fact smaller than 10000. It could be ⌊600851475143/2⌋ for all we know. This would be the proper bound of your search space.

Maybe we can reduce that bound: Every time we find a prime in our sieve loop, we test if number is divisible by that prime. We then do so until the number isn't divisible by that factor. If the result is 1, we can break the loop, as the largest prime factor was found.
The loop runs from 2 to bound, where bound initially is floor(number/2), but once the first factor is found, the bound is the number divided by every factor. If no factor was found, then the number itself is the largest factor.

Example 1:

Factorization of the number 15. Bound is floor(15/2) = 7.
First prime is 2. Not a factor.
Next candidate 3 is prime, is a factor. New bound is 5.
Next candidate 5 is prime, is a factor. Bound drops to 1 → break.
Largest prime factor is 5.

Example 2:

Factorization of the number 13. Bound is floor(13/2) = 6.
First prime is 2. Not a factor.
Next candidate 3 is prime, not a factor.
Next candidate 5 is prime, not a factor.
Loop exits without factor found. 13 itself must be a prime, and its largest prime factor.

General hints:

In your original code you tested for factors in the range (0, n] where n is the number you wanted to factorize. But as no factor can be larger than n/2, you could have reduced the range to (0, ⌊n/2⌋]. This would have reduced substantial overhead. Try to find such cases that can never occur (factors in the range [⌈n/2⌉, n]) and optimize.
In your fist factorization loop you started with the largest factor first. This is bad, as ½ of numbers are divisible by 2, ⅓ by 3, ⅕ by 5 and so on. I.e. you can weed out many non-primes by testing a very small set of numbers. Try to find common cases, and test for them befoe testing for uncommon cases. Also, try to “fail early” (which is wisdom not only applicable to programming).

However, when factorizing your large number, you should have started with the largest possible prime first, count downwards, and stop once you found a factor, instead of looping through all primes


foreach (var source in Sources.Where(x => !destList.Exists(s => s.ElementName == x.ElementName))
{
    var alter = lstAlteration.FirstOrDefault(a => a.ElementName == source.ElementName
                                 && a.ChangeInfo.ChangeFrom == source.ElementName);

    if (alter == null) {
        alter = new Alteration
                    {
                        ElementName = source.ElementName,
                        ChangeInfo = new ChangeDetail()
                    };

        lstAlteration.Add(alter);
    }

    alter.ChangeInfo.ChangeTo = source.ElementName;
}

Sorter
Only one .ChangeInfo.ChangeTo = source.ElementName; execution


Bash pass multiple commands to SSH and make readable

You're quoting the heredoc terminator, so $2 will certainly not be expanded

When you want to pass multiple commands to ssh, wrap them as a single script to an interperter, thus ssh sees one single command.

Lots of whitespace for readability.

And yes, not much opportunity for syntax highlighting.

Since you need variable expansion within the script, you need to worry about quoting variables you want to be expanded on the remote host. I changed the while loop to a for loop to minimize the number of $-signs to escape.

If the script you want to send is more complex, be careful about how you use single and double quotes.

function remoteExec()
{
    echo "remote execution starting"
    ssh -n "$1" << EOF
        bash -c '
            for (( currIt="$2"; currIt < 5; currIt++ )); do
                echo "hello"
            done
        '
EOF
}

Given an arbitrary number of args:

function remoteExec()
{
    local host=$1
    local startIt=$2
    local quotedArgs
    shift 2
    for arg in "$@"; do
        quotedArgs+="\"$arg\" "
    done

    echo "remote execution starting"
    ssh -n "$host" << EOF
        bash -c '
            for (( currIt="$startIt"; currIt < 5; currIt++ )); do
                echo "hello"
            done
            args=( $quotedArgs )
            printf "%s\n" "\${args[@]}"   # escape this sigil
        '
EOF
}

remoteExec host 3 arg1 arg2 "this is arg3"


Your desire to use the "functional way" is not well-motivated. Why do it "the functional way" when the "other way" is not only easier to read, but also common practice, and well-understood?

val stripCurly = "[{}]".r

val replaced = stripCurly.replaceAllIn(a, "")

If you want to have forced-matching of the braces consider:

val pure = """\{([^}]*)\}""".r
val pured = pure.replaceAllIn(content, "$1")

Note the use of the "not a } inside the {}" logic in the regex.

The examples above are running here in ideone


So why is the second sort slightly faster [...]

On my machine, the first algorithm is "faster" (1.588s vs. 1.62s).
The number of samples you have taken (1) is too low to draw conclusions.
For significant statistics, you should run at least 20 times and then compare the average execution time.

  [...] slightly faster [...]

The difference between your two runs is 4 ms.
The precision of the default clock on Windows is ~16 ms., so 4 ms is even within measuring tolerance.

  [...] having more processes

You still only have 1 process. It's not that you find the minimum and maximum in parallel. It's done one after the another.

  other than bubble sort

Bubble sort is typically an in-place algorithm, which means that it operates on one list only. Your implementation works on two lists, templist and list_to_sort1. I would not call this a bubble sort implementation.

BTW:
Python's min() and index() functions seem to be pretty optimized.
A real bubble sort is slower by a factor of ~10 on my machine:

list_to_sort3 = rand_list[:]
start_time = time.time()
for i in range(len(list_to_sort3)):
    for j in range(i):
        if list_to_sort3[j] > list_to_sort3[i]:
            list_to_sort3[j], list_to_sort3[i] = list_to_sort3[i], list_to_sort3[j]
print('\nSorting Complete: Bubble sort took', time.time() - start_time, "to run")

  (comments) I actually meant instructions not processes in reference to the second sort there is a lot more going on yet it takes about the same time.

In version 1 you have:

while 0 < len(list_to_sort1):
    templist.append(list_to_sort1.pop(list_to_sort1.index(min(list_to_sort1))))

This loop runs 10000 times, because it pop()s one item per loop. Thus it also calls min(), index() and append() 10000 times.

In version 2 you have:

while 0 < len(list_to_sort2):
    max_pos = list_to_sort2.index(max(list_to_sort2))
    min_pos = list_to_sort2.index(min(list_to_sort2))

    if len(list_to_sort2) != 1:
        if max_pos > min_pos:
            max_half.append(list_to_sort2.pop(max_pos))
            min_half.append(list_to_sort2.pop(min_pos))
        else:
            min_half.append(list_to_sort2.pop(min_pos))
            max_half.append(list_to_sort2.pop(max_pos))
    else:
        min_half.append(list_to_sort2.pop(0))

This loop only runs 5000 times, because you pop() twice per loop (either in if or in else). Thus it calls min(), max(), index() (twice), append() (twice) also 5000 times.

As you can see, the amount of method calls is the same, although it's more lines of written code.


Write to the event log without needing to check whether or not it exists by use of a `-Force` parameter

There is one fundamental flaw in this script, you need to run the whole script as admin to avoid errors of EventSource.Exists unless you ignore or hide them. But if you do that, then you can as well just use EventLog.WriteEntry that will create the source for you automatically.

There are few problems with your code. Let's try to go through them in the order they appear:
1) Specifying ValueFromPipeline for more than one parameter is not a  good thing to do. Value from pipeline is meant to easily bind input from the pipeline that can't satisfy the properties defined by ValueFromPipelineByPropertyName. Usually you use it to bind the most significant and most volatile piece of information. For Item related cmdlets it is Path. In your case it should be the message.

2) Specifying Force as ValueFromPipelineByPropertyName might have unexpected results. In my point of view you should only bind data this way, not behavior. So binding Message, Source, ComputerName and LogName is OK. Binding Force is not.

3) Specifying position for every parameter is not necessary, the order is inferred by the order of the parameters by default. Specifying position is needed only if you don't need some of the parameters to be positional or you want to define them in order different from their actual usage.

4) Specifying Mandatory=$false is not necessary, it is the default.

5) Switch converts to Boolean implicitly, there is no need to explicitly check for IsPresent.

6) I prefer to use -not instead of !, it keeps you with just one style of operators, plus it's easier to spot.

7) Use parameter splatting to forward complicated calls cmdlets or other functions. Splatting is a technique where you populate a hashtable with keys names as parameter names, and values that are the actual values for that parameter. See example in the code below.

8) Optionally in PowerShell 3 and later you don't need to provide $true to set options of parameters.

9) Optionally set default value to the message type.

 #this is how we'd generall call once we were certain the command had been called at least once with -Force

Why not check in the begin even if the -Force is not specified then?

function Write-EventLog2
{
    [cmdletbinding()]
    param(
        [Parameter(Mandatory,ValueFromPipelineByPropertyName)][String]$LogName,
        [Parameter(Mandatory,ValueFromPipelineByPropertyName)][String]$Source,
        [Parameter(Mandatory,ValueFromPipelineByPropertyName)][Int32]$EventId,
        [Parameter(ValueFromPipelineByPropertyName)][Diagnostics.EventLogEntryType]$EntryType,
        [Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)][String]$Message,
        [Parameter(ValueFromPipelineByPropertyName)][Int16]$Category,
        [Parameter(ValueFromPipelineByPropertyName)][String]$ComputerName,
        [Parameter(ValueFromPipelineByPropertyName)][Byte[]]$RawData,
        [Switch]$Force
    )

    begin
    {
        if($Force)
        {
            if (! ([System.Diagnostics.EventLog]::Exists($LogName) -and [System.Diagnostics.EventLog]::SourceExists($Source) ))
            {
                New-EventLog -LogName $LogName -Source $Source
            }
        }
    }
    process
    {
        $params = @{
            #put mandatory params here directly
            LogName = $LogName
            Source = $Source
            EventId = $EventId
        }
        if($EntryType) { $params.Add('EntryType', $EntryType) }
        if($Message) { $params.Add('Message', $Message) }
        if($Category) {$params.Add('Category', $Category) }
        if($ComputerName) { $params.Add('ComputerName', $ComputerName) }
        if($null -ne $RawData) { $params.Add('RawData', $RawData) }

        #since your parameters are named the same way as Write-EventLog parameters, and you use cmdlet binding
        #you might get away with just specifying @PSBoundParameters
        Write-EventLog @params
    }
}

Another option would be to implement a proxy function for the cmdlet, more info here


In looking at your code, it seems well written and solves the problem in a straight forward manner.  The one thing I would do is to remove the else after your argument check and remove a level of indent.  That just helps to keep things flat... Flat is better than nested.

Now onto optimization and potentially making it more complex than it needs to be in order to make it faster.  In these problems it seems like a reasonable thing to do even though....Simple is better than complex.

Here are a couple things I looked at as potential issues:

When doing the sum(map(power, digits)), you are calculating the power of each digit many times.  If this was a much more expensive calculation then only calculating 1 time is even more important.
In this problem there is a conversion from int->str->int.  If you can breakdown the digits without converting them it saves some time.  It seems like a good thing to know how to do just in case your ever trying a different language where skipping those transitions may be even faster.

To address these, I did two things:

Pre-calculate 1-9 powers and store the results in a dictionary so they don't get recalculated (Memoization).  It lets me look them up very quickly without calculating each time.
Separate the digits using math.log10 as to avoid the int->str->int conversion.

The first item is fairly straight forward, calculating for each digit:

powers = {}
for a in range(10):
    powers[a] = a ** exponent

The second part is a little trickier, what it does is uses math.log10 which gives a count of the digits, then it does a mod 10 to get the right most digit, looks up that power to add to the total and then finally does integer division to divide by 10 effectively moving the decimal place 1 position to the left (dropping the right most digit we just dealt with).  This is probably a little different between Python 2/3 due to changes in int/float division.  It is basically doing what you are using [x for x in str(number)] to do but without converting to string and adding the power of 5 dict lookup as it goes along:

savei = i
for _ in range(int(math.log10(i)) + 1):
    digit = i % 10
    total += powers[digit]
    i //= 10

Applying those changes to the code make it about twice as fast.  Here is what I end up with for the function:

import math

def digit_powers(exponent):
    if exponent <= 1:
        return "The exponent must be at least 2."

    powers = {}
    answer = 0
    # Get the powers
    for a in range(10):
        powers[a] = a ** exponent

    limit = (exponent + 1) * (9 ** exponent)

    # Search for them
    for i in range(10, limit):
        savei = i
        total = 0

        for _ in range(int(math.log10(i)) + 1):
            digit = i % 10
            total += powers[digit]
            i //= 10

        if (total == savei):
            answer += total

    return answer


If any two items in a list is equal to a given number

There's a failing case you might have missed.  If the target number is exactly twice the value of one of the entries, then you'll wrongly return true.

Test case:

anyequalto([5], 10)

Besides that, try to think of a better name for the function.  Perhaps contains_pair_totalling() as a start?


Stack that does Push, Pop and Median in O(1)

minHeap.add(item);
        maxHeap.add(item);

Adding to a PriorityQueue is not \$O(1)\$.  It is \$O(\log{n})\$.

Same thing for removal.

    public int median(){
        return (minHeap.peek() + maxHeap.peek())/2;

    }

This is not a median.  The smallest and largest elements are totally irrelevant to a median.  In 4, 5, 6, then 5 is the median.  In -4000, 5, 6000, then 5 is still the median.  The only time you take an average to get a median is if there are an even number of elements in the set.  E.g. in 2, 4, 6, 8, then \$(4+6)/2 = 5\$ is the median.  Note that it is only the middle items in the set that matter.


Takes in two sorted lists and outputs a sorted list that is their union

I think your solution is ok.

Instead of using continue, consider using if..elif..elif..else:

if k >= len1:
  ...
elif j >= len2:
  ...
elif ...:
  ...
else:
  ...

Also, the test k >= len1 is an example of "defensive programming". It protects against k skipping over len1 when being incremented in the loop. Also, the expression list1[k] doesn't make sense unless k < len1, and the negation of that is k >= len1 which is another good reason to use it in the if statement.

If you've learned about xrange() then I would use that instead of range() -- see these SO answers:

https://stackoverflow.com/questions/135041/should-you-always-favor-xrange-over-range

Otherwise it looks good!


Animation base class

typedef std::chrono::high_resolution_clock hrc;

In modern C++, use an alias-declaration:

using hrc = std::chrono::high_resolution_clock;

It is arguably more readable.

std::chrono::time_point<hrc> m_now;

unsigned int m_us;      // us for microseconds
unsigned int m_endUs;

The types and names of the last two members are not helpful.  (By the way, unsigned int = unsigned.)  And they should be private:

private:
    using time_point = std::chrono::high_resolution_clock::time_point;
    time_point m_now;

    using duration = std::chrono::high_resolution_clock::duration;
    duration m_time_elapsed;
    duration m_total_time;

The derived classes should have read-only access to m_total_time:

protected:
    auto total_time() const
    {
        return m_total_time;
    }

void UpdateTime() {
    auto end = hrc::now();
    auto diff = end - m_now;
    m_now = end;
    auto msDuration = std::chrono::duration_cast<std::chrono::microseconds>(diff);
    m_us += (unsigned int)msDuration.count();
}

This function is a bit complex because of the conversion between different types.  They can be simplified:

void UpdateTime()
{
    auto time = hrc::now();
    time_elapsed += time - m_now;
    m_now = time;
}

Animation() {
    m_us = 0;
    m_now = hrc::now();
}

The constructor should provide a means to set the m_total_time member.  And it should use member initializer clauses instead of assignment:

template <class Rep, class Period>
explicit Animation(const std::chrono::duration<Rep, Period>& total_time)
    : m_now{hrc::now()}
    , m_time_elapsed{}
    , m_total_time{total_time} // std::chrono::duration supports conversion
{
}

(The support for different durations is for convenience.)

bool finished() {
    return m_endUs <= m_us;
}

You are missing const.

virtual bool Update(sf::Sprite& spr) = 0;

Good.

Animation child class

FadeIn(int ms) {
    m_endUs = ms * 1000;
}

Missing explicit — an integer is not logically a FadeIn.  Type mismatch (you are using unsigned in the base class).  With the design mentioned, just do this:

using Animation::Animation;

And the constructors will work as expected.

// Updates the sprite based on the timeline, and returns if the animation is over
virtual bool Update(sf::Sprite& spr) {
    UpdateTime();
    if (finished()) return true;

    sf::Color color = spr.getColor();
    color.a = (int)((float)m_us / m_endUs * 255);
    spr.setColor(color);
    return false;
}

Missing override.  Don't use C-style casts.  float may be too imprecise for this calculation.  Don't put the whole if statement on a single line.

The color algorithm should be in a separate function:

private:
    sf::Color get_color() const noexcept
    {
        auto color = spr.getColor();

        double ratio = static_cast<double>(m_time_elapsed) / m_total_time;
        color.a = static_cast<int>(ratio * 255);
        return color;
    }

Also, if overflow is not a concern, just multiply first and then divide to avoid the floating point.  And then the function can be simplified:

virtual bool Update(sf::Sprite& spr) override
{
    UpdateTime();

    if (finished()) {
        return true;
    } else {
        spr.setColor(get_color());
        return false;
    }
}

Render Component

RenderComponent() { }
RenderComponent(sf::Drawable* element, sf::Vector2u size) {
    sf::RenderTexture rt;
    rt.create((unsigned int)size.x, (unsigned int)size.y);
    rt.draw(*element);
    m_texDefault = rt.getTexture();
}

Good — except for the C-style casts:

remove them if possible;
otherwise, use unsigned{size.x} if possible;
otherwise, use static_cast.

template <typename T, typename... Args>
void SetAnimation(Args... args) {
    m_animationPtr = std::make_unique<T>(args...);
}

You are missing perfect forwarding:

template <typename T, typename... Args>
void SetAnimation(Args&&... args)
{
    m_animationPtr = std::make_unique<T>(std::forward<Args>(args)...);
}

void draw(sf::RenderTarget* target) {
    sf::Sprite sprite;
    sprite.setTexture(m_texDefault);

    // Handle animation and set pointer to null if done
    if (m_animationPtr) {
        if (m_animationPtr.get()->Update(sprite)) {
            m_animationPtr = nullptr;
        }
        sf::Color c = sprite.getColor();
    }
    target->draw(sprite);
}

Always turn warnings on — unused c variable should issue a warning.  (I am pretty sure sprite.getColor() has any side effects.)

A helper function

sf::Vector2u floatRectToVec2u(sf::FloatRect r) {
    sf::Vector2u vec;
    vec.x = (unsigned int)ceil(r.width);
    vec.y = (unsigned int)ceil(r.height);
    return vec;
    auto start = std::chrono::high_resolution_clock::now();
}

This function is a pure math function, so should probably be noexcept.  The name is a bit awkward — it does not mention ceil at all.  Also, it seems that ceil should be std::ceil.  And what does the last line do?

If sf::Vector2u can be constructed with the coordinates, the code is simplified:

sf::Vector2u ceil_vector(sf::FloatRect r)
{
    return {std::ceil(r.width), std::ceil(r.height)};
}

Main function

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);
    RenderComponent circle(&shape, floatRectToVec2u(shape.getGlobalBounds()));
    circle.SetAnimation<FadeIn>(1000);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        circle.draw(&window);
        window.display();
    }

    return 0;
}

The main function looks nice.  (I don't why you are explicitly specifying 100.f here instead of 100, but maybe there's a good reason.)  return 0; is redundant for main and can be omitted.  event can be declared in the inner loop with for.


Maximum absolute difference of array elements

There is a (simple) linear time (and by necessity space) solution. My thanks to 'random person next to me' for being a Rubber Duck in this process.

It's really very simple: observe that |Ai - Aj| + |i - j| is just the maximum of 4 other functions: + Ai + i - Aj - j, + Ai - i - Aj + j, - Ai + i + Aj - j, - Ai - i + Aj + j.

Knowing this, we can compute one half of each of these (e.g. + Ai + i) for each value in linear time and store them in an array. Now the half-clever bit is this: if we 'look' at point j, we know that if our best partner (i) is to the left of us (i.e. i <= j) that it is the i to the left of us with either the largest + Ai + i or - Ai - i, to which we will add - Aj - j or + Aj - j to compute the result. The same is true for the j to our left, (excluding our current j), and for the j next to him, etc. This means we can compute the 'best' is for the js to their right all at the same time (linear) and then just look them up when we compare them to each j. The same can be said for j < i.

Duly, we can compute 4 arrays, one for each of the 4 functions that we need to find the maximum of, but only containing the Ai and i components, and replace any element smaller than any element to the right (or left) with the greatest element to it's right (or left):

With these 4 arrays built (in linear time) we can loop through the array, computing the other half (e.g. - Aj - j) and find the max of adding each half to it's corresponding other half. Our solution is then just the max of these sums.

In actuality, this can be implemented very cleanly as just 1 pass over the original array, where we keep track of the largest + Ai + i and - Ai + i, and compare it to the current Aj and j sums (we can argue from symmetry that going the other way is pointless - we know that the optimal has a 'left' and a 'right', we only need to look at one of them).

/// <summary>
/// Finds the max of |Ai - Aj| + |i - j|
/// </summary>
/// <param name="A">The array of Ai</param>
/// <returns>The max of |Ai - Aj| + |i - j|</returns>
public static int SimpleSuperiorMaxArr(int[] A)
{
    int best = 0; // known lower bound

    int bestPosi = 0;
    int bestNegi = 0;
    bool first = true;

    for (int i = 0; i < A.Length; i++)
    {
        int posi = A[i] - i;
        int negi = -A[i] - i;

        if (first || posi > bestPosi)
        {
            bestPosi = posi;
        }

        if (first || negi > bestNegi)
        {
            bestNegi = negi;
        }

        int posj = -A[i] + i;
        int negj = A[i] + i;

        int pos = bestPosi + posj;
        int neg = bestNegi + negj;

        int m = Math.Max(pos, neg);

        if (m > best)
        {
            best = m;
        }

        first = false;
    }

    return best;
}

owing to the algorithms simplicity, we can implement it in Excel without any trouble at all!

All of the functions are as on the left, with the 'best' rows being the max of the current value and the previous (or just current for the first column). Note that it works left-to-right, so the 'best' rows never decrease in value to the right. The 'ans' is just the max of all of the bottom pair of rows.

Edit: old code kept for posterity:

This code isn't the highest quality code ever, but it seems to work.

/// <summary>
/// Finds the max of |Ai - Aj| + |i - j|
/// </summary>
/// <param name="A">The array of Ai</param>
/// <returns>The max of |Ai - Aj| + |i - j|</returns>
public static int SuperiorMaxArr(int[] A)
{
    // Computes the array of Ai * ac + i * ic
    int[] ComputeInfoArray(int ac, int ic) // for our case, ic and direction are equal
    {
        int direction = -ic; // if we are adding i, then we are the 'right' array, otherwise we are 'left' array
        int[] iarr = new int[A.Length];

        bool first = true;
        int b = 0; // current best

        int s = direction > 0 ? 0 : A.Length - 1;
        int e = direction > 0 ? A.Length : -1;

        for (int i = s; i != e; i += direction)
        {
            int t = A[i] * ac + i * ic;

            if (first || t > b)
            {
                first = false;
                b = t;
            }

            iarr[i] = b;
        }

        return iarr;
    }

    int[] LeftLow = ComputeInfoArray(1, -1); // + Ai - i
    int[] LeftHigh = ComputeInfoArray(-1, -1); // - Ai - i
    int[] RightLow = ComputeInfoArray(1, 1); // + Ai + i
    int[] RightHigh = ComputeInfoArray(-1, 1); // - Ai + i

    int best = 0; // known lower bound

    for (int j = 0; j < A.Length; j++)
    {
        int ll = LeftLow[j] + j - A[j];
        int lh = LeftHigh[j] + j + A[j];
        int rl = RightLow[j] - j - A[j];
        int rh = RightHigh[j] - j + A[j];

        // in truth, we can just compute ll + lh

        int max = Math.Max(Math.Max(ll, lh), Math.Max(rl, rh));

        if (max > best)
            best = max;
    }

    return best;
}


Calculating a total price with group pricing

Removing intermediate variable $webinar_count

$total_price = ($_POST['meeting_type'] == 'w')
             ? (ceil($guests / 10) * $price)
             : ($guests * $price);

OR

if ($_POST['meeting_type'] != 'w') {
    $total_price = $guests * $price;
} else {
    $total_price = ceil($guests / 10) * $price;
}


In

        if (compareScreens(screenShot, screenShot2) < threshHold) {
            idle = true;
        } else {
            idle = false;
        }

Isn't this better as

        idle = compareScreens(screenShot, screenShot2) < threshHold;

Here, why initialize robot to null first? Isn't this given in the constructor? And why do you continue if there is an AWT exception? Doesn't it mean no GUI? perhaps your constructor should throw that exception. Otherwise, perhaps it is better to have a larger block for try catch. The reason is that the exception handling code is better away from the main sequence. You use robot in the run code. So in order for that to run, robot has to be non null. So catching the exception here is not correct.

    // setup the robot.
    robot = null;
    try {
        robot = new Robot();
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

You also set idle to false, which is not really needed because it is initialized to false by java.

Why do you take an extra screen shot? Isn't this what you mean?

public void run() {
 try {
    BufferedImage screenShot = null;
    BufferedImage screenShotPrev
         = robot.createScreenCapture(screenDimenstions);
    while (true) {
        Thread.sleep(idle ? idleTime : activeTime);
        screenShot = robot.createScreenCapture(screenDimenstions);
        idle = compareScreens(screenShotPrev, screenShot) < threshHold;
        screenShotPrev = screenShot;
    }
 } catch (InterruptedException e) {
    ...
 }

Here, where do you use the changed? (as noted in comment to the question.)

private double compareScreens(BufferedImage screen1, BufferedImage screen2) {
    int counter = 0;
    boolean changed = false;

    // Count the amount of change.
    for (int i = 0; i < screen1.getWidth() && !changed; i++) {
        for (int j = 0; j < screen1.getHeight(); j++) {
            if (screen1.getRGB(i, j) != screen2.getRGB(i, j)) {
                counter++;
            }
        }
    }

    return (double) counter
            / (double) (screen1.getHeight() * screen1.getWidth()) * 100;
}

The for loop may be better as

 int[] s1 = ((DataBufferInt) screen1.getRaster().getDataBuffer()).getData();
 int[] s2 = ((DataBufferInt) screen2.getRaster().getDataBuffer()).getData();
 for(int i = 0; i < s1.length; i++)
     if (s1[i] != s2[i]) counter++;

Since it avoids multiple calls to getRGB.

And is there any chance of getHeight or getWidth returning 0?
Also, I assume that you are calling .run instead of .start only because you are testing?


Granular vs a aggregated tests when dealing with arrays

I prefer the second option: using a test for both facets of the behavior.
While it has a lot of assertions, I feel it covers the behavior well in one go, removing duplication.
From a pure code economy point of view, we achieve the same thoroughness as the two tests scenario with just one extra line of code.
Moreover, in the two tests example, the first test would pass regardless of how the output is built, as long as it contains only one element. Yes, the second test is there to make sure the Group is built properly, but I'm somehow uncomfortable with how close to a false positive the test that only checks the array count is.
If the second tests was to be removed, code coverage tools wouldn't register a change in coverage, but the thoroughness of what is checked would decrease.


There is a simple solution that does not require a dictionary:

int[] A = { 9, 3, 9, 3, 9, 7, 9};
int result = 0;
foreach (var i in A)
    result ^= i;
Console.WriteLine(result); // 7

The trick here is, that "a xor a" gives 0. So all number will be erased except the single one.

Or in short:

var result = new [] { 9, 3, 9, 3, 9, 7, 9}.Aggregate(0, (a, b) => a^b);

To you solution with the dictionary:

You don't need a dictionary. You could just use a Hashset. Add a new entry if the entry does not exists and remove the entry if it already exists. After processing all items, the hashset should have one item - the result.


Generic Comparator Using Class Fields & Lambda Java

If you want suggestions for improvement, here is one:

The following code:

private static <T> Field getField(Class<T> clazz,String fieldName){
    Field field = null;
    try {
        field = clazz.getDeclaredField(fieldName);
    }catch(java.lang.NoSuchFieldException e){
        e.printStackTrace();
    }
    return field;
}

is best rewritten as follows:

private static <T> Field getField(Class<T> clazz,String fieldName) {
    try {
        return clazz.getDeclaredField(fieldName);
    }catch(java.lang.NoSuchFieldException e){
        throw new RuntimeException(e);
    }
}

The following code:

//Lambda comparator
Comparator<T> orderByComparator = (f1, f2) -> {

    Comparable compA = null;
    Comparable compB = null;

    // getting fields from object f1,f2
    try {
        compA =(Comparable) field.get(f1);
        compB =(Comparable) field.get(f2);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    // handling null comparators
    if(compA == null)
        return -1;
    else if(compB == null)
        return 1;

    return compA.compareTo(compB);
};

is best rewritten as follows:

Comparator<T> orderByComparator = (f1, f2) -> {
    Comparable compA, compB;
    try {
        compA = (Comparable) field.get(f1);
        compB = (Comparable) field.get(f2);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    return Objects.compare(compA, compB, Comparator.naturalOrder());
};

in short:

lose the useless comments; a comment is only useful if it says something that is not immediately obvious by looking at the code
do not initialize variables to nonsensical values, because then the compiler will not warn you when you forget to assign something meaningful to them
if you do not know what to do with an exception, do not print a stack trace, throw a runtime exception instead.

Generics and lambdas have no impact on performance.


Insert value into multiple locations in a list

Is it intended that insertAt 999 [1] [1..10] inserts 999 at index 1, but insertAt 999 [0] [1..10] does nothing.  Shouldn't it insert a value at index 0?
Also, it looks like certain other insertions don't work correctly:
> insertAt 999 [2,5,6,7] [1..10]
[1,2,999,3,4,999,5,999,6,7,8,9,10]

Note that this inserts only at indices 2, 5, and 7 and appears to skip index 6.
My guess is that you probably wanted something more like:
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices xs = go 0 xs
  where
    go _ [] = []
    go j (y:ys)
      | j `elem` indices = x : go (j+1) (y:ys)
      | otherwise        = y : go (j+1) ys

which handles these cases correctly:
λ> insertAt 999 [0] [1..10]
[999,1,2,3,4,5,6,7,8,9,10]
λ> insertAt 999 [2,5,6,7] [1..10]
[1,2,999,3,4,999,999,999,5,6,7,8,9,10]

It doesn't insert anything for insertAt 999 [10] [1..10], but if you want that to insert at the end, then you need a slight modification:
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices xs = go 0 xs
  where
    go j yall   | j `elem` indices =  x : go (j+1) yall
    go j (y:ys)                    =  y : go (j+1) ys
    go _ []                        = []

which works like so:
λ> insertAt 999 [0] [1..10]
[999,1,2,3,4,5,6,7,8,9,10]
λ> insertAt 999 [2,5,6,7] [1..10]
[1,2,999,3,4,999,999,999,5,6,7,8,9,10]
λ> insertAt 999 [10] [1..10]
[1,2,3,4,5,6,7,8,9,10,999]
λ> insertAt 999 [10,11,12] [1..10]  -- multiple consecutive indices off the end
[1,2,3,4,5,6,7,8,9,10,999,999,999]

I think this version is quite readable.  The main efficiency problem is that, if indices is more than a few elements, the repeated linear traversals of the elem function through the indices list will be slow.  A second efficiency problem is that if all the insertions are near the beginning, you will end up traversing the entire input list even after all the insertions have been performed.
You can improve the performance substantially by using an IntSet.  (A plain Set from Data.Set would work, too, but IntSets are even faster for sets of Ints.)
import qualified Data.IntSet as IntSet
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices = go 0
  where
    indices' = IntSet.fromList indices
    go j yall | j `IntSet.member` indices' =  x : go (j+1) yall
    go j (y:ys)                            =  y : go (j+1) ys
    go _ []                                = []

You could also pass the IntSet as a parameter to go and delete indices as they are used.  This might be faster, but you'd need to benchmark it to be sure:
import qualified Data.IntSet as IntSet
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices = go 0 (IntSet.fromList indices)
  where
    go j indices' yall | j `IntSet.member` indices' =  x : go (j+1) (IntSet.delete j indices') yall
    go j indices' (y:ys)                            =  y : go (j+1) indices' ys
    go _ _ []                                       = []

This would also allow you to stop inserting when the list of indices is empty, but again, only benchmarking will tell whether or not this is faster:
import qualified Data.IntSet as IntSet
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices = go 0 (IntSet.fromList indices)
  where
    go _ indices' yall | IntSet.null indices'       =  yall
    go j indices' yall | j `IntSet.member` indices' =  x : go (j+1) (IntSet.delete j indices') yall
    go j indices' (y:ys)                            =  y : go (j+1) indices' ys
    go _ _ []                                       = []

Personally, I think I probably would have approached it by writing a go function that operates on the current index and a sorted list of indices:
insertAt x indices = go 0 (sort indices)

This way, we can directly compare the current index with the next insertion point in the sorted list:
go j (i:is) (y:ys) | i == j = ...

This variant would look something like:
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices = go 0 (sort indices)
  where
    go _ []     yall              = yall
    go j (i:idxs) yall   | j == i = x : go (j+1) idxs yall
                         | j >  i = go j idxs yall -- delete duplicate indices
    go j idxs     (y:ys)          = y : go (j+1) is ys
    go _ _        []              = []

This avoids those efficiency problems I mentioned earlier without having to switch to a different data structure.  Sorting the index list and consuming it as insertions are made will avoid any traversals through the index list, since you're only ever looking at the list's head.  Also, when the index list is empty, the go _ [] yall = yall case will immediately return the remaining list without further processing.
I'm not sure that there's any clever, non-recursive method that uses folds or other functions from Data.List and ends up being better than the above.  You can replace the recursion with unfoldr.  For example, given the version from above:
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices xs = go 0 xs
  where
    go j yall   | j `elem` indices =  x : go (j+1) yall
    go j (y:ys)                    =  y : go (j+1) ys
    go _ []                        = []

you can rewrite this as:
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices lst = unfoldr step (0, lst)
  where step (j, lst)  | j `elem` indices = Just (x, (j+1, lst))
        step (j, y:ys)                    = Just (y, (j+1, ys))
        step (_, [])                      = Nothing

and the other versions can be rewritten similarly.  This doesn't particularly improve readability, and I doubt it's more efficient.
Another completely different approach might be to intercalate the insertion value into a sequence of sublists generated from the indexes.  So, for example, given the indexes [2,5,6,7], you might want to first break the input list [1..10] up into sublists between the insertions:
[[1,2],[3,4],[],[],[5,6,7,8,9,10]]

It might be easiest to first convert a sorted list of indices into a list of sizes for all the sublists except the last:
indicesToChunks :: [Int] -> [Int]
indicesToChunks indices = zipWith (\i j -> i-j-1) indices (-1 : indices)

giving:
> indicesToChunks [2,5,6,7]
[2,2,0,0]

and then write a function to break a list into sublists based on these sublist sizes.  It's pretty easy to write recursively:
chunks :: [Int] -> [a] -> [[a]]
chunks [] lst = [lst]
chunks (n:ns) lst = a : chunks ns b
  where (a,b) = splitAt n lst

Then, you can write:
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices = intercalate [x] . chunks (indicesToChunks (sortu indices))
  where -- unique elements in sorted order
        sortu = map head . group . sort

The definition of sortu is weird, but it's a reasonable method of sorting and removing duplicates.  (The nub function in Data.List removes duplicates, but doesn't do it efficiently for sorted lists, the way map head . group does.)
Note that this version behaves a little differently than the others, if there are insertions at the end of the list that skip indexes.  The earlier versions all insert only one 999 at the end of the list in this example:
> insertAt 999 [10,1000] [1..10]
[1,2,3,4,5,6,7,8,9,10,999]

treating the 1000 as an out-of-bounds index.  However, the intercalate-based version inserts two 999s:
> insertAt 999 [10,1000] [1..10]
[1,2,3,4,5,6,7,8,9,10,999,999]