Group by two lists in one map using lambda

This does not look horribly wrong to me. There are some issues though:

groupingBy I presume is a static import from Collectors? You should make these things more obvious. In fact, I dislike the static imports for most things.....
you don't show much about ruleKeys.

The style otherwise looks good.

The concept you are solving, given the information you have given, is being solved in what amounts to a reasonably efficient manner, all things considered. It is an \$O(nm)\$ solution, if you double either the number of rules, or number of keys, your solution will take twice as long, and if you double both, the solution will take 4 times as long.

If you do this just once and then reuse the Mapping, then it should be fine. If you have fewer than say 100 members in each of the rules/keys, then you should be fine.

If you have more data than that then you should consider building up the data directly in to the map at the same time as you initially populate the rules/keys.

So, you are right to not like the solution because it scales badly, but, if your data is small, be pragmatic and not worry about it too much in this instance.


Storing char* in a vector leads to leaks. instead use std::string, which will manage its own buffer and delete it as needed.

vector<string> values;

inserting to the back of a vector can be done with push_back or you can construct in place with emplace_back in C++11:

while(in.getline(thisVal,MAXSIZE,',')) {
    string str(thisVal);
    values.push_back(std::move(str));
    //std::move signals that I won't be using str anymore and that the underlying buffer can just be passed through to the new element.
    // After this str will not be valid. You can still assign to it normally but until you do any result of calling a method on it will be implementation defined.
}

or

while(in.getline(thisVal,MAXSIZE,',')) {
    values.emplace_back(thisVal);
}

Failing to open a file is common enough to use an explicit if and print an error message instead of asserting (which won't do anything when compiled as a release version):

if(!in.is_open()){
    cerr << "failed to open file.";
    return 1;
}

I return 1 here to signal to the OS that the program didn't finish successfully and a script using it can then react to it.


Speed up javascript code to convert csv to geojson

From a short review;

Old school for loops still beat map

Prevent repeated object[string] access, like accesssing several times item[latName], because it is relatively slow

Is it absolutely necessary to create a new object? I have a suspicion that modifying the object would be faster. (Yes, not great practice, but you are looking for speed, you should try this)

One more thing, I was hesitant to mention this but, but the plus operator can be faster than parseFloat according to jsperf. So you could just go for
  const newLat = +item[latName];
  const newLong = +item[longName];

give it a shot, let us know ;)
This is my counter proposal with in place conversion;
function convertLocationToNumbers(data, latName, longName) {
  const dataLength = data.length;
  for(let i = 0; i < dataLength; i++){
    const item = data[i];
    //Dont check for hasownproperty, just go!
    const newLat = +item[latName];
    const newLong = +item[longName];
    if(isNaN(newLat) || isNaN(newLong ){
      item[latName] = 42.2;
      item[lonName] = ~83.6;
    }else{
      item[latName] = newLat;
      item[lonName] = newLong;
    }
  }
}


IMHO there is nothing in this class that requires integration testing. At most you should be able to mock it, but all of its functionality is calling methods that are presented by the framework (or by a NuGet package, e.g. the JSON serialization). If you feel the need to test those, then why not write a test to check that the return value of some method that returns a string is actually a string and not some other type of object?
You could argue that perhaps it might fail to create a file because it needs to do so on a share and that share is inaccessible, but then it is perfectly possible that this happens on production and not a single integration test will catch it. That's why exceptions exist and logging etc.
And that's where your code really fails: at no point do you apply a try...catch and do you log any possible IO exceptions. Sure, maybe your exception will bubble up and get caught elsewhere and reported, but you need to be sure about that. For instance: it is entirely possible an existing file cannot be deleted because another process has it locked.
Perhaps you should catch any IO exceptions here and return a bool to report back whether the file was written without issues (if you care about that, if other code depends on the file existing,...).

Your WriteFileOutput class is also pretty bad in other ways. Its name sounds like a method and is fairly undescriptive anyway. Moreover, you've obviously copy-pasted code instead of thinking through its logic. This does exactly the same while using far less lines and has no duplication:
    if (System.IO.File.Exists(File))
    {
        System.IO.File.Delete(File);
    }

    using(var tw = new StreamWriter(File, true))
    {
       tw.WriteLine(result.ToString());
       tw.Close();
    }

Some quick remarks:

What is even the point of else if (!System.IO.File.Exists(File))? What else could the else to if (System.IO.File.Exists(File)) even be?

public void writeFile doesn't follow the standards WRT naming (methods should be PascalCase).

Why is this public: public string File { get; set; }? Why can it be set from outside?

Both File and fileName are incorrect names. You're clearly passing a path to a file, not the name of a file (and "File" is even less descriptive).

result is too generic a name.

Are you saving other objects in much the same way as List<CustomerDistanceRecord> invitees? If so, do you have a specialized class for each of those? Because that seems overkill to me when the logic of writeFile (except for var result = JsonConvert.SerializeObject(invitees, Formatting.Indented);) can easily be reused.


Small function and level of abstraction - clean code - refactor further

First of all, each condition and formatting will be moved to your own class. Let's create a common interface:

interface FormattingRemover
{
    bool Match(string value);
    string RemoveFormat(string value);
}

Now we can use it to abstract the formatting:

public class RemoveBold : FormattingRemover
{
    public bool Match(string value) {
        // your condition here
        return true;
    }

    public string RemoveFormat(string value) {
        return RemoveBold(value);
    }
}

In your class you'll need a list with all implementantions of FormattingRemover, iterate over it and when the value matches, you can remove its formatting.

private removers = AllRemovers();

private string Fix(ChangeLogFixOperationPreferences preferences,string value)
{
    foreach (var remover in removers)
    {
        if (remover.Match(value))
        {
            value = remover.RemoveFormat(value);
        }
    }

    return value;
}

For now on, you just need to add new implementations to provide it with AllRemovers. A good idea is inject it with some DI container, like Ninject.


A few tips for leaner code:

Use enumerate while iterating when you need the index, to avoid the sequential search and extra verbosity of orParas.index(orPara). For example the last loop becomes

for orIndex, orPara in enumerate(orParas):
    matchSet.insert(orIndex + shifter, (orIndex + shifter, "-"))

max(matchTuples) achieves the same as sorted(matchTuples, key = lambda tup: tup[0])[-1] and avoids sorting. You could even give a key argument to max, but tuples are sorted item by item anyway, and here the second item is an ascending integer, so including it in the sort key does not change the order.
Unpacking bestRatio, bestIndex = max(matchTuples) improves readability as you can use bestRatio instead of bestMatch[0] in the code that follows.


private enum Fields {
    referrer, ip, userAgent, email

It is customary to use UPPERCASE for enum members.

private static Document getDocument(String referrer, String ip, String userAgent, String email) {

I wouldn't mind seeing a javadoc somewhere that explains what a referrer URL looks like. It can be quite detailed, including ? query terms, but I imagine you strip it down to page or FQDN level, or perhaps even to 2nd-level domain, which .co.uk and others add interesting wrinkles to.

Similarly, I expect ip looks like "10.0.1.2", but some folks prefer the sort order they get from normalizing to "010.000.001.002" or compact hex "0A000102". And the UA might be case-smashed or truncated, and (at least the 2nd half of) the email might be case-smashed, as well.

Some folks choose to blacklist a prefix rather than a /32 individual IP, e.g. matching first three bytes for a /24, or masking for a /20. If you could typically combine 512 IPs into a /23 prefix, your DB would shrink by orders of magnitude, making cache hits go up and random I/Os go down, supporting higher query rates.

I see no evidence that your server answers IPv6 clients. Handling prefixes would be even more important in that environment.

Kudos for following Webster, despite history.
Oh, actually, wait! Does Fields.referrer.name() even work? Or does it return one more "r" than headers arriving off-the-wire have?
Do tests succeed?

Thank you for adding the getStringField() helper - it improves readability.
I wonder if we could achieve even greater conciseness by putting it in the Fields class?

            .add(new TermQuery(new Term(key, value)), BooleanClause.Occur.SHOULD)

I'm reading BooleanClause.Occur :

  SHOULD.
  Use this operator for clauses that should appear in the matching documents. For a BooleanQuery with no MUST clauses one or more SHOULD clauses must match a document for the BooleanQuery to match.

I wouldn't mind seeing a comment explaining why SHOULD works better here. The simplest thing to do seems like MUST - then the Gentle Reader wouldn't be puzzling out what other interactions there might be, what might override it.

private static boolean isBlacklisted(String ref, String ip, String ue, String email) throws IOException {

The ue identifier is very odd. A more natural choice would be ua.

    RAMDirectory directory = new RAMDirectory();

Rather than invent a name for this temp, you might have just buried it in the IndexWriter() call. Then I don't have to worry about other interactions further down in the code. Code with fewer variables in-scope is code that is more easily read at a glance.

    cache = new IndexSearcher(reader);

I would have preferred to see this as a static initializer, rather than deferring until main runs, to make your public API easier to use and so more reusable. Static initializers run at class load time, which can threaten to introduce cyclic dependencies among your own classes, but here the app and the library are well separated so I don't have that concern.

    System.out.println(isBlacklisted("ref1", "127.0.0.ip1", "Mozilla UserAgent1", "email.com")); // true
    System.out.println(isBlacklisted("r2.com", "127.0.0.4", "Mozilla", "yahoo.com")); // false

Well! Now we finally get down to brass tacks, answering some doubts I voiced above. Ok, first thing, it's nice to see the test results printed, but it would so much nicer to have a self-evaluating test, e.g. assertTrue in JUnit.

POLA violation: I was not expecting that "ref1" might be a plausible valid input. Yes, I understand you're making up test inputs. But that's not even an FQDN. Maybe I should understand the substring "hoo" would match "yahoo.com"? When I saw referrer I was kind of mislead into thinking in RFC terms, rather than grep -F terms. At some point you'll blacklist "oo.com" and then see interesting interactions.

Similarly "ip1" was unexpected, and while "Mozilla" makes perfect sense the longer UAs are very test oriented, given that matching a structured user-agent is complex in its own right. Consider pre-processing "equivalent" UAs down to a single-word identifier before handing them to Lucene.

Test coverage seems light. At a bare minimum you probably want four or eight tests, each with three wildcards, so you can focus on individual field behavior.

Test cases are an opportunity to educate folks about your public API, just as javadoc offers an opportunity to educate.  Good test data can help to reveal your intent.

It's hard to comment on performance when it isn't clear what semantics you support (e.g. substring vs. prefix-match) and what Lucene features you considered using to support performant queries. Add some benchmark results, and contrast e.g. "Lucene answers 20 query/second" with a requirement of "peak web traffic is 10 hit/sec" or "is 30 hit/sec" so we can see any gap. Mention Winchester vs. SSD, and available RAM. It would be useful for IddoE to create a separate Answer posting that describes any recent work with this code.

Caching is a big deal for performance, so you will need a representative workload, either synthetic or gathered from production. Issuing 20 high-entropy queries each second is very different from 20 predictable queries.

Lucene is very nice, and can be fast. In createQuery() it's not obvious to me that trusting Lucene to optimize MATCH_ALL will yield fastest results. You could just suppress such terms, so Lucene considers between 1 and 4 fields according to how many MATCH_ALL's you used.


Here are some observations that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, none of the digit_ variables are ever actually used.  My compiler also tells me that.  Your compiler is probably also smart enough to tell you that, if you ask it to do so.

Consider using a better random number generator

Because you're using a compiler that supports at least C++11, consider using a better random number generator.  In particular, instead of rand, you might want to look at std::uniform_real_distribution and friends in the <random> header.

Use string concatenation

The main function includes these lines:

std::cout << "\n";
std::cout << "\tAvailable numbers in your area.";
std::cout << "\n\t******************************";
std::cout << "\n\n";

Each of those is a separate call to operator<< but they don't need to be.  Another way to write that would be like this:

std::cout << "\n"
            "\tAvailable numbers in your area."
            "\n\t******************************"
            "\n\n";

This reduces the entire menu to a single call to operator<< because consecutive strings in C++ (and in C, for that matter) are automatically concatenated into a single string by the compiler.

Consider improving names

The variable input is not very descriptive.  Perhaps areaCode would be a better name.

Add error checking

The program appears to assume that the user will enter a valid 3-digit area code, but no provision is made to assure this.  A robust program always checks user input and provides error checking and handling.

Use object orientation

Because you're writing in C++, it would make sense to have a class such as PhoneNumber to encapsulate the details of your implementation.  You may not yet have learned about objects or classes, but they're one of the main strengths of C++ and something you should learn soon if you haven't already.  Use objects where they make sense.

Understand the problem domain

In the US and Canada (which, by the formatting of the phone number, seems to be where this is intended to be used), phone numbers are created according to the North American Numbering Plan.  In that plan, the second grouping of numbers is called that Central office code.  That three-digit number must start with a number in the range of 2 through 9 and cannot start with a 0 or 1.  Your current program does not obey this scheme and generates invalid numbers.


Performance of Codility MaxCounter challenge solution

I can't speak to performance, since I don't know what codility considers acceptable, but I'll give it a go.

In terms of reviewing your code, your solutions seem to be getting more and more compact, but that doesn't necessarily help performance. Shorter code does not  equal faster code. Sure, if you can skip code, that's one thing, but just shaving off bytes of source code is unnecessary.

You certainly should not make confusing constructions like unless ... unless or and next unless. Just read that out loud, and it'll sound strange.

And I don't think there's any advantage to using the self-modifying map!. In fact, there's no reason to use map at all.

And please don't add pointless semi-colons. A nice aspect of Ruby is not having to use those darn things everywhere.

You also seem to misinterpreting how map (with or without the !) works. These are all equivalent:

 counter.map! {|x| x = counter.max}
 counter.map! {|x| counter.max}
 counter.map! {counter.max}

In other words, you setting the block parameter x does absolutely nothing useful - you don't even need the block parameter. The map method(s) only use the block's return value.

Moreover, your block gets invoked n times by map!, since n is the counter-array's length. That means that counter.max gets called n times, even though the result is the same each time! If n is large, you're looking at a lot of unnecessary work being done there. Worst case is at that all of the values in a equal n + 1, in which case you'll be calling counter.max a total of a.count * n times. And given that you're using map!, I doubt Ruby even has a chance to cache/memoize or otherwise optimize the result of counter.max, since you keep changing the array in-place.

Besides, Array provides a lot of help here, if you check the docs.

fill does what it says in the name: Fills the array with a given value (or by using a block), which is what you're trying to do with map!
and Array.new accepts a length and a seed value, so you can fill a brand new array right away. Don't muck around with mapping a range; just make an array of the right length that's filled with zeros.

Here's my take

def solution(n, a)
  counters = Array.new(n, 0) # an array of zeros (and make the var name plural, since it's an array)
  limit = n + 1 # let's just calculate this once, since it's constant

  a.each do |v|
    if v == limit
      counters.fill(counters.max) # max gets called once, and the array gets filled
    elsif v > 0 && v < limit
      counters[v-1] += 1 # just increment
    end
  end

  counters
end

It works for the sample input in Codility's example, but as mentioned I haven't gone beyond that.

Update: With a bit of manual work, you can get rid of the call to max entirely by tracking the maximum yourself:

def solution(n, a)
  counters = Array.new(n, 0)
  limit = n + 1
  maximum = 0 # the maximum counter value

  a.each do |v|
    if v == limit
      counters.fill(maximum) # use our known maximum
    elsif v > 0 && v < limit
      counter = (counters[v-1] += 1) # increment a counter and store the result
      maximum = counter if counter > maximum # use the new value as maximum, if it's higher
    end
  end

  counters
end

This will likely be faster than the first approach, especially for larger values of n. It's maybe not quite as Ruby-esque to do things "manually" like this, but it's not terribly complex either.


You can improve the code for 3 or more columns and at the same time use it for 1 or 2 columns, by using LINQ:

public partial class FlattenedArray
{
    public int rows;
    public int cols;
    public double[] array;
    public void sort()
    {
        array = (from i in Enumerable.Range(0, rows)
                        select new List<double>(array.ToList().GetRange(cols * i, cols)))
                        .OrderBy(x => x[0])
                        .SelectMany(x => x)
                        .ToArray();
    }
}

This divides the array into dimensions and sorts it by the first column then flattens it all back to 1D.  It will work for any combination of rows and columns as long the conditions you mentioned hold true.

If the data size gets very large you still might want to use Array.Sort for the 1 column data as this code wouldn't be very efficient for 1 column.


I don't like while loops without a body. They are hard to read.

while(cin.get() != '\n');

// Even if the body is just a comment.
while(cin.get() != '\n')
{  /* Empty Body */ }

But what you are doing is basically ignoring the current line. It would be easier to do this with ignore()

std::cin.ignore(numeric_limits<streamsize>::max(), '\n');

But now that we have looked at it I don't really think you want to ignore the current line of input. Getting input screwed up (especially when working with interactive user input) is that you are mixing std::getline and operator>>. User input is line based so always read a line of input from the user then parse the input. Then you will not get screwed up by unread end of line markers.

Looping while(true) is dangerous when working with streams. Things have a tendency of becoming infinite. If your stream becomes bad (ie bad bit is set), then you will go into infinite loop. Clearing the bad bit and retrying is unlikely to make it better.

So I would re-write like this:

How about:

int getInt(std::istream& stream)
{
    // Only loop as long as the input is stream is usable.
    // Otherwise you enter an infinite loop.
    while (stream)
    {
        cout << "Enter an int." << endl;

        // Read a line of user input.
        std::string line;
        std::getline(stream, line);

        // Now convert user input to value.
        std::stringstream linestream(line);
        int               value;

        if (!(linestream >> value)) {
            continue;   // The input was not an integer.
        }               // So retry the loop.

        // You got a good value.
        // Do you care if there is stuff on the end of the line?
        // i.e.  If the user entered 56 f<enter> is that bad?
        //       If it is then you check to see if there is more valid input on the line.
        char  x;

        if (linestream >> x) {
            continue;    // There was good input (thus the input was bad).
        }
        return value;
    }
    // If you get here,
    // this means you ran out of input.
    // What do you do?
    // You could return a default value.
    // or throw an exception.
    return 0;

    // The trouble with either of these methods is that its hard to detect
    // the error situation. You need to explicitly check. That is why `operator>>`
    // works well. The stream goes bad when things get out of sync and the natural
    // operations cause the current operation to fail.
}

So an alternative to getInt() would be to extend operator>> for reading a line and getting an integer out of it.

 struct GetInt
 {
     int&  val;
     GetInt(int& v): val(v) {}

     friend std::istream& operator>>(std::istream& str, GetInt& data)
     {
         data.val  = getInt(str);
         return str;
     }
 };

Now you can use your line getting in a normal stream like operation.

 int val;
 if (std::cin >> GetInt(val))
 {
     // We correctly retrieved a value from the user.
 }


C++-safe way to use using inside headers

1. Auto Non-type template parameter

No, not possible, sorry, see this on SO.
I wish it could be done... but no, not in current standard.

2. Complex namespaces and using

It is not causing problems to users of the header, but the question is: who will maintain the code? You? Only you?

If the answer is yes, then it sounds too complex for me. It would be much easier to have one header (e.g. common.hpp) with the usings within one private namespace (e.g. firda::detail in my case) where any implementation will go inside this namespace (e.g firda::detail::something) automatically sharing all the usings specified in one file like a convention (common usage, something anybody needs to read before altering your code).

To be honest, I use such header importing selected features to my global namespace (firda). It is not adviced to use using namespace std and the same apply to my namespace (do not use using namespace firda, I am the only one allowed to do so in my own projects).

You can run into problems after adding usings to that common header, but it is your code and you should be able to manage it.

If the answer is no, than you need some common convention and from my perspective, it is much easier to simply forget about usings (except inside functions/methods). You can use shortcuts (namespace alias) if you really need to (e.g. namespace ns1 = some::complex::namespace::chain) placed usually on top of the header (to be easily found). Writing std::something or ns1::something is not so much typing and explicity is much better for multiple-coworker scenairo.

If you have the convention to place all such usings on top of the header, than it can be found by anybody sharing this convention. So, the idea is not that bad after all, but I would still prefer namespace aliases and std:: prefixes.


DataService that fetches data not loaded already or loads cached values

Short review

  if (this.datas !== null) {
    return of(this.data);
  }

That looks like a bug, should it not be (this.data !== null) ?

Also, what is of, where is it defined?

Other than, the code is very clean in both parts. So clean, that I almost would switch the of and the localStorage call. But since this would dupe the null check, that might in the end not be the best idea.

  if (this.data !== null) {
    return of(this.data);
  } else {
      this.data = JSON.parse(localStorage.getItem('data'));
      if (this.data !== null) {
        return of(this.data);
      }
  }


Before getting into each function, your last question is important -- how do we generalize the type of container? By passing iterators instead of containers, of course! When we first encounter the C++ Standard Library, the ubiquity of iterators can seem confusing -- why not pass containers around instead? The reason is that different programs have many different needs, and passing a particular kind of container can be very restricting. For example, if my function takes a parameter of type const vector<const Foo>&, I cannot pass a const vector<Foo>& or a const vector<const Foo*>&. If instead I take a pair of iterators with the requirement that *it is of type const Foo&, I can use a wider range of container types; vector<Foo>'s and vector<const Foo>'s iterators work directly, and vector<const Foo*> can be made to work with iterator adaptors.

OK, function by function.

1. Simply Remove All Instances of a Value From a Vector

template<class T>
void Vec_RemoveAll(vector<T>& vec, T val)
{
    vec.erase(remove(vec.begin(), vec.end(), val), vec.end());
}

First I'll include my standard disclaimer about using namespace std;: Don't do it, it can lead to subtle bugs, and you'll get used to seeing std:: everywhere.

Second, pass const T&, not T. What if T is a large type? std::remove takes const T&.

Third, I don't think this is a particularly wise function to write. It's a common C++ idiom; once you learn it it should become automatic.

2. Remove All Instances of a Container of Values From a Vector

template<class Container, class T>
void Vec_RemoveAll(vector<T>& vec, const Container& vals)
{
    for (const T& val : vals) vec.erase(remove(vec.begin(), vec.end(), val), vec.end());
}

First point is a question: Is this the performance characteristic you want? Intuitively, I would think that vals would tend to be smaller than vec, so you probably want to iterate through vals in the inner loop, not the outer loop. You could achieve this by using std::remove_if instead and writing a function that determines whether an element is in vals. You could get even better performance if you required vals to be sorted.

Second: for (const T& val : vals) is dangerous. Container isn't required to contains Ts, just things that are comparable to T. You would want to write this as for (const auto& val : vals). For example, consider that vec is a vector<string> and vals is a vector<const char*>. Each of the strings in vals would be copied into a string while iterating using your version.

3. Remove All Elements That Meet Unary Predicate's Condition

template<class T, class UnaryPredicate>
void Vec_RemoveAll_If(vector<T>& vec, UnaryPredicate* predicate)
{
    vec.erase(remove_if(vec.begin(), vec.end(), predicate), vec.end());
}

Almost right, except that you should pass UnaryPredicate, not UnaryPredicate*. Your version works fine for function pointers but not function objects. But I raise the same objection as to function 1 -- this is a standard idiom, and hiding it behind a function call is more likely to confuse than enlighten experience C++ programmers who read your code.

4. Remove Elements That Meet Any of the Predicates' Conditions

template<class T, class UnaryPredicate>
void Vec_RemoveAll_If(vector<T>& vec, const vector<UnaryPredicate> predicates)
{
    for (const UnaryPredicate& predicate : predicates)
        vec.erase(remove_if(vec.begin(), vec.end(), predicate), vec.end());
}

I recommend against writing this function in the first place; it's probably best for any potential user of this function to compose their predicates manually into a single predicate, or in the alternative to write a library to help them do so. That is more generally applicable and removes the requirements that users of your library learn this idiosyncratic API. In the alternative, you can do as you did in function 2, and pass const Container& instead of trying to specify a specific container.


As far as I can tell,

This looks like a pretty solid implementation of blacklisting.
I can't see any obvious code mistakes.

I you are worried about security it can be wise to check the corresponding OWASP documentation

This is for Java, but the security considerations should be similar


Identifying the closest player to an internal 2D grid

You are exactly duplicating the code for checking the distance for player 1 and player 2. You could move that code into a separate getDistanceToCarpet function, and have the getWhoIsCloser function call that twice.
If I understand your code correctly, you seem to be using so-called taxicab distance, meaning the total distance is equal to the X distance plus the Y distance (this is perfectly valid, as long as you're doing it on purpose). This is convenient, because it lets you separately calculate the X and Y distances and then just add them together.
Let's look at just the X distance for now. We can see that if X is on the carpet, the distance is 0. If is is less than xCarpet, it's equal to xCarpet - xPlayer, and if it's more than xCarpet + size the distance is equal to xPlayer - (xCarpet + size).
And hey, we're doing the same exact thing for Y. We could just copy-paste it and replace all the xes with ys, or we could break it out into another function. The copy-paste approach can be error-prone, so I'd recommend more functions.

Put all that together, it might look a little something like this:
public static int singleAxisDistance(int playerCoordinate, int carpetCoordinate, int carpetSize) {
    if (playerCoordinate < carpetCoordinate) {
        return carpetCoordinate - playerCoordinate;
    } else if (playerCoordinate < carpetCoordinate + carpetSize - 1) {
        return 0;
    } else {
        return playerCoordinate - (carpetCoordinate + carpetSize - 1);
    }
}

public static int getDistanceToCarpet(int xPlayer, int yPlayer, int xCarpet, int yCarpet, int sizeCarpet) {
    int xDistance = getSingleAxisDistanceToCarpet(xPlayer, xCarpet, sizeCarpet);
    int yDistance = getSingleAxisDistanceToCarpet(yPlayer, yCarpet, sizeCarpet);

    return xDistance + yDistance;
}

public static int getWhoIsCloser(
      int xFirstPlayer,
      int yFirstPlayer,
      int xSecondPlayer,
      int ySecondPlayer,
      int xCarpet,
      int yCarpet,
      int size) {

    int firstPlayerResult = distanceToCarpet(xFirstPlayer, yFirstPlayer, xCarpet, yCarpet, size);
    int secondPlayerResult = distanceToCarpet(xSecondPlayer, ySecondPlayer, xCarpet, yCarpet, size);

    if (firstPlayerResult > secondPlayerResult) {
        return 2;
    } else if (firstPlayerResult < secondPlayerResult) {
        return 1;
    } else {
        return 0;
    }
}

If I were to look past that function, I might eventually want to bundle the parameters into position and carpet objects, and put the distance calculations in their classes. Passing a single object is usually neater than passing multiple primitive values, and tends to have less of a risk of getting the parameters confused. And while I admit it's a matter of opinion, I do think this looks nicer on some level:
public static int getWhoIsCloser(
      Point firstPlayerPosition,
      Point secondPlayerPosition,
      Carpet carpet) {

    int firstPlayerDistance = firstPlayerPosition.getDistanceTo(carpet);
    int secondPlayerDistance = secondPlayerPosition.getDistanceTo(carpet);

    if (firstPlayerDistance > secondPlayerDistance) {
        return 2;
    } else if (firstPlayerDistance < secondPlayerDistance) {
        return 1;
    } else {
        return 0;
    }
}
```


Checking if a sentence is considered valid

What you have here is a series of boolean-result conditions that you want to apply to a given String.

The design can be expanded to allow List of conditions to be applied.  This way you can add or remove conditions with minumal changes.
You can leverage Java 8 Predicate interface that fits the conditions you want to write.  You can write at least some of the conditions as lambda expressions, saving you the need to write concrete clases

List<Predicate<String>> conditions = new ArrayList<>();
conditions.add((sentence) -> Character.isLetter(sentence.charAt(0))
        && sentence.charAt(0) == sentence.toUpperCase().charAt(0))

  private boolean areConditionsValid(String sentence) {
      return conditions.stream().allMatch(condition -> condition.test(sentence));
  }


I would not hard-code the fee logic, but instead store it as pure data. It's easier to maintain, even allowing to load it from a file.
Then, it boils down to a range-based lookup, which is quite classical (cf HLOOKUP in spreadsheet software, with so called "approximate search").

In Python, we can perform such a search via bisect, relying on lexicographic order (and infinity as an unreachable upper bound).

Separated core logic would look like :

from bisect import bisect

#For each country, list of (x,y) = (cost_threshold, fee)
#For first x such cost <= x, pick y for fee.
inf = float("inf")
shippingFees = { 'USA' :    [ (50, 6), (100, 8),  (150, 10), (inf, 0) ],
                 'CANADA' : [ (50, 8), (100, 10), (150, 12), (inf, 0) ]
               }
#Make sure it is sorted (required for lookup via bisect)
#FIXME : Actually it would be better to assert it is already sorted,
#        since an unsorted input might reveal a typo.
for fee in shippingFees.values() : fee.sort()

def getShippingFee(amount, country):
   fees = shippingFees[country.upper()] #raise KeyError if not found.
   idx = bisect(fees, (amount,) )
   return fees[idx][1]

Update

Here is a sample of "working application" using the helper function, assuming you have saved the code snippet above as prices.py (which should be stored in a module, but that's another story).

NB : I have dropped the exit part, since I don't like to type no when I can hit CTRL+C.

#!/usr/bin/python2
""" Your description here """

from prices import getShippingFee

print('This will calculate shipping cost and your grand total.')

while True:

   #TODO : proper input processing, python3 compatible.
   totalAmount = float(raw_input('Enter your total amount: ').replace(',', '').replace('$', ''))
   country = raw_input('Type "Canada" for Canada and "USA" for USA: ').strip().upper()

   try :  #TODO : proper country check.
      shippingFee = getShippingFee(totalAmount, country)
      grandTotal = totalAmount + shippingFee
      if shippingFee :
         print('Your shipping cost is: %.2f' % shippingFee)
      else :
         print('Your shipping is free!')
      print('Your grand total is: %.2f' % grandTotal)

   except KeyError :
      print ("Sorry, we don't ship to this hostile country : %s" % country)


Get list and default value of columns of table with Eloquent

If I’m fully understanding your need, the best approach would be to set the defaults at the database level. If a record is saved with a null value for that attribute, it will automatically get the default value set at the database level.  The end result is much cleaner code and no extra processing needs during data load as the default is there at rest.

In the migration, for example, $table->string(‘favorite_color’)->default(‘Blue’);  , as described at https://laravel.com/docs/master/migrations#column-modifiers

Would this solve your need? If not, it probably means your need is contextual, and that this default doesn’t always need to apply. Think critically about that context and what it represents. It might indicate a difference in data which might cause further problems down the road.

I hope this helps!


A python default dictionary which seamlessly saves to disk

I think you should rather returns a default value if file exists but key is not found in it.
Opening file every time you want to get or set a value is expensive. Consider reading it in __init__ method, saving the data in handler registered using atexit module and adding a flush() method if for some reason you'd like to dump data right now. You could also add some no_cache option in __init__ to force saving thins right away?
pickle module is potentially insecure. Consider famous example import pickle; pickle.loads("cantigravity\n") If you open a maliciously prepared file with your class a weird things can happen. It should be used for internal used only, not for a general purpose class that can read any input.
What if multiple instances of FileDict will use the same file as source? Consider using tempfile module or generating unique names with uuid module, and then allowing returning generated the name with some method
Following collections.defaultdict example you might want to use a callable to generate a default value. You can always pass lambda: 0 if you want to have only one value returned


This problem has me perplexed. Frankly, I don't believe you ;-) !!!

There is no logical reason for this code to be so different from each other. There must be something else going on.... For a start, the bash process itself is probably taking almost no time at all, and all the time will be spent running the 'install' sub-processes. I imagine that you are running the install processes twice as many times for some reason.... or that, subsequent installs are faster because you don't need to access the disk/net, or something.

Regardless, I don't believe the difference in performance is because of the case vs. if

As a side note, do you need to execute the installs in a sub-shell and capture the results like you do and then echo them? The install lines should all look similar to:

# Relace this: echo $(./install.sh --resourceId=$id --name=httpd)
# with:
./install.sh --resourceId=$id --name=httpd


An overloaded random number function template using modern C++

The constructor of uniform_int_distribution has default arguments:
template<typename T>
explicit uniform_int_distribution(T a = 0,
                                  T b = std::numeric_limits<T>::max());

(I don't know why a defaults to 0 rather than to the minimum T, but there you go).
You can reduce your duplication by using the same default arguments, and passing them through to this constructor:
template <typename T>
T Randolfi(T range_start = 0,
           T range_end = std::numeric_limits<T>::max())
{
    std::uniform_int_distribution<T> dist(range_start, range_end);
    return dist(rng);
}

Or, we can use perfect forwarding to create the distribution with the same arguments as passed in:
template <typename T, typename... Args>
T Randolfi(Args&&... args)
{
    std::uniform_int_distribution<T> dist(std::forward<Args>(args)...);
    return dist(rng);
}

We'll need to do this if we want to support a variety of distributions, so it's probably the way to go.

Don't recreate a random generator every call.  You could make it static, which will reduce that to once per instantiation, but it's better to keep it outside of the function, so you only create and seed it once per process.
In the test program, you should exercise more than one type T, and test with implicit and explicit range.  Also, avoid using namespace std;, and prefer tests which don't require a GUI environment (so they can be more easily run on build servers).

Modified code
#include <limits>
#include <random>
#include <utility>

static auto rng = []{
    std::mt19937 rng;
    rng.seed(std::random_device()());
    return rng;
}();

template <typename T,
          template<typename> typename Distribution
                                      = std::uniform_int_distribution,
          typename... Args>
T Randolfi(Args&&... args)
{
    Distribution<T> dist(std::forward<Args>(args)...);
    return dist(rng);
}

#include <iostream>

int main()
{
    std::clog << Randolfi<int>(-100, +100) << '\n'
              << Randolfi<char>('a', 'z') << '\n'
              << Randolfi<double, std::normal_distribution>(100, 15) << '\n'
              << Randolfi<std::size_t>() << std::endl;
}


Yes it is horrible.

The only time where inheritance over composition makes any sense is when you want to take advantage of the empty baseclass optimization. A container is not a empty class.

In a struct all fields are public so you don't need to public inherit anyway.

None of the methods of the std containers are virtual so you cannot override them. Which in turn means you cannot prevent user code from invalidating any invariants you want to impose. This last is an issue with public member field as well.

If you ever want to change containers to one with a different api you have to change all code dealing with the container part instead of only changing the type in the header and the implementation of the wrapper functions.


When reading through your code I find several things which I would change/remove.

The first is the empty constructor. A class without a constructor and a class with an empty constructor behave the same. I think it creates unnecessary noise in your code, so I would remove it.

Second is the naming of your methods. Since the class name is CookieMonster I find the suffix Cookie in registerCookie(), retrieveCookie() and destroyCookie() unnecessary. You could also name them register(), retrieve() and destroy() which I find more concise.

In your retrieveCookie() method I think there is room for improvement. The language construct empty also checks if the variable/key exists before determining if it evaluates as empty. So you could refactor the method body to the following:

/*
 * I have also renamed the method according to the
 * suggestions above.
 */
public function retrieve($name)
{
    if(!empty($_COOKIE[$name])) {
        return $_COOKIE[$name];
    }
    return false;
}

This is also true for your destroyCookie() method.

Regarding your destroyCookie() method. It doesn't destroy the cookie, but merely unsets the value inside the superglobal $_COOKIE. The cookie would be loaded again on the next request and would therefore never be deleted until it expires. To destroy a cookie you will have to redeclare it with an empty value and an expiration time in the past using the native PHP function setcookie() as you did when setting the cookie in registerCookie(). Unsetting the cookie inside the $_COOKIE superglobal is important too, as this can prevent any further code accessing a to be deleted cookie value. This effectively denies the code the possibility to rely on unpredictable data and helps reduce extremely hard to find bugs.

When destroying a cookie you will also have to make sure it has the same parameters as when set. This includes both the path and domain, When destroying cookies you should also be aware of the timezone complications outlined in this question. An example:

/*
 * Create a timestamp one hour in the past, which is 3600 seconds.
 */
$expire = time() - 3600;

setcookie('mycookie', null, $expire);

/*
 * If a path and/or domain was specified when the cookie was
 * created they too should be included.
 */
setcookie('mycookie', null, $expire, $path, $domain);

Talking about the path and domain leads me to the next part. When creating a cookie with your registerCookie() method I have no way to set a path and/or domain as well as I cannot declare whether the cookie should only be sent over secure connections (SSL etc.) or if it is only restricted to HTTP requests leaving javascript unable to read/update/delete the cookie (this is often preferable when dealing with security).

Therefore I would change the method signature to include this.

/*
 * Renamed according to suggestions.
 */
public function register($name, $value, $expire, $path, $domain, $secure, $httponly) {...

The $path, $domain, $secure and $httponly parameters can usually have default values. See the documentation of setcookie() for more information.

Now when I am able to change these settings I will also require them to be available when destroying the cookie as two of them are required, namely $path and $domain. Therefore you should also change your destroyCookie() method signature.

/*
 * Renamed according to suggestions.
 */
public function destroy($name, $path, $domain) {...

Again these can have default values matching the register() method signature.

Now to the last thing. I cannot see the use of and have never required the possibility to restore a deleted cookie. I would even go as far as sayings its a security issue. Consider the following. Your authentication system destroys the cookie when the user logs out. Then somewhere inside your code the cookie is restored before a response is sent to the client. Now your authentication system has been undermined by one single method call. This cannot be good and you're right!

I would simply remove the method and its related class property and focus on making this a utility class which wraps the cookie functions with reasonable logic. Such logic could be ensuring the cookie $name is in fact a string and that is doesn't contain invalid characters. This is also appropriate for your other methods.

I would urge you to take a look at the Symfony cookie wrapper. They have a dedicated class to this and cookies are set using the setCookie() method in response headers, which you might also find interesting.

I hope this can help guide you, happy coding!


I'll just work through this from the top:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Looks good; we need these.

typedef struct node_s {
    int *array;
    int  size;
    struct node_s *next;
} node_t;

It's usual to use the same structure tag as the typename we're going to use: struct node_t.

If size is the number of elements in the array, a more natural type might be size_t.

node_t* alloc_node()
{
    return (node_t*)malloc(sizeof(node_t));
}

All this does is to allocate the memory.  Consider initialising the members to sane values, too:

node_t* alloc_node()
{
    node_t *n = malloc(sizeof *n);
    if (n) {
        n->array = NULL;
        n->size = 0;
        n->next = NULL;
    }
    return n;
}

We're writing C, so it's not advised to cast the result of malloc().  But we can't assume it succeeds!

It's a good habit to use the assigned-to variable in the argument of sizeof, rather than its type; that saves us the mental work of having to check that the type actually matches.  That's why I've used sizeof *n in place of sizeof (node_t) here; you'll see just following an example where we're further from the declaration and this idiom has more benefit.

It's possibly a good idea to create the array at the same time:

node_t* alloc_node(size_t array_count)
{
    node_t *n = malloc(sizeof *n);
    if (n) {
        n->array = malloc(sizeof *n->array * array_count);
        n->size = n->array ? array_count : 0;
        n->next = NULL;
    }
    return n;
}

void free_node(node_t *node)
{
    free(node);
}

Assuming that the node owns its array, we need to free that, too:

void free_node(node_t *node)
{
    if (node) {
        free(node->array);
    }
    free(node);
}

Does the node own its next as well?  If so, we need to free that, or perhaps return it.

#define SIZE 3

Why is this in the middle here?  It should be right at the beginning (or perhaps just before main()).

void print_one(int *one)
{
    printf("%d ", *one);
}

I'm not convinced there's much benefit to encapsulating this as a function.

void print_1d_array(int *array, int size)
{
    for(int i = 0; i < size; i++) {
        print_one(&array[i]);
    }
    printf("\n");
}

We should use size_t for the count here:

void print_1d_array(int *array, size_t size)
{
    for (size_t i = 0;  i < size;  ++i) {
        printf("%d ", array[i]);
    }
    printf("\n");
}

void print_2d_array(int **array, int *col_sizes, int size)
{
    for (int i = 0; i < size; i++) {
        print_1d_array(array[i], col_sizes[i]);
    }
}

Another size_t (okay, I'll stop mentioning these now).

int** create_solution_array(node_t *head, int ans_size, int **column_sizes)
{
    int **ans = (int**)malloc(sizeof(int*)*ans_size);

    node_t *iter;
    iter = head->next;
    int idx = 0;
    while(iter) {
        ans[idx] = iter->array;
        (*column_sizes)[idx] = iter->size;
        idx++;
        iter = iter->next;
    }
    return ans;
}

Aside from points from earlier, that while loop has an initialisation and an advancement, so it's really a for loop:

int** create_solution_array(node_t *head, size_t ans_size, size_t **column_sizes)
{
    int **ans = malloc(sizeof *ans * ans_size);

    if (ans) {
        int idx = 0;
        for (node_t *iter = head->next;  iter;  iter = iter->next) {
            ans[idx] = iter->array;
            (*column_sizes)[idx] = iter->size;
            ++idx;
        }
    }
    return ans;
}

void gen_powerset(int *num, int num_size, int idx, int cur_size, int *cur, node_t **iter_node, int *ans_size) {
    if (idx == num_size) {
        node_t *new_node = alloc_node();
        if (cur_size) {
            new_node->array = (int *) malloc(sizeof(int) * cur_size);
            new_node->size = cur_size ;
            memcpy(new_node->array, cur, cur_size*sizeof(int));
        }
        (*iter_node)->next = new_node;
        *iter_node = new_node;
        (*ans_size)++;
        return;
    }

    gen_powerset(num, num_size, idx + 1, cur_size, cur, iter_node, ans_size);
    *(cur + cur_size) = num[idx];
    gen_powerset(num, num_size, idx + 1, cur_size + 1, cur, iter_node, ans_size);
}

*(cur + cur_size) is normally written cur[cur_size].

We need to check whether our allocations succeeded:

/* true if successful, false on any error (e.g. out of memory) */
bool gen_powerset(int *num, size_t num_size, size_t idx,
                  size_t cur_size, int *cur, node_t **iter_node,
                  size_t *ans_size)
{
    if (idx == num_size) {
        node_t *new_node = alloc_node(cur_size);
        if (!new_node || new_node->size != cur_size) {
            return false;
        }
        if (cur_size) {
            memcpy(new_node->array, cur, sizeof *cur * cur_size);
        }
        (*iter_node)->next = new_node;
        *iter_node = new_node;
        ++*ans_size;
        return true;
    }

    cur[cur_size] = num[idx];

    return gen_powerset(num, num_size, idx + 1, cur_size, cur, iter_node, ans_size)
        && gen_powerset(num, num_size, idx + 1, cur_size + 1, cur, iter_node, ans_size);
}

int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {
    node_t  *head = alloc_node();
    node_t  *iter = head;
    int     *cur = (int*)malloc(sizeof(int)*numsSize);
    gen_powerset(nums, numsSize, 0, 0, cur, &iter, returnSize);
    return create_solution_array(head, *returnSize, columnSizes);
}

Again, check that malloc() succeeded, and check that gen_powerset() succeeded.

int main ()
{
    int *nums = (int*)malloc(sizeof(int)*SIZE);
    for (int i = 0; i < SIZE; i++) {
        nums[i] = i+1;
    }
    int *col_sizes = (int*)malloc(sizeof(int)*SIZE);
    int ans_size;
    int ** ans = subsets(nums, SIZE, &col_sizes, &ans_size);
    print_2d_array(ans, col_sizes, ans_size);
    return 0;
}

Having carefully created free_node(), we completely forgot to use it.  Valgrind reveals a substantial leak due to this.  We need to free the other allocated memory, too.


Comma Code (Python) (Automate The Boring Stuff)

Don't surround sub-predicates or predicates with parens when that isn't needed
Use logical and rather than binary &
Use join rather than a for-and-concatenate
Factor out common sub-predicates for your list emptiness checks into an outer if
Don't else-after-break
No need to continue
Gather your input in a separate function
Do not leave the input prompt blank

Suggested:
def and_add(alist):
    if len(alist) > 1:
        print(', '.join(alist[:-1]), 'and', alist[-1])
    elif len(alist) == 1:
        print(alist[0])
    else:
        print('')

def get_input():
    while True:
        item = input('Enter an item or nothing: ')
        if not item:
            return
        yield item

and_add(list(get_input()))


Portability

Your first loop immediately subtracts 4 from a cell whose value is 0.  It seems like your program is designed to run using the wraparound dialect of Brainfuck, so it would be a good idea to note that in a comment.  On the other hand, writing a Fibonacci sequence generator using the 8-bit dialect isn't that useful, because you would overflow after 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233.

However, I'm puzzled by why you would want to do any subtraction at all.  After all, the Fibonacci sequence involves addition, not subtraction.

Readability

There's no need to cram everything on one line.  Best practice would be to insert line breaks after . commands and use indentation to show off the loop structure.  Add some spaces as well, to let your code breathe.

Suggested solution

++++++++++ [->
   +++>+++++++>++++++++++>+++++++++++>++++++++++++ <<<<<
]
>> +++ .
< ++ .
>>> ++ .
< +++++  .
> ++++ .
> + .
<<<< .
>>> .
< - .
--- .
<< .
>> + .
> ----- .
.
--- .
<<< + .


Keeping data processing out of controllers

Your brace style is inconsistent. Allman style is usually applied in C#.

public class AppUser{
    // snipped
}

public class AddressDetails
{
    // snipped
}

Longtitude is a spelling error, it should be Longitude.

Underscores are usually only used for fields; properties should be PascalCase:

  protected AppDB _db { get; set; }
  protected AppUser _currentUser { get; set; }

Don't abbreviate unnecessarily: I don't know what Rep is, I do know what Repository is.

public class EmployeeRep : UserRep

Is this a field or a property:

private EmployeeRep _employeeRep { get; set; }

The { get; set; } says "property", but the private and the underscore at the start of the name says "field".

Avoid "negative checks" like you do here:

_employeeRep = (User.Identity.GetUserId() != null)
    ? new EmployeeRep(User.Identity.GetUserId())
    : null;

Invert that logic and things become a lot clearer:

_employeeRep = (User.Identity.GetUserId() == null)
    ? null
    : new EmployeeRep(User.Identity.GetUserId());

Also, since you call User.Identity.GetUserId() twice, consider calling it once, storing the result in a variable and then using that variable.


It'd be easier to separate this into two parts. First, we can do all the word transformations using map and a single word switcher:

(define (switch-word word)
  (cond ((equal? word 'I) 'you)
        ((equal? word 'me) 'you)
        ((equal? word 'Me) 'you)
        ((equal? word 'you) 'me)
        ((equal? word 'You) 'me)
        (else word)))

(define (switch sentence)
    (map switch-word sentence))'

That handles all the word swapping in one go, without having to write the iteration code yourself.

Now all we need to do is change the first word from me to I, if appropriate:

(define (me-to-I word)
    (if (equal? word 'me) 'I word))

(define (switch sentence)
    (let ((switched (map switch-word sentence)))
        (cons (me-to-I (car switched)) (cdr switched))))


It was more or less worked out in the comments that the use of reflection is a fine way to go about it and I agree with that. What I can't understand is your use of regions. In IMvcRouteExtender you have one that wraps a single method. In my opinion, it just clutters the code. In your implementation, you have a #region IMvcRouteExtender. This is a little stickier. I could definitely see a benefit to this if your class was implementing multiple interfaces and you had a region for each interface, but I would remove it for the code here. Clutter like this distracts us from the code.

Some of your instructions also get kind of long. I'd shorten then up a bit with a few line breaks.

/// <summary>
///     Registers the routes.
/// </summary>
/// <param name="routes">The <see cref="RouteCollection" /> to which the routes will be added.</param>
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Get all the types in the references assembly that implement the 'IMvcRouteExtender' interface.
    var types = AppDomain.CurrentDomain.GetAssemblies()
                .ToList()
                .SelectMany(a => a.GetTypes())
                .Where(t => typeof(IMvcRouteExtender).IsAssignableFrom(t) && !t.IsInterface);

    // Register all the routes.
    types.Select(type => Activator.CreateInstance(type) as IMvcRouteExtender)
                .Each(x => x.RegisterRoutes(routes));

    // All the required routes are placed here.
    routes.MapRoute(
            "Website",
            "{controller}/{action}/{id}",
            new
            {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional
            });
}

It's certainly not ideal still, but I prefer vertical scroll to horizontal scroll. It lets us see what the method is doing "all at once".


Thread spawning child threads and waiting for children to finish

Instead of creating threads use an ExecutorService and use invokeAll(Collection<Callable>, long, timeUnit). This will return when all calls are done or the timeout expires whichever happens first. Tasks that aren't completed will be canceled (which can be checked by the isCanceled() property of the matching Future in the return value).

This will mean you will need to change the Runnables to Callables but that just means returning null in the call method.


If you don't want to handle an error, then ignore it by using the _ symbol.
I.E. replace:

file, err := os.Open("./phonenumbers.txt")
check(err)

with:

file, _ := os.Open("./phonenumbers.txt")

Move the entire scanning logic into a separate function (you did write you are fond of functional programming ).
func PrettifyNumber(original string) string
You could use the strings.Fields to filter out any non numeric character.

func IsNotADigit(r rune) bool {
    return !unicode.IsDigit(r)
}

func PrettifyNumber(original string) string {
    return strings.Join(strings.FieldsFunc(original, IsNotADigit), " ")
}


Mad Libs using recursive IO for user input

Can we make getAnswer simpler or out of IO? Well, not really. You want to ask the use a question, and you want to get an answer. So all we could do is to reduce the amount of unnecessary code:

getAnswer :: String -> IO String
getAnswer question = putStrLn question >> getLine
-- or
--                 = do
--      putStrLn question
--      getLine

However, getAnswers can be refactored quite heavily. First of all, its interface isn't really developer-friendly. What are the questions? What are the answers? We should probably hide that in the bowels of our function:

getAnswers :: [String] -> IO [String]
getAnswers xs = go xs []
  where go [] ys = return ys
        go (x:xs) ys = do
          answer <- getAnswer x
          let answers = ys ++ [answer]
          go xs answers

But ++ [...] isn't really best-practice. Instead, you would ask all other questions and then combine them:

  where go [] = return []
        go (x:xs) = do
          answer <- getAnswer x
          otherAnswers <- getAnswers x
          return (answer : otherAnswers)

But at that point, we're merily copying mapM's functionailty. Therefore, your getAnswers should be

getAnswers :: [String] -> IO [String]
getAnswers = mapM getAnswer

A lot simpler.

Now for your main. If you don't know how many words you'll get you will need a list, correct. But lets check the structure of your result:

 "Your %s is %s up a %s mountain %s."
       1     2       3           4

There is a pattern. We have our text, then whatever the user gave us, then again our text, and so on. Let's split that into fragments:

["Your ","%s"," is ","%s"," up a ","%s"," mountain ","%s","."]
--       ^^^^        ^^^^          ^^^^              ^^^^

This brings up the following idea: if you have a list of your answers, you only need the list of the other words, right?

["Your "," is "," up a "," mountain ","."]

And then we need to "zip" that list with yours:

interleave :: [a] -> [a] -> [a]
interleave (x:xs) (y:ys) = x : y : interleave xs ys
interleave xs     _      = xs

We end up with the following main:

main = do
    let questions = ["Enter a noun:", "Enter a verb:", "Enter an adjective:", "Enter an adverb:"]
    let madlib = ["Your "," is "," up a "," mountain ","."]
    answers <- getAnswers questions

    putStrLn $ interleave madlib questions

Here's all the code at once:

getAnswer :: String -> IO String
getAnswer q = putStrLn q >> getLine

getAnswers :: [String] -> IO [String]
getAnswers = mapM getAnswer

interleave :: [a] -> [a] -> [a]
interleave (x:xs) (y:ys) = x : y : interleave xs ys
interleave xs     _      = xs

main :: IO ()
main = do
    let questions = ["Enter a noun:", "Enter a verb:", "Enter an adjective:", "Enter an adverb:"]
    let madlib = ["Your "," is "," up a "," mountain ","."]
    answers <- getAnswers questions

    putStrLn $ interleave madlib questions

Exercises

The interleave function above is left-biased. Why? Could this pose problems for your program? Why not?


Why not name them both the same? The difference is the type of parameter you're passing. This leaves you free to do some method overloading:

public SubscriptionsViewModel GetSubscriptionsViewModel(Guid id)
{
    //GET Logic here...
}

public SubscriptionsViewModel GetSubscriptionsViewModel(SubscriptionsViewModel viewModel)
{
    //POST Logic here...
}

Why call them the same? They both do the same: return a SubscriptionsViewModel.


reorder_buf() is horribly inefficient, and it's unnecessary if you use the buffer as a circular-list.  What you want is called a ring buffer.

/* Store up to 10 characters */
#define BUFSIZE 11

char buf[BUFSIZE];
int qhead = 0, qtail = 0;

int getch(void) {
    if (qhead != qtail) {
        int c = buf[qhead];
        qhead = (qhead + 1) % BUFSIZE;
        return c;
    } else {
        return getchar();
    }
}

void ungetch(int c) {
    if ((qtail + 1) % BUFSIZE == qhead) {
        fprintf(stderr, "Buffer full, dropped %c.\n", c);
    } else {
        buf[qtail] = c;
        qtail = (qtail + 1) % BUFSIZE;
    }
}

Errors should go to stderr rather than stdout.


Selecting random class from weighted class probability distribution

Using dictionaries is faster than lists. Your distributions can serve as keys to find the corresponding values instead of using indexed lists.


Remove repetitive strings from a given sentence efficiently

Here's my shot at this puzzle.

Benchmark of original code, over 1,000,000 iterations (with print() commented out):

  real    1m8.486s
  user    0m0.000s
  sys     0m0.000s

Benchmark of my code, over 1,000,000 iterations (with print() commented out):

  real    0m16.226s
  user    0m0.000s
  sys     0m0.015s

Performance gain: 422.07%

It looks like you want to preserve the string order and uppercase/lowercase, so I took that into account. Otherwise this could be even faster/shorter.

The strategy here is to preprocess the strings, instead of going through strip(), lower(), and split() each time you need to do a comparison.
Additionally, sort the strings by length, so you only perform comparisons you need to perform. See comments for more details.

WATSON_RAW = 'watson  Represents|watson represents|Watson represents a first step into cognitive systems, a new era of computing.|first step into  Cognitive|Cognitive Systems; a new era|what does watson represent'

# 1. Preprocess the string.
#    Remove extraneous whitespace, replace semicolon with comma.
modified = ' '.join(WATSON_RAW.split())
modified = modified.replace(';', ',')

# 2. Split string by delimiter.
split = modified.split('|')

# 3. Generate string metadata, sorted by length
#    Keep track of the string contents, its index in the "split" variable, and its length.
#    Tuple has a speed advantage over list.
metadata = [(i, len(s), s.lower()) for i, s in enumerate(split)]
metadata = sorted(metadata, key=lambda x: x[1])

# 4. Uniqify the strings.
indexes_of_unique_strings = []

for index, _, string_lowercase1 in metadata:
    # Only search from current index on, skipping comparisions with earlier indexes.
    for _, _, string_lowercase2 in metadata[i:]:
        if string_lowercase1 in string_lowercase2 and string_lowercase1 != string_lowercase2:
            # This string is redundant.
            break
    else:
        # This string is unique.
        indexes_of_unique_strings.append(index)

# 5. Map indexes back to original, correctly capitalized strings, in original order.
indexes_of_unique_strings = sorted(indexes_of_unique_strings)
final = '|'.join(split[i] for i in indexes_of_unique_strings)

print(final)


Analyze terraform template files to return infrastructure cost

Usually, the code is a bit worse, indentation-wise:

if res, ok := decodedOutput["resource"].([]map[string]interface{}); ok {
    for _, resource := range res {
        for key := range resource {
            switch key {
            case "aws_instance":
                if rk, ok := resource[key].([]map[string]interface{}); ok {
                    for resourceKey := range rk[0] {
                        if itype, ok := resourceKeys[0][resourceKey].([]map[string]interface{}); ok {
                            if d, ok := itype[0]["instance_type"].(string); ok {
                                masterResourceMap = countResource(masterResourceMap, key, d)
                            }
                        }
                    }
                }

            default:
                fmt.Println("resource type not recognized: ", key)
            }
        }
    }
}

Now, from a Terraform point-of-view, you already have a semi-assurance that the type you're trying to cast has been cleaned up, this due to how you declare the values of the terraform file. You usually define it with the schema package, so while it's running, you know Terraform already checked the types for you.

The overall I've seen is that providers, for example, do not tests against a true type casting from interfaces, again, due to Terraform pre-checking the information to match the schema definition, so if it is a string but someone passed an int, then Terraform will exit and fail way earlier than reaching your type casting.


How to make this ping test with timer more efficient?

Using Application.OnTime is a very neat way of implementing your timer, but I have a hard time figuring out how "pings servers every 15 mins or so" translates to Now + TimeValue("00:00:01"). Note that since VBA is single-threaded, OnTime doesn't mean your code will run at that specific time, rather that when Excel isn't busy doing something else, it will queue your method for synchronous execution, like any other event handler code.

That said, your naming and access modifiers lack consistency (I guess that's what you meant with "duct-taped"?).

Observations

You're using ListObject.ListRows.Count, but you're puzzling your way into adding a new row - why aren't you using ListObject.ListRows.Add() which returns the added row?
In sPing function (awful name), I would refactor this ElseIf construct into some Private Function GetPingResult(StatusCode As Long) As String, and assign the function's return value once; also you made the default value "Alive" - if there's an error code you haven't accounted for, your function returns "Alive" which is possibly wrong.

Nitpicks

This is VBA - stick to PascalCasing for all identifiers. It will make your code read consistently with the language itself.
The default access modifier for Sub and Function is Public - thus, either specify it or leave it out, but don't do both. If the unspecified ones are supposed to be Private, be explicit about it.
The language's convention for underscores in procedure names, is only for methods that implement interface methods (e.g. event handlers). Avoid it.
Worse than Hungarian notation (strTableName As String), is inconsistent Hungarian notation, especially in the same method signature (why isn't it iCol As Integer then?). Avoid it (Hungarian notation, that is!).

I know this is an incomplete review, but I think you have enough meat here anyway.


This is good Perl code.  You've followed good practices such as use strict and declaring variables using my.  It's also quite readable.

However, it feels a bit like C, trudging along with a lot of iteration and low-level operations.  Also, I would suggest defining subroutines such as caesar and shifts.

A typical way to implement a Caesar cipher using Perl is with the tr operator.  Unfortunately, since the amount of shifting is to be determined at runtime, you would have to use a nasty eval.

my $uc_in = join '', ('A'..'Z');
my $lc_in = join '', ('a'..'z');
sub caesar {
    my ($shift, $text) = @_;
    my $uc_out = substr((join '', ('A'..'Z', 'A'..'Z')), $shift, 26);
    my $lc_out = substr((join '', ('a'..'z', 'a'..'z')), $shift, 26);
    eval "\$text =~ tr/$uc_in$lc_in/$uc_out$lc_out/r";
}

An alternative implementation, closer to your original idea but avoiding splitting and iterating, is to perform a substitution using s///eg.

sub caesar {
    my ($shift, $text) = @_;
    $text =~ s{([A-Z])|([a-z])}
              { chr($1 && (ord($1) <= ord('Z') - $shift) ? ord($1) + $shift :
                    $2 && (ord($2) <= ord('z') - $shift) ? ord($2) + $shift :
                    $1 ? ord($1) + $shift - (ord('Z') - ord('A') + 1) :
                         ord($2) + $shift - (ord('z') - ord('a') + 1)
                   )
              }eg;
    return $text;
}

To parse the shifts, I would prefer a more functional approach, building the list using map instead of appending results within a for loop.

sub shifts {
    my ($arg) = @_;
    return map {
        my ($low, $high) = split /-/, $_, 2;
        if ($low < 0 || $high > 25 || defined $high && $low >= $high) {
            warn "Invalid shift size: $_";
        }
        defined $high ? ($low .. $high) : $low;
    } (split /,/, $arg);
}

With the difficult stuff out of the way, the main program would be something like

# print "…\n" is annoying.  Use say() if you have a newer Perl.
use v5.10;
use feature qw(say);

die 'usage: caesar <string> [shifts,...]' unless @ARGV;

my @shifts = defined $ARGV[1] ? shifts($ARGV[1]) : (13);
for my $shift (@shifts) {
    say caesar($shift, $ARGV[0]);
}


Asks the user for an input, stores and prints it to the console c#

You sure can, you can use something even smaller such as:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Please input something");
            Console.WriteLine("Your input: \n{0}", Console.ReadLine());
            Console.ReadLine(); //stops the console from closing
        }
    }
}


App for allowing the user to type in chemistry formulas using a custom keyboard

You can use some if else statement, where u use several independent ifs. This will lead to a slightly faster code, because in the case, where the previous if is try, no further testing is needed. Personally I also find it more readable for short and medium sized code block.

if (![currentElement isEqualToString:lastElementPressed])  {
    //…
} else {
    if (consecutiveElementCount == 1) {
         //…
    } else if (consecutiveElementCount > 1) {
        //…
    }
    if (consecutiveElementCount < 11) {
        //…
    }
}

But beside that, I don't think, that you are using to many if-statements. But you should use proper indention, as it will build visual block of your code and helps you, to understand the structure.

There is a rule of thumb: If a method/function does not fit on your screen, it becomes to long, and you should use well-named helper functions to break it into several logical blocks.


Script to check zero crossings to check if microphones phases are aligned

This is more of a usability thing than a code thing, but I'd suggest making the non-optional arguments positional so the user doesn't need to type the flags out.
A simple way to put two items into a list is files = [file1, file2].
You can also build sampling_rates and signals via list comprehension.
Since you're explicitly only ever handling two files, building a loop to handle the second thru last files is unnecessary and confusing.
Don't assign a value to a variable if you're going to overwrite it with something else before using it -- again, it's just adding lines of code that do nothing but make it harder to read the script (and use up an infinitesimal amount of processing power).  Combined with (4) above, you have two loops that take seven lines of code to do what's really a single simple equality comparison.
The rest of the script (everything starting at zccs) is hard to understand, but I attempted to condense some of the more magical logic into a function and use list comprehension instead of long loops; better variable names and/or type declarations (normally I'd add those as part of code review suggestions, but I'm not familiar with any of these libraries) would help someone who's not familiar with this particular domain be able to read the script and figure out what it's doing.  Here's what I ended up with after making the above edits:

from scipy.io import wavfile
import numpy as np
from argparse import ArgumentParser

parser = ArgumentParser(description='diff the zero crossing of two files')
parser.add_argument('files', nargs=2, metavar='file',
                    help='one of the files to diff')
parser.add_argument('-p', '--precision', type=float, default=0.0001,
                    help='precision to compare against')

args = parser.parse_args()

# Read data from wav files, scale signals by the max in each file.
sampling_rates, data = zip(*[wavfile.read(file) for file in args.files])
signals = [signal / max(abs(signal)) for signal in data]

# check we didn't somehow bungle the signal normalization math
assert all([min(signal) >= -1 and max(signal) <= 1 for signal in signals])

# files should have same sampling rates and signal length
assert sampling_rates[0] == sampling_rates[1], "rates don't match"
assert len(signals[0]) == len(signals[1]), "signal lengths don't match"

samples_per_ms = int(sampling_rates[1] / 1000)

def zcc(signal):
    """magic!!! (todo: write better docstring)"""
    norm_signal = signal - np.mean(signal)
    return [
      i * 0.001 / samples_per_ms  # is this right?  i is the index!
      if norm_signal[i] * norm_signal[i-1] < 0
      for i in range(1, len(norm_signal))
    ]

for a, b in zip(*[zcc(signal) for signal in signals]):
  if len(a) != len(b):
    print("length doesn't match %d %d"% (len(a), len(b)))
    for c, d in zip(a, b):
      if c - d > args.precision:
        print("precision %f c %f d %f exceeded"% (args.precision, c, d))
        exit(0)


1) Loading HTML this way will exclude all your users with js disabled from browsing your site, that's why back-end scripting exists
2) They are not a problem if you inject them in a valid HTML document. If you don't, the majority of modern browsers will create html, head and body elements by themselves, but all the other browsers will possibly display nothing
3) Theoretically not


File reader and streamer component running in its own thread on Android

One synchronise to much :

@Override
public synchronized void disconnect() {
    running = false;
}

You are declaring this synchronised.  So if 2 threads are calling this method, the second one has to wait until the first one is finished.
Because you don't have an input variable, the output will always be the same, setting running false. In this case there are no race conditions what could affect the outcome of this method, so I wouldn't make it synchronised.

private static final :

You are making a great use of the private static final fields.
What I'm not liking is the next step :

String mockFilePath = SAMPLES_SUBDIR + "/" + filename;

Why don't you put the "/" also in the SAMPLES_SUBDIR?

It's the only place where you use this field so it could be easily in the SAMPLES_SUBDIR.

Comments :

While I'm not the first to say you have to document your code, the following case is for me strange :

@Override
public void sendAsciiMessage(CharSequence chars) {
    // do nothing
}

You can do 2 things here.

Throwing a UnsupportedOperationException so the next developer knows, this method you need to override is not supported here.
Putting more comment then do nothing, why doesn't this has to do nothing?  When I read that in a project that I have to take over, I'm thinking maybe TODO but why didn't he put TODO?  So I'll be searching for the why and loosing maybe valuable time over a stupid issue.

All over :

Nice readable code, as an outstander, who doesn't know the things the other classes need to do I still understand what this class has to do.


Replacing every letter in a string with the letter following it in the alphabet

First, I'll note that str.charAt(n).charCodeAt(0) is better written as str.charCodeAt(n).

Strings are immutable, so it's better to work on array elements than to build them by character-by-character concatenation.

function transform(text) {
    var s = text.split('');
    for (var i = 0; i < s.length; i++) {
        // Caesar cipher
        switch(s[i]) {
          case ' ':
            break;
          case 'z':
            s[i] = 'a';
            break;
          case 'Z':     // One case you forgot to handle
            s[i] = 'A';
            break;
          default:
            s[i] = String.fromCharCode(1 + s[i].charCodeAt(0));
        }

        // Upper-case vowels
        switch(s[i]) {
          case 'a': case 'e': case 'i': case 'o': case 'u':
            s[i] = s[i].toUpperCase();
        }
    }
    return s.join('');
}

Edit note: My original answer had the for-loop written as for (var i in s) { ... }.  As pointed out by @EliasVanOotegem, that is more suited for iterating over object properties than array elements.  As suggested by @plalx and confirmed with jsperf, changing it to for (var i = 0; i < s.length; i++) { ... } makes it much faster.  I have therefore amended my response, changing for (var i in s) to for (var i = 0; i < s.length; i++).

Note that your solution and the solution above blindly increments every character except spaces.  If you want to increment just letters, then a replace operation would be more appropriate:

function transform(text) {
    var caesar = text.replace(/[a-z]/gi, function(c) {
        switch (c) {
          case 'z': return 'a';
          case 'Z': return 'A';
          default:  return String.fromCharCode(1 + c.charCodeAt(0));
        }
    });
    return caesar.replace(/[aeiou]+/g, function(vowel) {
        return vowel.toUpperCase();
    });
}

You could cheat on the Caesar cipher, mapping both z and Z to an uppercase A, since you know that vowels will need to be uppercased.

Addendum: Follow-Up Q&A

@Nathan asks in the comments…

  1) I keep reading that strings are immutable and I guess this means that in my code, I'm not really concatenating, I'm replacing. I take it this is bad but I'm not sure why. I understand how your array works, just not why it is better.

If a and b are strings, when you do var c = a + b, then it creates a new string for the result (allocates memory for the length of a and b, then copies the contents of a, followed by the contents of b).  If you iteratively do a concatenation for each character in a string, that works out to be O(n^2), where n is the length of the input.

In contrast, operating on an array of characters lets you modify the elements in place.

  2) Both your solutions were functions. Is this so that they can be reused? The code is more self-contained and complete?

Even if you call the code just once, putting it in a function is beneficial, because it…
- lets you give your code a name.  Naming is important because it describes the purpose of the code.  Good naming is a form of self-documentation.  Awkward naming is a sign of muddled thinking.
- compartmentalizes the code into small, understandable chunks.  In JavaScript, variables can be scoped by function; without functions, all variables would be in the global scope, and assigning to a global variable can have side effects anywhere in your code.

Admittedly, transform(text) is not a very descriptive name, the way caesarCipher(text) is.  However, the problem was a bit weird and artificial to begin with.  Anyway, it's worthwhile to make it a function, to separate it from the prompting and outputting code.  (Someday you might choose to use the same text transformation, but taking the text from an HTML <input> field and outputting the result to a <span>.

  3) How does the function get it's argument (c)?

That's how the String.replace() function behaves.  If you pass a function as the second argument to replace(), then for every match, that function will be called with the matched substring as its first parameter.


Consider

<?php
    foreach ($taskData as $key => $value) {
        $class = ($value['status']) ? 'check-' : '';
        $trClass = ($value['status'] == 1) ? ' class="checkedTR"' : '';
        echo <<<EOHTML

  {$value['task']}

EOHTML;
    }
?>

I prefer the long versions of tags.  So no <? or <=.  It may not matter as much now, but it used to be that some sites would turn off the short versions.  So software could suddenly stop working for no apparent reason.

I prefer to use single quotes in PHP unless I have to use double quotes, e.g. for variable interpolation.  This way I can see at a glance that a string is not using variable interpolation.

If I'm working with a block of lines in PHP, I prefer to use Heredocs and Nowdocs.  I prefer Nowdoc, but it won't work here.  We need the variable interpolation.  The original code will put the entire thing on one line.  This version will display it more like it looks here.

I prefer to use double quotes in HTML.  No particular reason except that it looks better to me.

I prefer to avoid the $tasks[uid] syntax.  Outside of a string, it's wrong and unreliable.  Inside of a string it's reliable, but it can be misleading.  People see it working inside of a string and don't know why the behavior is special.  Also, if people copy something like $tasks[FIELD] into a string, it may not be obvious why it doesn't work the same way inside a string as outside.  Always using the curly braces is clearer in my opinion.

In this case, I would pick the Javascript quoting to avoid escaping, i.e. single quotes.

Your HTML indentation is inconsistent.  Sometimes two spaces and sometimes four.

You lost a closing 	 in the refactor.


Bootstrap WordPress Carousel Recent Posts

I haven't ran (don't have a WordPress installation handy) or debugged the code, but this should work. Your original code is buggy in a number of ways. The $posts variable is clobbered when you use it as the iterating variable in the foreach loop, which is probably why your code wasn't working as expected.

Most Recent Post

<?php
  // Use a variable instead of magic number. Consider moving this to a WordPress config instead using get_option
  $chunk_size = 4;
  $args = array(
    'post_type'         => 'post',
    'posts_per_page'    => -1,
    'orderby'           => "date",
    'order'             => "desc"
  );
  $posts = get_posts( $args );
?>

    <?php // Use a for loop here instead of foreach, since you don't actually need the contents of the array ?>
    <?php for ($i = 0, $l = ceil(count($posts) / $chunk_size); $i < $l; $i++):  ?>
      <li data-target="#recent-post-carousel" data-slide-to="<?php echo $i ?>" <?php echo ($i === 0 ? 'class="active"' : '') ?>>

    <?php endfor; ?>

  <?php foreach (array_chunk($posts, $chunk_size) as $i => $chunk) :  ?>
    <div class="item <?php if ($i === 0){echo 'active';}?>">

        <?php foreach( $chunk as $p => $post ): setup_postdata($post); ?>

                <?php // href here should probably be the_permalink() ?>

                  <?php the_post_thumbnail( 'full' );  ?>

                <?php // Post date shouldn't be hard coded ?>

03 Dec 2014

<?php echo $i*$chunk_size + $p?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
                    <?php the_title(); ?>

                <?php // Post author shouldn't be hard coded ?>
                John doe
                <?php // Consider using wp_trim_excerpt() instead ?>

<?php echo substr(get_the_excerpt(), 0, 99).' [...]'; ?>

        <?php endforeach; ?>

  <?php endforeach; ?>

A few things to note here:

Use foreach( $array as $i => $element) instead of keeping track of $i separately.
Post count is calculated using $i*$chunk_size + $p
Your HTML was buggy in a few places. I cleaned it up, and left comments in the places where there are probably bugs
Format your code properly to make it more readable
Consider using short tags <?= ?> to replace <?php echo ?> to improve readability
Try to use WordPress functions instead of rolling your own. That way plugins can also hook into them


Reading data with different but similar semantics

As with all performance related questions, if and only if you can gather profiling evidence that shows that your current code is meaningfully detrimental to performance, don't call the first method in the second one, but rather repeat the code. This goes slightly against DRY (just barely, considering the very short code), but you will have to weigh the value of maintainability vs that of whatever performance gain is achieved.

In practice, I suspect that the effect on performance will be negligible if not non-existent. It's not as if you're not calling a slew of other methods and properties anyways.

The key point is profile profile profile.


Iteration and memcache for selected categorized random elements

Regarding image caching, this seems relevant.

Secondly, DRY this code up, it'll make your code more maintainable:

fileinfos = FileInfo.all().filter("category =", "eyes")
fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
url = images.get_serving_url(str(fileinfo.blob.key()), size=420)

Should have it's own function (forgive my py):

def get_random_image_url(category)
    fileinfos = FileInfo.all().filter("category =", category)
    fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
    return images.get_serving_url(str(fileinfo.blob.key()), size=420)

eyes_url = get_random_image_url("eyes")
nose_url = get_random_image_url("nose")
mouth_url = get_random_image_url("mouth")


I'm focusing on the various naming issues.

Why _nSteps? Why not simply _steps? Same for rnd instead of random, lb instead of labyrinth. The General Naming Conventions say:

  In general, you should not use abbreviations or acronyms. These make
  your names less readable.

What kind of name is _1d_labyrinth for a namespace? The General Naming Conventions say:

  Do not use underscores, hyphens, or any other nonalphanumeric
  characters.

Also, a namespace's name should be PascalCase, so in this case OneDimensionalLabyrinth.

Why Solver1? Is there also a Solver2 and a Solver3 etc? What are their differences? Base your class name on the particulars of your class.


Calculating min and max with if-statements within a for-loop

The code violates Tell, Don't Ask:

  Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.
  ~Alec Sharp

Before we get to that, consider:

fillUps[i].getDist() > dMin

Can be written:

fillUps[i].canTravel( dMin )

Similarly:

fillUps[i].getPrice() > priceMax

Can be written:

fillUps[i].priceExceeds( priceMax );

The important question remains unanswered: why does the code check against distance and price? If all you want to do is determine how much it will cost on a given tank of gas, then write:

float maxDistance = fillUps[i].calculateDistance();

If you want to know the price to fill the remainder of the tank, write:

float price = fillUps[i].calculateFillPrice();

Move the code that uses the variables into the class that has the variables.

You can also compare objects, rather than the internal variables. For example:

AnnualFuelUse fillUps[] // ...
AnnualFuelUse minPriceFillUp;

for (int i = 0; i < fillUps.length; i++) {
  if( fillUps[i].exceedsPrice( fillUps[i-1] ) ) {
    maxPriceFillUp = fillUps[i];
  }

  if( fillUps[i].exceedsDistance( fillUps[i-1] ) ) {
    maxDistanceFillUp = fillUps[i];
  }

  // ...
}

At the end of the loop you'll have objects that contain the desired information. With those objects you can then ask them to perform specific tasks. Then make the get accessor methods private.


Just a small thing: consider using object and collection initializers.

So this:

NameValueCollection config = new NameValueCollection();
config.Add("CacheMemoryLimitMegabytes", cacheMemoryLimitMegabytes.ToString());

Becomes (also using var):

var config = new NameValueCollection { { "CacheMemoryLimitMegabytes", cacheMemoryLimitMegabytes.ToString() } };

And this:

CacheItemPolicy policy = new CacheItemPolicy();
policy.SlidingExpiration = SlidingExpiration;

Becomes:

var policy = new CacheItemPolicy { SlidingExpiration = SlidingExpiration };

And if you do that, you might want to get rid of the variables, and just specify the value of the parameter directly.

Also, it's common to use camelCase, not PascalCase, for private fields.


As Dagg said in his comment, try to cache things as much as possible - I haven't tested this code but you could do something like this:

(function ($, window) {
    // Do stuff when the DOM is ready.
    $(function () {

        $('form').on("click", "div.toggler", function () {
            $(this).next().slideToggle(300);
        });

        $('a.edit').click(function (e) {
            var clickedElement = $(this).parent(),
                editForm = $('#editForm'), // cache the edit form element.
                url = editForm.data('amp-url');

            $.get(url, {
                id: parseInt(this.id, 10) // Always specify the radix parameter
            }, function (result) {
                editForm.html(result);

                // Display edit form just below the "item" clicked
                if (editForm.is(":visible")) {
                    editForm.slideToggle(300, function () {
                        editForm.appendTo(clickedElement);
                        editForm.slideToggle(300);
                    });
                } else {
                    editForm.appendTo(clickedElement);
                    editForm.slideToggle(300);
                }
            },
                "html");
            e.preventDefault();
        });

        // Hide edit form when click outside it
        $(document).mouseup(function (e) {
            var container = $("#editForm");
            if (container.is(":visible")) {
                if (container.has(e.target).length === 0) {
                    container.slideUp(300);
                }
            }
        });
    });

    // Add the screen center function to jQuery.
    $.fn.screencenter = function () {
        var w = $(window);
        this.css("position", "absolute");
        this.css("top", ((w.height() - this.outerHeight()) / 2) + w.scrollTop() + "px");
        this.css("left", ((w.width() - this.outerWidth()) / 2) + w.scrollLeft() + "px");
        return this;
    };
}(jQuery, window));

This avoids having to hit the DOM each time, for example, you had $('window') four times... It's much better to get it once and store it in a variable.

I've also wrapped everything in an IIFE (Immediately Invoked Function Expression).

I'm not sure what you were trying to do here:

(function (a) {
    // code omitted.
})(jQuery);

But effectively you are passing the jQuery object into a function aliased as a. Then you are not using a but the jQuery object anyway - a bit pointless.

Edit:
Regarding the deferred object question:

var idToSend = 10;
var request = $.get(url, {
    id:  idToSend
});

// Assign handlers for events (can also chain):
request.done(function (result) {
    // Code for success.
}).fail(function (result) {
    // Code for fail
});


Convert cardinal abbreviations into full cardinal direction

Some notes:

I'd leave some room between the constants and the method definitions (subjective).
if (not match[1].empty?) and (not match[2].empty?). Parenthenses not necessary. In any case, for boolean operations, use !, &&, ||.
When you have so many similar ifs, they can usually be refactored into something else (usually, with no conditionals at all, but array processing).

First, with your code as reference mind, I'd write:

module Example
  class Utils
    CARDINAL_PATTERN = /^([NS]?)([EW]?)$/
    CARDINAL_DB = {'N' => 'NORTH', 'S' => 'SOUTH', 'E' => 'EAST', 'W' => 'WEST'}

    def correct_cardinal(word)
      clean_word = word.gsub(/\p{Punct}/, '').upcase
      match = CARDINAL_PATTERN.match(clean_word)
      if match
        cardinals = match.captures.reject(&:empty?)
        CARDINAL_DB.values_at(*cardinals).join(" ")
      else
        word
      end
    end
  end
end

On a second refactor, as @janos pointed out, you can build the complete hash of {CARDINALS => NAME} (well, it's so short you could just write down all its values, but let's build it programatically to see a way to do it).

module Example
  class Utils
    CARDINALS = {'N' => 'NORTH', 'S' => 'SOUTH', 'E' => 'EAST', 'W' => 'WEST'}
    # DIRECTIONS: {"NE"=>"NORTH EAST", "NW"=>"NORTH WEST", "N"=>"NORTH", ...}
    DIRECTIONS = ["N", "S", ""].product(["E", "W", ""]).map do |cardinals|
      name = CARDINALS.values_at(*cardinals).compact.join(" ")
      [cardinals.join, name]
    end.to_h

    def correct_cardinal(word)
      clean_word = word.gsub(/\p{Punct}/, '').upcase
      DIRECTIONS.fetch(clean_word, word)
    end
  end
end


I would prefer the name iterable for the iterable argument (compare the documentation for the itertools module), and sep for the seperator argument (compare the documentation for str.split).
isplit has the unsatisfactory feature that you cannot ignore any of the returned iterators — you have to consume each one fully before moving on to the next, otherwise the iteration goes wrong.

For example, suppose we want to select words starting with a capital letter. We might try:

for word in isplit('Abc def Ghi', ' '):
    first = next(word)
    if first == first.upper():
        print(first + ''.join(word))

But this produces the output:

Abc
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
StopIteration

Instead, we have to ensure that we consume each word iterator fully, even if we don't care about it:

for word in isplit('Abc def Ghi', ' '):
    first = next(word)
    if first == first.upper():
        print(first + ''.join(word))
    else:
        for _ in word:
            pass

The same issue arises with the standard library function itertools.groupby, where calling code might move on to the next group before it has finished iterating over the previous group. groupby solves this problem for us by fully consuming the previous group as soon as the caller moves on to the next group. It would be helpful for isplit to do the same.
The similarity with itertools.groupby suggests that we could implement isplit very simply in terms of groupby, like this:

from itertools import groupby

def isplit(iterable, sep):
    """Generate the contiguous groups of items from the iterable that are
    not equal to sep.

    The returned groups are themselves iterators that share the
    underlying iterable with isplit(). Because the source is shared,
    when the isplit() object is advanced, the previous group is no
    longer visible. So, if that data is needed later, it should be
    stored as a list.

    """
    for key, group in groupby(iterable, sep.__ne__):
        if key:
            yield group

Note that this code behaves like plain str.split() in that it coalesces adjacent separators. If you need the behaviour to be more like str.split(' '), with empty groups when there are adjacent separators, then it should be straightforward to add an else: clause to generate the necessary empty iterators, like this:

for key, group in groupby(chain((sep,), iterable, (sep,)), sep.__ne__):
    if key:
        yield group
    else:
        for _ in islice(group, 1, None):
            yield iter(())

This uses itertools.chain and itertools.islice.

(There are a couple of minor optimizations you could make here: the 1-element tuple (sep,) could be stored in a variable and used twice, and iter(()) could be a global constant since you don't need a new empty iterator each time.)