Is this a good/safe way to convert enums?

I solved a similar issue by inventing a DisplayName attribute, so I can define my enums like this:

public enum CreditCardName
{
    [DisplayName("VISA")]
    Visa,

    [DisplayName("MasterCard")]
    MasterCard,

    [DisplayName("Discover")]
    Discover,

    [DisplayName("American Express")]
    AmericanExpress
}

This has a number of advantages. For one, apps like Resharper will stop complaining about your naming scheme. Also, your string doesn't have to actually correspond to an English name, it could correspond to an entry in a translation strings file or something like that.

Source for DisplayName:

[AttributeUsage(AttributeTargets.Field)]
public class DisplayName : Attribute
{
    public string Title { get; private set; }

    public DisplayName(string title)
    {
        this.Title = title;
    }
}

Source for the method to retrieve your DisplayName objects

        IEnumerable<DisplayName> attributes = from attribute in typeof(CreditCardName).GetCustomAttributes(true)
                                              let displayName = attribute as DisplayName
                                              where displayName != null
                                              select displayName;

You can roll this into a more complete generic method too:

public string[] GetNames<TEnum>()
{
    return (from attribute in typeof(CreditCardName).GetCustomAttributes(true)
                                                     let displayName = attribute as DisplayName
                                                     where displayName != null
                                                     select displayName.Title).ToArray();
}

Unfortuately, I there isn't a way you can enforce that TEnum is an enum at compile time, but you could make it throw an exception instead.


Parsing a string with specific pattern into json

I could have criticized the most lines of the initial approach in terms of naming, relations, structuring and performance, but I believe it should be completely rewritten.

The optimized approach:

const input = "status:all,applied_date:2019-04-15--to--2019-04-15,screen_status:SR|NS";
const dateSep = /--to--/;

/**
 * Parse input string to build JSON representing
   a rule-set of AND clauses for SQL query.
 * The return value is JSON output.
 * @param {string} str - input string
 * @param {string} [entry_sep] - entry separator, defaults to ","
 */
function strToAndClause(str, entry_sep = ",") {
    let entries = str.split(entry_sep);
    let output = { and: {} },
        and_clause = output.and;

    entries.forEach((entry) => {
        let [key, val] = entry.split(":"), rule = {};
        key = key.replace("_", ".");
        and_clause[key] = rule;

        if (dateSep.test(val)) {
            rule.between = val.split(dateSep);
        } else if (val.indexOf("|") !== -1) {
            rule.inq = val.split("|");
        } else {
            rule.eq = val;
        }
    });
    return JSON.stringify(output);
}

console.log(strToAndClause(input));


Monitor a web page for when a desired price is met

Constant reuse

Store your base URL, "https://www.example.com", in a constant for reuse.

HTTP codes

Some status codes, such as 200, are common and obvious, while others such as 429 are less so. Fundamentally these are all magic numbers, and requests.codes contains symbols - including too_many_requests.

URL construction

           allposts = [f'https://www.example.com&Price={i["Price"]}'
                    for i in req.json()["data"]["Sellers"] if i["Price"] <= 10]

Firstly - you don't need to be adding the URL in here. You can move the query parameter to the params dict to be passed to session.post. Then the URL can be passed to session.post directly without any baked-in query parameters.

Variable case

ConnectTimeoutError as E:

Don't capitalize E since it's a variable. Past that, you shouldn't even write as E, since you aren't using the exception.

Import long-form symbols

requests.urllib3.exceptions.ConnectTimeoutError

would benefit from an import of this class so that you can use it without package qualification.


public static Validatable<T> ThrowIf<T>(this T argument)
{
    return new Validatable<T>(ref argument);
}

This of course is creating a lot of objects. You could speed this a little bit up by making Validatable a struct but still, it'll be slower then the normal check. Convenience comes often with some kind of a performance hit.

  I was going to use it my game engine

You'd better not. Make it fast, not convenient.

There is one more thing about validating arguments. The only thing you need to validate is user input or something that you cannot predict like configurations. Internally most methods usually work without argument checking because it's nearly impossible to pass invalid values. Use Debug.Assert for this purpose during development to be absolutely sure if you want. It'll be removed in the release version so that it doesn't slow the application down.


Replacing a for loop that iterates over an array with the functional programming equivalent

I think something like this will work for you.

Array.prototype.zip = function(other) {
    if (!Array.prototype.isPrototypeOf(other)) {
            throw new TypeError('Expecting an array dummy!');
    }
    if (this.length !== other.length) {
            throw new Error('Must be the same length!');
    }
    var r = [];
    for (var i = 0, length = this.length; i < length; i++) {
        r.push([this[i], other[i]]);
    }
    return r;
};

Player.prototype.d2 = function (ratingList, rdList) {
    var self = this;
    return 1 / Math.pow(q, 2) *
        ratingList
        .zip(rdList)
        .map(function (elem) {
            var tempE = self.e(elem[0], elem[1]);
            return Math.pow(self.g(elem[1]), 2) * tempE * (1 - tempE);
        })
        .reduce(function (acc, value) {
            return acc + value;
        });
};


It's a math problem more than a programming problem.

The distance to cover is \$y - x\$, so we divide that with our "speed", d, and round up to get the number of jumps. No loops or anything, just arithmetic.

The only trick is that if d is an integer, our division will be imprecise, since \$\frac{85-10}{30} = 2.5\$ but the decimal gets dropped by everything being treated as integers.

So we can either make d a float using to_f, or we can use fdiv to force a more precise, floating point division.

Using the latter, you get:

def solution(x, y, d)
  (y - x).fdiv(d).ceil
end

The return can be skipped, since this is Ruby.

Using to_f you could do:

def solution(x, y, d)
  jumps = (y - x) / d.to_f
  jumps.ceil
end

Finally, as Caridorc points out, renaming the arguments could make this even clearer

def solution(start, goal, jump_distance)
  (goal - start).fdiv(jump_distance).ceil
end

The above is the more correct solution (again, it's a math problem), but if we pretend that we do need a loop, you don't need the array for anything. Instead you could just do:

def solution(x, y, d)
  jumps = 0
  until x >= y
    x += d
    jumps += 1
  end
  jumps
end

Again, not the right solution for the problem, but a better one than using an array.


Combinatorial Geometry Algorithm (synthetic)

Here's my attempt at trimming it down. Note that there's no real reason to prefix variables with the_. Also list comprehensions can help with making code more concise, removing the need for total_triangles() entirely.
def make_triangles(lines: [(float, float)]) -> [(float, float, float)]:
    """
    :param lines: the lines to make triangles from
    :return: the triangles
    time: O(len(lines) * len(lines)
    space: O(len(lines) * len(lines))
    """
    triangles: [(float, float, float)] = []
    for ax, ay in lines:
        for bx, by in lines:
            if ax == bx and ay != by:
                triangles.append((ax, ay, by))
            if ax == by and ax != bx:
                triangles.append((ax, ay, bx))
    return triangles

def print_sums(sums: [float]) -> None:
    """
    :param the_sums: the calculated sums
    :return: None
    Output: std output
    """
    row = 0
    for number in sums:
        if row % 3 == 0:
            print('', end='\n')
        print(str(number), end=" ")
        row = row + 1
    print('\n', end='')

def main() -> None:
    """
    Entry point for script
    :return: None
    Input: None
    Output: std output
    """
    lines = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]
    triangles = make_triangles(lines)
    sums = [ sum(triangle) for triangle in triangles ]
    print_sums(sums)

if __name__ == "__main__":
    main()


Assigning atomic number based on atomic symbol

The most efficient way is to use unordered_map since C++11:

int main(int argc, const char * argv[]) {
    std::unordered_map<std::string, unsigned int> symbol_to_number = {
        {"H",  1},
        {"He", 2},
        {"Li", 3},
        // And so on..
    };

    // Usage:
    std::cout << symbol_to_number["H"] << std::endl;
    return 0;
}

Above, you get the number out of a symbol in constant time which improves on going through a lot of if statements.


Obtaining a list of files to be re-encoded (ideally determining the encoding just once)

Often, list comprehensions can aid readability. But here cramming all that behaviour into a single line is obfuscation. The Pythonic way is to do the simplest and most readable thing possible.

Here, this probably means writing a generator function that uses a normal for loop and skips over elements without an available encoding.

def encoded_files(files):
    for file in files:
        encoding = getEncoding(file)
        if encoding is not None:
            yield FileEnc(file, encoding)

to_convert_files = list(encoded_files(filenames))


Refactoring String manipulating method with TDD

Often, when performing text manipulation, Regular Expressions can do the work for you. Your solution is essentially manually building a text parser and stripper, when a regular expression will do the work in a much more concise way.

The regular expression would be to remove all text up to the last \ or ; character, which would be written as:

private String extractSimplePromptName(String promptNameOrg) {
    return promptNameOrg == null ? "" : promptNameOrg.replaceAll("^.*(\\\\|;)", "");
}


There is a general problem: The
distanceTo(_: Self) -> Self.Distance of the
ForwardIndexType protocol requires that

  start and end are part of the same sequence when conforming to RandomAccessSequenceType.
  end is reachable from self by incrementation otherwise.

(and RandomAccessSequenceType is probably a typo and should be
RandomAccessIndexType).

Here is a simple example where this conditions are not met, and
your code crashes:

let r1 = "foo".rangeOfString("")!
print(r1) // 1..<5
let r2 = "bar".rangeOfString("")!
print(r2) // 2..<6
let r = r1.intersect(r2) // fatal error: cannot increment endIndex

Incrementing the start index of r1 never hits the start index
of r2.

Here is another example:

struct MyIndex: ForwardIndexType {
    let value: Int

    func successor() -> MyIndex {
        return MyIndex(value: self.value + 1)
    }
}

func == (lhs: MyIndex, rhs: MyIndex) -> Bool {
    return lhs.value == rhs.value
}

is an index which can only be incremented. Then

let r1 = Range(MyIndex(value: 4) ... MyIndex(value: 6))
let r2 = Range(MyIndex(value: 3) ... MyIndex(value: 5))
let r = r1.intersect(r2)

will loop forever, because incrementing MyIndex(value: 4)
never reaches MyIndex(value: 3).

So intersecting ranges makes only sense if both ranges refer
to the same sequence. I don't know if that can be ensured at
compile time with a suitable restriction, I assume that it is
not possible. It should at least be documented (similar to the
above mentioned requirements of ForwardIndexType).

You could restrict the method to ranges of integer elements

public extension Range where Element : IntegerType { ... }

but of course that reduces its usability considerably.

The implementation itself looks good to me. The behavior in the case
of an empty intersection it a sensible choice. Is similar to that of the clamp()
method of ClosedInterval:

ClosedInterval(3, 4).clamp(ClosedInterval(5, 6)) // 4 ... 4
ClosedInterval(3, 4).clamp(ClosedInterval(1, 2)) // 3 ... 3

which returns the left or right bound, depending on wether the other
interval lies on the left or on the right.

If your ranges just represent intervals and do not refer to indices
of sequences, then ClosedInterval (and the existing clamp() method) might be an alternative.


Fluent interface for manipulating employee records

I would drop the edit function and make add_employee the entry point to the API.  I've written a number of fluent APIs in C++ and found that placing the required arguments (e.g., employee name) in the API entry point invaluable.  From the usage point of view, something like:

int main(void) {
    Record db;
    init_record(&db);
    add_employee_to(&db, "Bob")
        ->having_salary(2000)
        ->with_id(10202);
    return 0;
}

The goal of the API is to create a new employee and append them, so make that the entry point.  If you can't have a valid employee record with a name, then this becomes a first-class parameter of the entry point.  Not sure about the requirements, so it may make sense for ID to be a required parameter as well.  I also changed the names to make them More Fluent™.


I would suggest moving the CSS selection logic to a custom template tag or even a filter, e.g. {{ t.relative_due_date }}. After that your templates will look much cleaner and that logic would still belong to the presentation part of MVT (Model, View, Template).
You can split your tuple in the definition of the loop so that you don't redefine the tasks variable. {% for header, task_list in tasks %} ....
Use reverse URLs, no question about it. You'd hate the day you have to change them otherwise :) Go even further, use URL namespaces.


dp_triangle(triangle, height, row, col) depends on three things: dp_triangle(triangle, height, row + 1, col), dp_triangle(triangle, height, row + 1, col + 1), and triangle[row][col]. Therefore it's not necessary to cache more than one row at a time. With that insight you should be able to refactor it to not need dict() at all.

I actually prefer to solve this problem by going down rather than up. That is to say, I define my intermediate result as v(row, col) = max(v(row-1, col-1), v(row-1, col)) + triangle[row][col]. Then the double-array of triangle can be processed in order using a simple for loop, as opposed to in reverse using a slightly more complicated for loop.


You are on the right track, but the code does need a lot of attention.

Never go for #include <bits/stdc++.h>

Same goes for using namespace std; Both will lead you into a lot of trouble for zero gain. Only include what you need and use proper qualifications

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

Note that I also sorted the includes alphabetically so it is easy to see what is already included
You should pass by value whenever it is possible. However std::string is no such case. Luckily we have std::string_view since C++17 so you should almost always prefere this to passing a std::string, e.g

int sumASCII(const std::string_view input) {
    int i;
    int sum = 0;
    int size = input.size();

    for( i = 0; i < size; i++) {
        sum+=(int)input[i];
    }

    return sum;
}

Same for all the other functions. Your strings are stored in the original vector so there is no possibility for a dangling reference. That said you should definitely read up on ownership and view-like types
Use a formatter. Your formatting is highly unregular. You should pick a clang-format style you are comfortable with and use that everywhere.
Use range-based loops when possible

int sumASCII(const std::string_view input) {
    int sum = 0;
    for (const char character : input) {
        sum += (int)character;
    }
    return sum;
}

Do not use C-style casts. C++ has a wide variety of specialized casts that do what they are supposed to do and not more. In the above case static_cast is sufficient

int sumASCII(const std::string_view input) {
    int sum = 0;
    for (const char character : input) {
        sum += static_cast<int>(character);
    }
    return sum;
}

Use the proper algorithms

The STL provides a wide range of algorithms that is not only incredibly powerfull but also is often highly optimized and correct with respect to various corner cases.

int sumASCII(const std::string_view input) {
    return std::accumulate(std::begin(input), std::end(input), 0);
}

Note that you might want to test this with proper warnings.
Consider const correctness.

One of the most difficult parts of programming is keeping all the moving parts in your head. The more explicit you are about what is immutable the easier it is to reason about the code. So use const whenever possible and cbegin and cend too. (Even if in this case it does exactly the same it provides additional information to the reader)

int sumASCII(const std::string_view input) {
    return std::accumulate(std::cbegin(input), std::cend(input), 0);
}

Keep control flow as simple as possible.

Another hard part of software engineering is keeping track of control flow. Try to minimize indentations as much as possible to keep the code clean and easily readable. As an example this is what you wrote

for( i = 1 ; i < size;  i++ ) {
    sumCurr = sumASCII(text[i]);
    originalSize = originalStrings.size();
    for( k = 0; k < originalSize; k++ ) {
        if(originalStrings[k].size() == text[i].size() ) {
            sumPrev = sumASCII(originalStrings[k]);
            if(sumPrev == sumCurr) {// means it found a possible anagram.
                copyA = originalStrings[k];
                copyB = text[i];
                if(sortStringAndCompare(copyA,copyB) == 0)
                {
                    anagram = true;
                    break;
                }
            }
            else
                anagram = false;
        }
        else {
           anagram = false;
        }

    }
    if(!anagram) {
        originalStrings.push_back(text[i]);
    }
}

It is hard to keep track of the different conditions in thi loop and what it actually does so lets try to simplify it with some early returns:

for( i = 1 ; i < size;  i++ ) {
    anagram = false;
    sumCurr = sumASCII(text[i]);
    originalSize = originalStrings.size();
    for (const string_view newString : originalStrings) {
        if(newString.size() != text[i].size() ) {
            continue;
        }

        sumPrev = sumASCII(newString);
        if(sumPrev != sumCurr) {
            continue;
        }

        copyA = originalStrings[k];
        copyB = text[i];
        if(sortStringAndCompare(copyA,copyB) == 0) {
            anagram = true;
            break;
        }
    }

    if(!anagram) {
        originalStrings.push_back(text[i]);
    }
}

I hope you agree that this is much easier to read.
Think about the proper data structures.

You are searching for a reoccuring pattern. This is usually done via an associative container. The STL knows std::unordered_map and std::map. You should use those.

The first thing you need is a container of histograms,. You wantunique ones so you should go for a set

std::unordered_set<someHistogramThing> histograms;

The second thing you want to do is to count the characters in the string. Again a map is the simplest solution

std::unordered_map<char, std::size_t> charCount;

Lets have a look at how we get there;

std::unordered_map<char, std::size_t> countCharacters(const std::string_view input) {
    std::unordered_map<char, std::size_t> charCount;
    for (const char character : input) {
        charCount[character]++;
    }
    return charCount;
}

For any word this gives us a histogram of the occurences of characters in that word. Two words are an anagram if they have the same histogram. So lets see if we can put it together.

std::vector<std::string> removeAnagrams(const std::vector<std::string>& input) {
    std::vector<std::string> result;
    std::unordered_set<std::unordered_map<char, std::size_t>> histograms;
    for (const std::string& newWord : input) {
        const auto[it, notAnagram] = histograms.insert(countCharacters(newWord));
        if (notAnagram) {
            result.push_back(word);
        }
    }
}

Usetype aliases to give your data structures better names

using CharacterHistogram = std::unordered_map<char, std::size_t>;
using HistogramSet = std::unordered_set<CharacterHistogram>;

If we put that all together we get

#include <string>
#include <string_view>
#include <vector>
#include <unordered_map>
#include <unordered_set>

using CharacterHistogram = std::unordered_map<char, std::size_t>;
using HistogramSet = std::unordered_set<CharacterHistogram>;

CharacterHistogram countCharacters(const std::string_view input) {
    CharacterHistogram charCount;
    for (const char character : input) {
        charCount[character]++;
    }
    return charCount;
}

std::vector<std::string> removeAnagrams(const std::vector<std::string>& input) {
    std::vector<std::string> result;
    HistogramSet histograms;
    for (const std::string& newWord : input) {
        const auto[it, notAnagram] = histograms.insert(countCharacters(newWord));
        if (notAnagram) {
            result.push_back(word);
        }
    }
}


To answer your specific concern about jQuery-dependence, the jQuery extend function is basically this:

var key;
for(key in objB) {
  objA[key] = objB[key]; // copy each value from objB into objA
}

That's all there is to it really.

However, I see a number of other things in your code that I think deserve attention.

1. Why define pluck insides the AOHandler constructor, and everything else in its prototype? Just wondering, since it's an unnecessary mixing of style. pluck can just as easily go in the prototype.

2. You're using typeof ao === 'object' when determining whether to use the argument passed to the constructor or not. Use ao instanceof Array instead. Almost everything in JS is "typeof object", but what you're looking for is an array and only an array. (I'd probably be strict about it too and throw an exception if a non-array argument is passed).

3. Your code doesn't seem to handle multiple identical values very well. Say I do this:

var ao = new AOHandler(),
    obj = { foo: "bar" },
    dup = $.extend({}, obj);

ao.add(obj);
ao.add(dup);
ao.add(obj);

Now there are three items in the AOHandler's list, two of which are the exact same object, and the third being a copy. None of you functions seem prepared to deal with such a situation. For instance, calling update would update the first item, which happens to also be the third item, so in fact 2 items get updated. However, the 2nd item (which has the same values, but isn't the same object) would be untouched. Could get pretty confusing.

4. Your function names seems a little off to me. pluck usually means to pick out values from each item in a list (i.e. a map-like function); not the items themselves, and certainly not only the first one. filter, select, find, search, or fetch would all be better names, provided the function actually returns all the matches. filter is indeed the name used for the native JS function (available in ECMA 5) that, well, filters an array and return the subset that matches a comparison function.

However, your pluck can also return the index of an item. You call it key, but since this.ao is a normal numerically-indexed array index is the word to use. Key implies it won't change, but indices of an array do change when other items are added or removed.
Anyway, the usual JS name for a function that finds the index of a certain thing in an array is indexOf. So I'd suggest that you break the pluck function into an indexOf function and a filter function, since those are separate things.

You could also make the case for push instead of add, since AOHandler is pretty much a wrapper around an array, and you push items to arrays. But add is plain English (and the same that Java uses for its ArrayList), so it's fine to use.

update is more problematic though, because it really does 2 (very) different things: Merge or replace. Merge will update the object in-place, so whereever else you have a reference to it, the updates will be visible. Replacing the object is a different story altogether. Again, I'd suggest 2 functions, since the effects are so very different, and the implementations have little in common.

Here's me take:

function AOHandler(ao) {
  // if anything's passed, it must be an array
  if(typeof ao !== "undefined" && !(ao instanceof Array)) {
    throw new TypeError;
  }
  this.ao = ao || [];
}

AOHandler.prototype.indexOf = function (predicate, offset) {
  var i, l = this.ao.length;
  if(typeof predicate !== 'object') { throw new TypeError; } // type check
  offset = parseInt(offset, 10) || 0;
  // match native indexOf's handling of negative offset
  // see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
  offset = (offset < 0 ? l - offset : offset);
  offset = offset < 0 ? 0 : offset;
  for( i = offset ; i < l ; i++ ) {
    if(this.ao[i][predicate.key] === this.ao[i][predicate.value]) {
      return i;
    }
  }
  return -1;
};

AOHandler.prototype.filter = function (predicate) {
  var offset = 0, index, results = [];
  while((index = this.indexOf(predicate, offset)) !== -1) {
    results.push(this.ao[index]);
    offset = index + 1;
  }
  return results;
};

// This, by the way, is a pluck function
AOHandler.prototype.pluck = function (key) {
  var i, l, results = [];
  for( i = 0, l = this.ao.length ; i < l ; i++ ) {
    results.push(this.ao[i][key]);
  }
  return results;
};

AOHandler.prototype.add = function (obj) {
  if(typeof obj !== 'object') { throw new TypeError; } // type check
  return this.ao.push(obj);
};

AOHandler.prototype.get = function (predicate) {
  var index = this.indexof(predicate);
   // return null - not false - if no obj is found
  return (index === -1 ? null : this.ao[index]);
};

// Simple jQuery-less merge function
AOHandler.prototype.update = function (predicate, source) {
  var matches = this.filter(predicate), i, l, key;
  if(typeof source !== 'object') { throw new TypeError; } // type check
  for( i = 0, l = matches.length ; i < l ; i++ ) {
    for(key in source) {
      // it may be a good idea to do a source.hasOwnProperty[key] check here
      matches[i][key] = source[key];
    }
  }
};

// replace all matches
AOHandler.prototype.replace = function (predicate, replacement) {
  var matches = this.filter(predicate), index, l, offset, key;
  if(typeof replacement !== 'object') { throw new TypeError; } // type check
  while((index = this.indexOf(predicate, offset)) !== -1) {
    this.ao[index] = replacement;
    offset = index + 1;
  }
};


In the Logtalk library, you have a map_reduce/5 predicate:

:- public(map_reduce/5).
:- meta_predicate(map_reduce(2, 3, *, *, *)).
:- mode(map_reduce(+callable, +callable, +term, ?list, ?term), zero_or_more).
:- info(map/5, [
    comment is 'Map a list and apply a fold left (reduce) to the resulting list.',
    argnames is ['Map', 'Reduce', 'Accumulator', 'List', 'Result']
]).

map_reduce(Map, Reduce, Acc, List, Result) :-
    map_reduce_(List, Map, Reduce, Acc, Result).

:- meta_predicate(map_reduce_(*, 2, 3, *, *)).
map_reduce_([], _, _, Result, Result).
map_reduce_([Arg| Args], Map, Reduce, Acc, Result) :-
    call(Map, Arg, Arg2),
    call(Reduce, Acc, Arg2, Acc2),
    map_reduce_(Args, Map, Reduce, Acc2, Result).

A main difference to your code is that you assume a single closure combining both the map and reduce operations in the Logtalk version. You also return the map result in addition to the final fold result.


Looks good in general. Few comments.

Missing import random.
Random pivot selection is just one of many possible strategies. It may or may not be a good strategy depending on the nature of data. Only the client knows what a suitable strategy will be; let him chose.
No Raw Loops mantra: Every loop possible represents an algorithm, often very important itself. In this case the algorithm is partition. It is worthy to be factored out in a function of its own.


Finding correct format? Arrays and Modulation

Here's how I would do it.

Update: I included a description of my code this time based on comments.

First, reading a file into a variable so that each line of the file is its own element in an array is super easy with File.ReadAllLines(...). But I don't feel like using a variable for that is necessary here, so I immediately start using the array by using the Select(...) method. I'm using Select here to create an anonymous type (That's the return new { ... } part).

var data = File.ReadAllLines(@"c:\temp\data.txt").Select (f =>
{
    var split = f.Split(',');
    return new {
        Age = int.Parse(split[0]),
        District = split[3]
    };
});

At this point, I've got a type-safe collection of "data" that I can work with. That's important, and very useful.  For example..

var byDistrict = data.GroupBy (d => d.District);

In the line above, I've grouped the data by District. Grouping is, in my opinion, almost always better than using Distinct.

The rest of the code is very similar to your original code, except my code avoids the need to have the age reports within a loop.

foreach (var district in byDistrict)
{
    Console.WriteLine("District {0} has {1} resident(s)", district.Key, district.Count());

}

Console.WriteLine("Ages 0-18 : {0} resident(s)", data.Count(x => x.Age < 18));
Console.WriteLine("Ages 18-30 : {0} resident(s)", data.Count(x => x.Age >= 18 && x.Age <= 30));
Console.WriteLine("Ages 31-45 : {0} resident(s)", data.Count(x => x.Age >= 31 && x.Age <= 45));
Console.WriteLine("Ages 46-64 : {0} resident(s)", data.Count(x => x.Age >= 46 && x.Age <= 64));
Console.WriteLine("Ages >=65 : {0} resident(s)", data.Count(x => x.Age >= 65));


This isn't related to your question, but you are not using exceptions properly.

try
{
    foreach (string s in response)
    {
        if (string.IsNullOrWhiteSpace(s))
            throw new Exception(string.Format("Message='{0}' ", s));

        //...
    }
}
catch (Exception ex)
{
    serviceLog.Error("fatal error", ex);
}

You are using the exception as a way to break out of the for loop. This is exactly what the break statement is for. Instead, you create a new Exception, which must populate the stack trace, and then the code starts to unwind the stack looking for the closest matching catch. This is an expensive process for something that is very basic. This could be replaced with:

foreach (string s in response)
{
    if (string.IsNullOrWhiteSpace(s))
    {
        serviceLog.Error("fatal error", string.Format("Message='{0}' ", s));
        break;
    }

    //...
}

In addition, you are throwing the base class Exception. This means that the most specific catch you can write is for the base class. This will catch all exceptions, including things like StackOverflowException and OutOfMemoryException. Your code will then try to continue on with no knowledge that these much more serious exceptions were swallowed up into a log message.

When you throw an exception in your code, it should be a sub-class of Exception that is as specific as you can be. This may be a predefined exception of an exception class you explicitly declare. By doing this, you can use the type system to handle different types of exceptions differently and not catch the exceptions you don't mean to handle.


Your solution is absolutely correct and practical.

In fact Enumerable.Empty<T> also returns empty array under the hood, just slightly in a different way (they have a separate instance holder class that is lazily initialized).


//retrieves the datetime WITHOUT loading the whole image
string[] GetDateTakenFromImage(string path)

Function name and parameter are named well. You should use an XML-doc header to document the quirk that it doesn't need to load the entire image.
Overall I like that the method is concise: it mostly does only one thing, it's easy to read, and not needing to pre-load the whole image is a nice bonus.
It is strange to use string[] to denote a date. You should be returning a DateTime?.
Consider changing it to accept a Stream instead of a string path. Currently it's a bit burdensome to test your method because it requires a file path, even though all it's doing is getting a stream out of it anyway. By accepting a Stream instead, you can more easily put automated tests around it that use in-memory test data and avoid a whole litany of IO nonsense.

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))

fs is a poor name. Give it some more meaning, like imageStream. It can also be written a bit more concisely:
using (FileStream imageStream = File.OpenRead(path))

Likewise, myImage could just be named image.

PropertyItem propItem = myImage.GetPropertyItem(36867);

Avoid magic numbers -- that 36867 should be in a named constant somewhere:
const int ExifDateTimeOriginal = 0x9003;

Your error handling in general could be improved. If I was consuming this API, I would naturally expect exceptions relating to IO (file not found, file not accessible, not a valid image file, and so on) to propagate up. It's up to you whether you want to throw or return null in the case where everything is valid but the image simply doesn't have that tag.
You're returning null if anything goes wrong which makes this harder to test. Be aware that myImage.GetPropertyItem(36867); will throw if the tag is not present (which in my opinion is a totally non-exceptional circumstance), so if you do tweak your method to propagate other exceptions you will need to put that one line around a try-catch for that one exception.

The EXIF tag you're checking is encoded in ASCII according to the EXIF docs I've been able to find, so this should use Encoding.ASCII instead of Encoding.UTF8:
string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);

You also don't need to do any string replacing. DateTime.ParseExact is handy for parsing dates encoded in custom formats:
string dateTaken = Encoding.ASCII.GetString(propItem.Value);
...
return DateTime.ParseExact(dateTaken.Trim('\0'), "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture);

Lastly, if you want to really adhere to the letter of the spec then depending on how you decide to modify or keep your method contract you'll need to handle the case where the date and time are unknown and all non-colon characters are replaced with spaces.


Program to reverse a string using std::string

The functionality is already present in the standard library. Your class has very limited usability and I would prefer simple std::reverse(str.begin(), str.end()). But lets put it aside and deal with the code you've written.

#include <iostream>
#include <cstdio>

Very bad idea to mix these two. I/O may become unordered.

using namespace std;

Why is “using namespace std” in C++ considered bad practice?.

class stringOps

Operations on class's data should be part of it, so naming it stringOps is not good idea. C++ programmers often use operator overloading to expand on some class.

You begin your class definition by private keyword, but everything in class is private by default, whereas in struct it is public. It is the only difference between the two.

    string arr;

What arr means? Nothing comes to mind. You should use something like str. It is good to give your variables good name. It greatly increases readability of the code.

   int length;

Declared, but never used.

    stringOps(string arr);

If you want to make a copy of the string type should be const std::string&. If you want to move from it, the type should be std::string&&.

    ~stringOps();

You declared destructor that does nothing. Compiler generates this by default if you don't provide any destructor. Remove it.

    int getLength();

From return type (int) I may suspect that the code can return negative size. It should be std::size_t, which is meant to be used in context of size. Further reading: When should I use std::size_t?

The functionality is present in std::string. On top of that, you use arr.length() as return value, not length.

    const string& displayString(const stringOps &a);

Why would you return const reference to it? I think users expect a copy of internal string. All operations on copying are noexcept, not including memory allocation, of course.

The next thing is arguments. It would be better to just omit argument, and return internal string.

stringOps reverseStr(stringOps &a);

Again, argument should be omitted. The internal string should be reversed and returned. Also, it would be better to return std::string.

Answer for your first question:

Don't do it in the future. It's not that your code is wrong. The purpose of it is very wrong.


Why zip?

You have:

dots  = [x for x, y in zip("7321", range(r1))]
dots += [x for x, y in zip("8654", range(r2))]

You're never using the second part of that zip. So you're basically making lists for the two ranges, making lists for the two zips, making lists for the outcomes of those things, all to drop most of the information.

You can simplify that to just:

dots = '7321'[:r1] + '8654'[:r2]

character name

Try to avoid building up strings with +=. Instead just use format:

character_name = "BRAILLE PATTERN DOTS-{}".format(join(sorted(dots)))


import cTurtle
import random
import sys

Excellent!  Many people use wildcard imports, (from <module> import *), but you didn't.  You even alphabetized your imports.  Keep up the good work.

PEP 8, the Python style guide, has this to say in the Function Names section:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.

  mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

That means that DrawTicTacToeBoard would be draw_tic_tac_toe_board, for example.

Your spacing does not comply with PEP 8.  Specifically:

  Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=,-= etc), comparisons (==,<,>,!=,<>,<=,>=,in,not in,is,is not), Booleans (and,or,not).

#Vertical Lines of board
t.pensize(3)
t.up()
t.goto(.5,-.5)
t.down()
t.goto(.5,2.5)
t.up()
t.goto(1.5,-.5)
t.down()
t.goto(1.5,2.5)

I realize that you want to save characters, but -.5 is a little hard to read.  It almost looks like the - is one argument and 5 is another argument.  The extra 0 between the two would greatly improve readability.  Speaking of saving characters, you could use a for loop ... probably.  I haven't come up with anything that I really like, though.  You should also consider a different name for your argument.  Perhaps turtle would be more descriptive.

def flipPlayer(currentPlayer):
    if currentPlayer==0:
        currentPlayer=1
    else:
        currentPlayer=0
    return currentPlayer

This function is included in two rules mentioned above, but I mention it here because there is a much easier way to do it:

def flip_player(current):
    return (current + 1) % 2

Read more about the modulus operator and when to use it.

for i in range(4):
    t.forward(.8)
    t.right(90)

Again, you should be using a more descriptive name, but I brought up the for loop because you use i as your variable name.  There isn't anything wrong with using it, but in cases where the variable is not used, it is common practice in Python to use _ as the variable name.  It just makes it a little more obvious that it is an unused variable.

move = input("Enter location to place your marker " + markerList[currentPlayer] + ", or EXIT to end game => ")

That line is 110 characters not including indentation.  PEP 8 says:

  Limit all lines to a maximum of 79 characters.

Perhaps it would be better to define a template and format it in the loop:

template = "Enter location to place your marker {}, or EXIT to end game => "
while move not in valid_move_list:
    move = input(template.format(marker_list[current_player]))
    ...

I would also change how you check your conditions in the while loop.  Here is what I would do:

while True:
    move = input(template.format(marker_list[current_player]))
    if move == "EXIT":
        sys.exit()
    elif move in valid_move_list:
        y, x = map(int, move.split())
        if not boardLoL[y][x]:
            return move
        else:
            print("Location already occupied")
    else:
        print("Invalid move")

There is no need for while to be checking anything since you account for all cases inside.  I also added an else: so that the user would know why he was being asked again for input.

def gameWon(b):
    for row in range(3):
        if b[row][0]==b[row][1] and b[row][1]==b[row][2] and b[row][0]!="":
            print("Way to go",b[row][0])
            return b[row][0]
    for column in range(3):
        if b[0][column]==b[1][column] and b[1][column]==b[2][column] and b[0][column]!="":
            print("Way to go",b[column][0])
            return b[0][column]
    for diag in range(2):
        if b[0][0]==b[1][1] and b[1][1]==b[2][2] and b[0][0]!="":
            print("Way to go",b[0][0])
            return b[0][0]
        if b[2][0]==b[1][1] and b[1][1]==b[0][2] and b[2][0]!="":
            print("Way to go",b[2][0])
            return[2][0]

You can simplify that to this:

def game_won(board):
    for row in board:
        if len(set(row)) == 1:
            return row[0]
    for column in zip(*board):
        if len(set(column)) == 1:
            return column[0]
    for diag in range(2):
        ...

I would do all of the printing outside of the function.  In your main() function, it would be like this:

print(game_won(boardLoL))

instead of:

game_won(boardLol)

I'm not crazy about the diagonal searching, but I can't think of anything better at the moment.  Maybe it's because I've been awake for ... yawn

return[2][0]

I don't think that's what you meant.  Perhaps, return b[2][0]

def boardIsFull(boardLol):
    return False

Haven't added it yet, huh?  Maybe this:

def board_is_full(board):
    return all(all(row) for row in board)

Yeah, nifty.  You see, all(row) makes sure that each item in row is a Truthy value.  Any non-empty string is Truthy, so if any of the cells in that row is empty, all(row) will return False.  Since I am running all() on each of those all() calls, it returns False if any cell in the board is empty, but True otherwise.

while boardIsFull(boardLoL)==False and gameWon(boardLoL)=="" and move !="EXIT":

Any condition is checking a boolean.  That is, if ...: is seeing if ... is True.  Using if ... == True: is redundant because you could have just used if ...:.  Consequently, if ... == False: is redundant because you could have used if not ...:  You can simplify that line like this:

while not board_is_full(boardLoL) and not game_won(boardLoL) and move != "EXIT":

That line is one character too long for PEP 8.  I would suggest changing boardLoL to board in all places.  What is LoL doing there anyway?  Are you laughing as you type?

I hope I haven't sounded too harsh, but it's been a late night.


Message Object - Best Practice? |  Consider data attribute for pulling text in

I don't really understand what you are asking here, but I'll give some general pointers:

I find that you have two different variables called Message very confusing.
It's not really a good idea to add proprietary properties to DOM elements. You should consider using the HTML5 dataset API instead.
It seems wrong to hard code the fade effect.
IMHO this seems like a lot of code and unnecessarily over-engineered for displaying a simple message. It reminds me a lot how of the Twitter bootstrap library does things.


Well, you could build a dictionary for the temp array but it depends how often the key (index 1 of each temp row) is repeated. If you have very few repetitions then it could reduce the time because it only has to search through a subset of the 1000 temp rows.

Something along these lines:

Dictionary<string, List<string[]>> rowCache = new Dictionary<string, List<string[]>>();

foreach (var row in tempArray)
{
    List<string[]> keyRows;
    string key = row[1];
    if (!rowCache.TryGetValue(key, out keyRows))
    {
        keyRows = new List<string[]>();
        rowCache[key] = keyRows;
    }
    keyRows.Add(row);
}

Then your main loop becomes something like

// little helper method
public List<string[]> GetRows(string key)
{
    List<string[]> rows;
    return rowCache.TryGetValue(key, out rows) ? rows : new List<string[]>();
}

...

foreach (var row in rawArray)
{
    foreach (var srcRow in GetRows(row[0])
    {
       // perform your SRC logic here
    }

    foreach (var dstRow in GetRows(row[1])
    {
       // perform your DST logic here
    }
}

Another major speed improvement can probably be achieved by not using strings for entries which obviously aren't strings. You are doing a lot of double-to-string-and-back conversion which will be slow. If you can convert the input data into double when obtaining it, perform your calculations and then convert it back for output if necessary it should speed things up a lot as well.


Setter use for dependency injection, passing interface through too many layers

Your class names are really throwing me off.  Perhaps because they are so generically named.  By looking at these classes I have a hard time understanding the interfaces you are trying to expose.

What is a Chat?  Why does a chat hold references to Offers (which seems to only be a single "offer" so should perhaps be named Offer)?  Why would a Chat object need a method to check if the Offers it holds is byLawyer (which perhaps should be named isLawyer() since it returns boolean.)?

I just honestly can't make heads or tails of it because I don't think your classes are defined upon real-world lines. Make sure you name your classes meaningfully and specifically, and most importantly with relevance to real-word concepts.  9 times out of 10, if you find yourself thinking of you objects in real-world terms, you will come up with a better design.  In the real world, does a chat have the ability to determine if it has something to do with a lawyer?  No, a chat may need to know about the parties chatting, have some send/receive message functionality, maybe store messaging history, etc.  What does it have to do with lawyers or offers?

What is a CategoryService (ServiceCategory?) and what does it have to do with lawyers (are lawyer services one category of service?)

Lots of questions around Offers:

Why would an Offer(s) object hold information on categories? Wouldn't this be an opposite relationship in real world terms (where categories hold offers)?
If you require AbstractCategory (or CategoryService) as a dependency for Offers why not pass that dependency in constructor?  Why let your class be set up in a bad state?
Do you really need Offers to be mutable, or will it always have a 1-to-1 relationship with CategoryService it wraps?  If so, why the need for the getters/setters?
Does Offers even provide any meaningful functionality above and beyord the AbstractCategory object it holds.
Should AbstractCategory truly be an abstract class or an interface?  Usually when you pass a generalized object like this, you are depending on that object having a given interface, not that it inherits from some class. I would seem a bit odd to be type hinting against an abstract class.

$this->parent_cat_id

You don't have parent_cat_id defined as property on this class.

return (int)$this->parent_cat_id;

There should be no reason for type casting here.

Chat can be set up in a bad state.  byLawyer() method can perform unexpectedly if offer property has not been set.  Should Offers be passed as dependency on constructor?

Why inconsistent use of doc blocks?

Don't mix camelCase and snake_case in your own code.

Why inconsistent use of return type hinting?


Logic

Is the basic logic OK? Any obvious improvements?

Well does the game work? If so then the basic logic must be OK.
Is there room for improvement, yes.
The code is tangled mess of roles and states.

You have 4 functions that manage 7 distinct game states.
There is some repeated code (win and lose).
You have magic values in the code (text prompts and displays)
The whole thing runs in a continuous blocking state which is VERY bad for browser based code (you can not exit until end game)
There is no checking for repeated character guesses, or valid character guesses.
You randomly pick words, not checking if a new game is using an already used word.

Example
The example shows some alternative approaches to creating game like state machines.
Note that I do not use the console, prompt, or confirm, thus the game needs an additional wait state to wait for input.
Nor do I vet input for repeats, or bad characters.
update I have fixed the inplay state to only allow start when not inplay
Some points.

Uses finite state model to control the game.
Settings out of the code and grouped in one place to allow easy changes.
Encapsulate the game in a singleton (to keep the global scope clean)
Though I do not use prompt and confirm, the state changes use setTimeout to change between states, this stops the game from blocking the page.
States are pedantic but there roles are clear and without ambiguity.

"use strict";  // Always add this to the top of your code.

/* Start game is external state request */
document.getElementById("play").addEventListener("click", ()=> {
    hangman.state = "start";
})

const hangman = (()=> {
    const settings = {
        limit : 4,
        words : ["fish","cat","chicken","freedom","turnip"],
        text : {
            start : "Guess one letter at a time to reveal the secret word.",
            prompt : "Guess a letter. You have ## remaining guesses", // ## is replaced with remaining guesses
            good : "Well done.",
            bad : "That letter in not in the secret word.",
            win : "Yay, you guessed it!",
            lose : "You have used all your guesses. Game Over.",
            again : "Play again Y/[N] ",
            gameOver : "You have used up all the words. GAME OVER!",
            exit : "Bye!",
        }
    };

    const display = text => log(settings.text[text] ? settings.text[text] : text);
    var word, player, inplay, wrongGuesses;

    function start() {
        if(settings.words.length > 0){
            word = settings.words.splice(Math.random() * settings.words.length | 0, 1)[0];
            player = "";
            wrongGuesses = 0;
            display("start");
            display("Cheat >>> " + word + " <<<<");
            return states.guess;
        }
        return states.gameOver;
    }

    function getPlayerGuess() {
        const gotKey = (key) => {
          const guess = key.toLowerCase();
          player += guess;
          game.state = word.indexOf( guess ) === -1 ? states.badGuess : states.goodGuess;
        }
        var remaining = settings.limit - wrongGuesses;
        const guess = prompt(settings.text.prompt.replace("##", remaining), gotKey);
        return states.wait;
    }

    function checkPlayer(){
        var wordDisplay = "";
        for (const char of word) { wordDisplay += player.indexOf(char) > -1 ? char : "_" }
        display(wordDisplay);
        return wordDisplay === word ? states.win : states.guess;
    }

    const states = { // All game states named
        start : 1,
        guess : 2,
        badGuess : 3,
        goodGuess : 4,
        win : 5,
        lose : 6,
        playAgain : 7,
        gameOver : 8,
        wait : 9,
    };

    const game = {  // assign property game.state to change state
        set state(value) {
            if(! inplay){
                if(value === "start") {
                    value = states.start;
                } else {
                    return;
                }
            }
            inplay = true; // prevents game restart while in play
            var nextState; // if left undefined then game ends
            switch(value) {
                case states.wait:
                   return;
                case states.playAgain:
                    confirm(settings.text.again, result => {
                       game.state = result ? states.start : states.exit;
                    });
                    nextState = states.wait;
                    break;
                case states.start:
                    nextState = start();
                    break;
                case states.guess:
                    nextState = getPlayerGuess();
                    break;
                case states.goodGuess:
                    display("good");
                    nextState = checkPlayer();
                    break;
                case states.badGuess:
                    display("bad")
                    wrongGuesses += 1;
                    nextState = wrongGuesses === settings.limit ? states.lose : states.guess;
                    break;
                case states.win:
                    display("win");
                    nextState = states.playAgain;
                    break;
                case states.lose:
                    display("lose");
                    nextState = states.playAgain;
                    break;
                case states.gameOver:
                    display("gameOver");
                    break;
                default :
                    return;
            }
            if (nextState) { setTimeout(() => game.state = nextState, 0) }
            else {
                display("exit");
                inplay = false;
            }
        }
    };
    return game;
})();

/*========================================================================*/
/*========== unrelated code to handle input and display ==================*/
var prompting;
var keyVal;
document.addEventListener("keyup",e=>{
    if(prompting){
        keyVal = e.key;
        prompting = false;
    }
})
function prompt(text,cb){
    var ticker = 0;
    const line = log(text );
    prompting = true;
    function tick(){
        if(prompting){
            line.textContent = text + (ticker++ & 1 ? "?" : ".");
            setTimeout(tick, 250);
        }else{
            line.textContent = text + "! " + keyVal;
            cb(keyVal[0]);
        }
    }
    tick();
}
function confirm(text, cb){
   prompt(text,(key)=>{ cb(key.toLowerCase() === "y") });
}
function log(text){
    var line;
    if(textContainer.children.length > 7){ line = textContainer.removeChild(textContainer.querySelector(".text")) }
    else{ line = Object.assign(document.createElement("div"),{className : "text"}) }
    textContainer.appendChild(line)
    line.textContent = text;
    return line;
}
body {
   background : black;
   font-size : 16px;
   color : #0f0;
.text {

}
<input type="button" id="play" value="play hangman">
<code id="textContainer">
</code>

Style

Any details or matters of style I need to address?

The style is generally good. Adding spaces after opening and before closing parentheses is a little unusual console.log( solutionSoFar.join( " " ) ) it is by no means bad. The most important aspect of code style is that you use it consistently, which you have done.
Comments should be kept to a minimum, they constitute un-vetted noise. None of your comments are needed, the code is self explanatory.
Variable declaration type

var vs const vs let - ... My basic approach was "If it needs to be global, use var, if it's not going to change, use const and if it is going to change but is not global, use let."

const
OK first const it will be the most used type of variable declaration in any good code. You used it correctly for words but missed using it for limit.
For solutionSoFar which holds an array you assign a new array each time you need. There is nothing wrong with that. But it could also have been a const and it would be declared as const solutionSoFar = []; and solutionSoFar.length = secretWord.length;' followed by solutionSoFar.fill("_");`
Doing it this way lets you keep additional references to the same array, and reduces the overall memory management overhead (in this case negligible overhead)
var V let
Using either in global scope makes no difference apart from when you can access them.
var is function scope and hoisted. The global scope can be thought of as the global function and var has scope to everything within that call. It is also hoisted to the top of the code and thus accessible at any time (however it may not yet contain a value).
let is block scoped and is not hoisted. Again the global scope like a function is contained in a block and thus let is accessible from anywhere but only after its been declared or it will throw an error (Warning let and const can not be accessed before they have been declared) .
Which to use?
The argument that block scope reduces bugs is non sequitur.
What you use is up to you. But var for global and let for functions makes no sense. I use the rule that if declared in function scope (and not a const) it should be a var
eg
function foo() {
    var funcScope;  // this is correct for function scope
    let blockScope; // This could / (should in my book) be function scope

    if (true) {
        var blockVar; // this is function scoped and should be at the top
                      // of the function
        blockScope = 0;    // Reference error blockScope is not defined
                           // The next line recreates the variable for this
                           // scope putting the name in a temporary dead zone
                           // This is a run time error and will not be
                           // thrown when parsing even in strict mode.

        let blockScope; // this is correct and is a new instance, not the
                        // same as the previouse declared blockScope
    }
}


If $target is accessible from a web browser, you need to verify that it does not have a dangerous extension.  For example, that it's not a PHP file.  Note that there are probably other dangerous extensions on your web server other than just '.php'.  For example, '.html' is a dangerous extension because of cross-site scripting type vulnerabilities.

You include a flag variable for this, but you aren't doing the checking.

$uploadit = 1; // I will change it with extension checker.

Why not use a Boolean here?

$uploadit = false; // I will change it with extension checker.

Also, it probably makes more sense to default to no and change to yes than to default to yes.

foreach($_FILES['images']['name'] as $key => $value){
    $path = $_FILES['images']['name'][$key];
    $ext = pathinfo($path, PATHINFO_EXTENSION);

Could just be

foreach ( $_FILES['images']['name'] as $key => $path ) {
    $ext = pathinfo($path, PATHINFO_EXTENSION);

In general, prefer more descriptive names than $key => $value.  In this case, I believe that $key is a numeric index, so $i or $index might be more appropriate.

$name = md5($name);

What's $name?

    if ($uploadit == 1) {

Given PHP's quirkiness, this should probably be

    if ( true === $uploadit ) {

According to the PHP date documentation,

$generate1 = md5(date('Y-m-d H:i:s:u'));

The date() function will always return '000000' for microseconds (u).

$date = new DateTime();
$generate1 = md5($date->format('Y-m-d H:i:s:u'));

Use DateTime::format() instead.

$randomizer = uniqid($name);

This does nothing for security.  Its purpose is to avoid clashes.  Note that this will put $name in the name twice.

$randomizer = $name . uniqid();

This does the same thing as the previous statement.

$name = $name . $generate1 . $randomizer;

You can write

$name .= $generate1 . $randomizer;

Not important now, but the next time you hit this situation, you might want to go with the shorter version.

Note that it is safer to put $target outside the web accessible area.  If you do that, then it is less of a concern about the extension.  If you do not do that, then you should care about the extension even if the filename is hard to guess.  It's not clear to me why you need it in a web accessible area if you are going to obfuscate the name.

Obfuscating the name does not provide security.  There have been exploits that have allowed attackers to view directory contents.  Also, there are any number of existing users that can do that.  Finally, you can't use the image without sharing the obfuscated name--possibly with an attacker.  So you might as well use the original name and secure that.

If you are trying to avoid name clashes, you might be better off with a database solution.  An autoincrement identifier with a unique index will be consistently unique and kept that way by the database.

It is preferable to whitelist extensions rather than blacklist them.  That way a change in the web server configuration can't open up a new dangerous extension when you aren't looking.

There's things you can do in either .htaccess or httpd configuration to prevent files in $target being evaluated in scripts.  For example, disable CGI.  You should probably do something like this in addition to an extension whitelist.


Is this the way of truncating the fractional part of a BigDecimal when its scale is zero in Java?

Is there a better way to do this?

Yes, stripTrailingZeros().

To check your tests:

public static void main(final String[] args) {
    check(truncate("12.000000"), "12");
    check(truncate("12.0001"), "12");
    check(truncate("12.0051"), "12.01");
    check(truncate("12.99"), "12.99");
    check(truncate("12.999"), "13");
    check(truncate("12.3456"), "12.35");
    System.out.println("if we see this message without exceptions, everything is ok");
}

private static BigDecimal truncate(final String text) {
    BigDecimal bigDecimal = new BigDecimal(text);
    if (bigDecimal.scale() > 2)
        bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
    return bigDecimal.stripTrailingZeros();
}

private static void check(final BigDecimal bigDecimal, final String string) {
    if (!bigDecimal.toString().equals(string))
        throw new IllegalStateException("not equal: " + bigDecimal + " and " + string);

}

output:

  if we see this message without exceptions, everything is ok


Java homework exercises working with 2D arrays

Your code looks well done.  Just a couple of tweaks to make it better:

Your check() method could fail if passed an empty string, "", since .charAt(0) will raise an IndexOutOfBoundsException.  Using the following to protect against the exception:

if ( ! item.isEmpty()  &&  item.charAt(0) == c ) {

In populate(), you loop up to arr.length and arr[i].length.  But you have just created that array of known dimensions m and n, so it would be clearer, simpler and slightly faster to use those variables for the loop limits.
Your variable names could be better: perhaps array instead of arr, and column instead of newarr.


Is this a proper callback implementation in Java?

Yes, that is an implementation of a callback. There are some things to note though:

Callbacks in Java are seldom called Callbacks, but rather 'events' or 'listeners' (which is why you probably found it hard to search for the concepts in Java). The most common Listeners are likely in the AWT/Swing library, like ActionListener
having a run() method on the callback is a poor choice of name, because it confuses it with the Runnable interface (which, in a sense, is a callback of sorts too).
Java8 introduces functional interfaces which allows you to extend your callback in more concise ways. You should consider it.

Using a functional interface:

If you were to use your interface, but declare it as a functional interface to make it obvious (it is not required to declare it as functional, the compiler can automatically detect it...):

@FunctionalInterface
public interface Callback {
    void run();
}

Then, in your code, you can have:

static void method (Callback callback){
    callback.run();
}

public static void main(String[] args) {
    method(() -> System.out.println("Printed!"));
}

(you can also use the anonymous class, but the functional-interface implementation is.... neater.


Chaining a number of callables into a single function

The function performs composition, so the name should be compose. Or rather reverse_compose, because it applies functions in the order reversed from natural composition.


I'm seeing several good practices in your code, you have a solid foundation to build upon. There are a few things to point out, but to answer your basic performance question -- process all your data in memory arrays. You'll see a tremendous performance improvement.

Several comments then, illustrated in the example code below:

Good declarations for your separate Worksheet variables; they are nicely descriptive.
Single-letter variables are not very descriptive (though a common practice is to restrict use of single-letter variables as loop indexes). So my suggestion is to rename these to ovRows and dataRows. These hold the number of rows detected on each sheet, so the variable name should echo that usage.
Use constants declared for fixed values. From what I can tell in your code, you have a limit to the number of columns on both sheets. Assuming this is a hard-coded value, declaring these as Const makes it easier to understand (and to change later if necessary).
Pull the overview and data ranges into local (memory-based) arrays for processing. This is the setup for the real speed.
Modify the loop to use the memory arrays. The example below is all-array, all the time. (If I've correctly understood your rows/columns logic.)
When the processing is completed, "write" the updated data back to the worksheet.

Thanks to @MacroMarc, I've updated the errors in my code (which was all done off the top of my head).

Option Explicit

Sub UpdateMatrix()
    Dim wsOverview As Worksheet, wsData As Worksheet
    Dim rngTable As Range

    Set wsOverview = ThisWorkbook.Worksheets("Sheet1")
    Set wsData = ThisWorkbook.Worksheets("Sheet2")

    Dim ovRows As Long
    Set rngTable = wsOverview.Range("A:A")
    ovRows = Application.WorksheetFunction.CountA(rngTable) + 1

    Dim dataRows As Long
    Set rngTable = wsData.Range("A:A")
    dataRows = Application.WorksheetFunction.CountA(rngTable)

    '--- set up memory based arrays
    Dim overviewRange as Range
    Dim overview As Variant
    Const OV_COL_LIMIT = 37
    set overviewRange = wsOverview.Range("A1").Resize(ovRows, COL_LIMIT)
    overview = overviewRange

    Dim dataRange As Range
    Dim data As Variant
    Const DATA_COL_LIMIT = 6
    set dataRange = wsData.Range("A1").Resize(dataRows, DATA_COL_LIMIT)
    data = dataRange

    Dim varAccount As Variant, varData As Variant
    Dim dataAcct As Variant, dataData As Variant
    For s1 = 2 To 3
        varAccount = overview(s1, 1)
        For s2 = 1 To COL_LIMIT
            varData = overview(1, s2)
            For s3 = 2 To dataRows
                dataAcct = data(s3, 2)
                dataData = data(s3, 1)
                If (varAccount = datraacct) And (varData = dataData) Then
                    overview(s1, 1) = data(s3, 6)
                    Exit For
                End If
            Next s3
        Next s2
    Next s1

    '--- put the data array back on the sheet
    overviewRange = overview
End Sub


You've got 0 validation in there, so the slightest hiccup will halt your script halfway. That's fine for you, but for a user, there will be a script that runs, crashes along the way, and then leaves all sorts of junk lying about.

You also have a "warning" for an unknown OS version, but then the os version seems to be required - without it, mppkg won't make sense and it's likely that the download will fail (unless there is a standard file, MacPorts-someversion-.pkg?). You'd be better off exiting the script then and there. Fail fast.

Lastly, the two paired curl calls

curl $uridist/$mppkg.pkg -O
curl $uridist/$mpchk.chk.txt -O

Could be ran asynchronously (see this serverfault question https://serverfault.com/questions/456490/execute-curl-requests-in-parallel-in-bash) with & and wait. That way the script would be a bit faster.


Your code is C++03 like (ie there are no move constructors or move assignment operators). You should definitely think about updating your class to be move aware.

The first thing about the interface is that the assignment operator is not close to the constructors. Since these are highly linked I like to place the assignment operators very close to the constructors (see rule of three/five).

Using _ as a prefix is a bad idea. You don't break any rules (but was this on purpose or just an accident?). The rules are sufficiently complex that prefix _ on identifiers is a bad idea for user space code. Others have suggested a prefix like m_ personally I think that is old school advice. As long as the naming is clear there should be no issues.

My personal convention with identifiers is that anything that can be an object starts with a lowercase letter. Anything that is a type begins with an uppercase letter. Others will disagree with this convention as the standard does not follow it and this can lead to other conflicts.

Here is one of those exceptions to my rules.

    typedef T* Iterator;

You should probably have iterator with a lowercase i. This is because a lot of the algorithms will use the type.

Good start.

    Iterator begin();
    Iterator end();
    T& front();
    T& back();
    T & operator[](unsigned int index);

But you will need const versions of all these (and a const_iterator type) to be a fully compliant container.

You are going to have a hard time making this work if the buffer is of type T. Every time you expand the buffer all the elements in the buffer will be initialized with T constructor. For int this is not a problem. But if T has a non trivial constructor then you are going to pay a heavy price initializing elements that may never be used.

T* buffer;

Really the buffer should be something that does not have a constructor.

char* buffer;

Prefer the initializer list.

template<class T>
Vector<T>::Vector() {
    _capacity = 0;
    _size = 0;
    buffer = 0;
    Log = 0;
}

// This will also warn about out of order initialization.
// Not a big thing but it keeps your thinking logical.

template<class T>
Vector<T>::Vector()
    : _size(0)
    , _capacity(0)
    , Log(0)
    // Personally I would always allocate some space for the buffer
    // even if the size is zero. This way I do not have to worry about
    // the special case of buffer ever being a NULL pointer.
    //
    // Having a special case of NULL will affect all the methods and make
    // the code much more complex. Reduce code complexity means easier to
    // maintain code.
    //
    , buffer(new char[sizeof(T) * capacity])
    // Note this assumes buffer is (char* as described above)
{}

Again. Use an initializer list.

template<class T>
Vector<T>::Vector(const Vector<T> & v) {
    _size = v._size;
    Log = v.Log;
    _capacity = v._capacity;

Do you really mean to allocate _size memebers to the buffer. Should this not be _capacity?

    buffer = new T[_size];

    for (unsigned int i = 0; i < _size; i++)
        buffer[i] = v.buffer[i];
}

Also use the internal algorithms to help you.

template<class T>
Vector<T>::Vector(Vector<T> const& v)
 // Note. I put cost here   ^^^^^   most of the time it does not matter.
 // There is one corner case where it does.
    : _size(v._size)
    , _capacity(v._capacity)
    , Log(v.Log)
    , buffer(new char[sizeof(T) * _capacity])
{
    for (unsigned int i = 0; i < _size; i++)
    {
        // Now you can use placement new to copy the elements from
        // source into the current vector.
        new (buffer + sizeof(T) * i) T(v[i]);
    }
}

Again use initializer list.

template<class T>
Vector<T>::Vector(unsigned int size) {
    _size = size;

This seems to be a constant. I would just make this a constant of the class and calculate it once by hand. The use of these maths functions seems a bit like overkill to me.

    Log = ceil(log((double) size) / log(2.0));
    _capacity = 1 << Log;
    buffer = new T[_capacity];
}

Personally one liners like this.

template <class T>
bool Vector<T>:: empty() const {
    return _size == 0;
}

I just put inline into the class.

The assignment operator problem has been covered by @liv902

template<class T>
Vector<T>& Vector<T>::operator = (const Vector<T> & v) {
    delete[] buffer;
    _size = v._size;
    Log = v.Log;
    _capacity = v._capacity;
    buffer = new T [_capacity];
    for (unsigned int i = 0; i < _size; i++)
        buffer[i] = v.buffer[i];
    return *this;
}

Basically you should not change the state of your object until you have guranteed that there are no expceptions can be thrown and leave your object in an incosistent state. This means your assignemnt should proceed in three stages.

Copy the state of the src class into temporary objects.
This is because making the copy can throw an exception and thus you should not put your object into a state wheere it can be invalid.
Swap the state of you object with the temporary values.
Swapping is an exception safe operation.
Now you can destroy the old state (which is in the temporary values).
This can also throw an exception, but your object will be in a consistent state.

This techniques means you provide the "Strong (Transaction) Exception Guarantee" (You can look it up in google).

The easiest way to implement the above is to use the "Copy and Swap Idiom".

When you remove something from a std::vector.

template<class T>
void Vector<T>::pop_back() {
    _size--;
}

The destructor for that object is also called. This allows you free resources for non trivial resources (say T was a std::shared_ptr<int>) not calling the destructor means you are effectively retaining a reference to an object that could be freed.

It is perfectly valid to manually call the destructor of an object (In fact this is very normal when pared with placement new operation).

template<class T>
void Vector<T>::pop_back() {

    // You way want to do a check for empty() before calling the destructor.

    // Call the destructor.
    (reinterpret_cast<T*>(buffer)[_size-1]).~T();

    // It is usual to prefer the pre decrement (and pre increment).
    --_size;
}

Just like a pop.
When you clear a vector you generally expect the destructor to all the members to be called.

template <class T>
void Vector<T>::clear() {
    _capacity = 0;
    _size = 0;
    buffer = 0;
    Log = 0;
}


Creating a form based on flight intentory

Suggested changes

Formatting. Typically you want to use TSLint, and possible also Prettier. I've ran your code through Prettier with the standard configuration. (Note that the point is consistency and readability. It doesn't matter if you want to use ' or ", tabs or spaces, etc)
this.messagePrefix ? this.messagePrefix : "" can be simplified as this.messagePrefix || ""
Looking at your code, it looks like we want to assign different values to message and validator depending on the values of this.flight.inventory.code. So lets keep everything else the same rather than having separate code paths. If we were to keep the current structure, then we should at least put the first assignment to this.formGroup in an else block, so we don't assign it twice.


Communicating events between entity components with minimal code overhead

You have one big problem with this design. It's easiest to explain the problem with the example.

So, let's say you add a new feature where you can issue a speak message. You'll need to add SpeakMessage and SpeakComponent classes. SpeakComponent would have public void Message(SpeakMessage message) method.

In this scenario, when someone calls your IssueMovement method, it will call SendMessage method which in turn will iterate over _components (which now contains MoveComponent and SpeakComponent) and try to call their Message method that has one argument of type MovementMessage. Since SpeakComponent doesn't have that method, it will throw an exception. The only way to avoid that with your current design is to have your component classes each handle every message in the system which is not what you would want to do.

So, to improve your design, your entity will need to know which component handles which message. The best way to do it, IMO, is to have an interface IMessageComponent<T> where T: IComponentMessage with a single method void Message(T componentMessage). MoveComponent would then implement IMessageComponent<MoveMessage> and SpeakComponent would implement IMessageComponent<SpeakMessage>.

Your SendMessage method inside the entity would then become:

public void SendMessage<T>(T message) {
  _components.OfType<IMessageComponent<T>>().ForEach(x => x.Message(message));
}

If you want one component to handle more than one message type (although, that would violate SRP), your component could implement multiple IMessageComponent<T> interfaces with different message classes.


Extracting the five most frequent queries from a log file

Your names could be improved, e.g. hm isn't a good name for a member variable.

You could replace the HashMap by a multiset implementation, e.g. HashMultiset from Google Guava. Then you get putWord for free.

The Comparator (and its Map) should be generified. Further, it seems to be plain wrong, as it never gives 0 as result of compare, but that is the expected outcome if two values are "equal" (whatever this means in the actual context). Without looking too deep in the code, it might even be that a simple priority queue could replace all the Comparator and TreeMap stuff.

The main method is too long and should be split in logical parts. Probably it would be better to avoid static methods, but to create a Topfive instance which does most of the work.

If you can use Java 7, try out the ARM block feature for your file access.

For your question you used the tag "clean code", but it looks like you didn't read the book by Uncle Bob. Check it out!

[Edit]

Based on your clarification I would write the class as follows:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;

public class TopWords {
    private final SortedSet<Freq> frequencies = new TreeSet<Freq>();

    public TopWords(File file)
            throws IOException {
        List<String> wordList = readWords(file);
        Map<String, Integer> freqMap = getFrequencies(wordList);
        sortFrequencies(freqMap);
    }

    public SortedSet<Freq> getFrequencies() {
        return frequencies;
    }

    private List<String> readWords(File file) throws IOException {
        List<String> result = new ArrayList<String>();
        BufferedReader br = new BufferedReader(new FileReader(file));
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            result.add(line);
        }
        return result;
    }

    private Map<String, Integer> getFrequencies(List<String> wordList) throws IOException {
        Map<String, Integer> freqMap = new HashMap<String, Integer>();
        for (String line : wordList) {
            int start = line.indexOf("query=") + 6;
            int end = line.length() - 1;
            String word = line.substring(start, end).trim();
            Integer frequency = freqMap.get(word);
            freqMap.put(word, frequency == null ? 1 : frequency + 1);
        }
        return freqMap;
    }

    private void sortFrequencies(Map<String, Integer> freqMap) {
        for (Entry<String, Integer> entry : freqMap.entrySet()) {
            frequencies.add(new Freq(entry.getKey(), entry.getValue()));
        }
    }

    public List<String> getTop(int count) {
        List<String> result = new ArrayList<String>(count);
        for (Freq freq : frequencies) {
            if (count-- == 0) {
                break;
            }
            result.add(freq.word);
        }
        return result;
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            try {
                TopWords topFive = new TopWords(new File(args[0]));
                List<String> topList = topFive.getTop(5);
                for (String word : topList) {
                    System.out.println(word);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class Freq implements Comparable<Freq> {
        public final String word;
        public final int frequency;

        private Freq(String word, int frequency) {
            this.word = word;
            this.frequency = frequency;
        }

        public int compareTo(Freq that) {
            int result = that.frequency - this.frequency;
            return result != 0 ? result : that.word.compareTo(this.word);
        }
    }
}

Of course this might be suboptimal depending on the intended use, but I think you get the general idea.

[Update]

After some meditation I came to the conclusion that I thought way too complicated. Try the following version:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TopWords {

    private final List<Freq> frequencies = new ArrayList<Freq>();

    public TopWords(File file)
            throws IOException {
        List<String> wordList = getSortedWordList(file);
        sortFrequencies(wordList);
    }

    public List<Freq> getFrequencies() {
        return frequencies;
    }

    private List<String> getSortedWordList(File file) throws IOException {
        List<String> result = new ArrayList<String>();
        BufferedReader br = new BufferedReader(new FileReader(file));
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            int start = line.indexOf("query=") + 6;
            int end = line.length() - 1;
            String word = line.substring(start, end).trim();
            result.add(word);
        }
        br.close();
        Collections.sort(result);
        return result;
    }

    private void sortFrequencies(List<String> wordList) {
        String lastWord = null;
        int count = 0;
        for (String word : wordList) {
            if (word.equals(lastWord)) {
                count++;
            } else {
                if (lastWord != null) {
                    frequencies.add(new Freq(lastWord, count));
                }
                lastWord = word;
                count = 1;
            }
        }
        if (lastWord != null) {
           frequencies.add(new Freq(lastWord, count));
        }
        Collections.sort(frequencies);
    }

    public List<Freq> getTop(int count) {
        return frequencies.subList(0, Math.min(frequencies.size(), count));
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            try {
                TopWords topFive = new TopWords(new File(args[0]));
                List<Freq> topList = topFive.getTop(5);
                for (Freq freq : topList) {
                    System.out.println(freq.word + " " + freq.frequency);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class Freq implements Comparable<Freq> {

        public final String word;
        public final int frequency;

        private Freq(String word, int frequency) {
            this.word = word;
            this.frequency = frequency;
        }

        public int compareTo(Freq that) {
            int result = that.frequency - this.frequency;
            return result != 0 ? result : that.word.compareTo(this.word);
        }
    }
}


I have some suggestions to improve your code:

Formatting

You should use empty lines consistently. E.g. you have some ifs/else ifs blocks where you put an empty line at the beginning but not everywhere. I suggest you to not use empty lines there at all.
You should not use more than two empty lines to seperate things. It's harder to read.
You should put empty lines between logically grouped things. E.g. your #include statements, the using statement and the wrapUp function are glued together.
In general try to group things visually that belong together. In the wrapUp function the two empty lines are seperating the ending curly bracket from the function for no reason.
You should not put a newline as first thing you print in a line, e.g. cout << '\n' << "Number of Lives: " << livesTracker << endl;. And you should not mixup '\n' and endl.

Naming

You should name variables more precisely. player should be named playerGuess. This will make it much clearer what the variable is for. You may ask why this is relevant because you know it already but be aware of other developers. Just by putting that Guess at the end will remove the amount of time someone has to put in finding out stuff. Some other variables could use better naming as well, like roundh or livesTracker.
I think wrapUp does not describe well enough what it's doing. (That one is kinda personal taste.)

Functional

It's strange to put the game logic in a for loop and decrement the iterator to continue with the game. I know, I know, it works, but this is not the usual way to use a for loop. A while loop does fit here much better. When you connect the while loop to the amount of lifes left, you will have a much more readable code, e.g. while (amountOfLifes > 0) {// continue with the game}.
The game logic for the normal game and the hard mode is very similar. You can put it in a method and use parameters, e.g. to individualize the range for the random number to guess.

Here is an example of how the program could look like when you apply my suggestions. It doesn't need to be exactly like that. Please note that I didn't double check everything and I changed some of the logic but I hope you get an overall idea about what is improvable:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

void printSeperator() {
    cout << "-------------------------------------------------" << endl;
}

bool guess(int& lifesCounter, int numberToGuess, int round, int upperRandomLimit) {
    cout << "Guess the number that will come up on the screen from 1 to " << upperRandomLimit << ": ";
    int playerGuess;
    cin >> playerGuess;

    if (playerGuess == numberToGuess) {
        cout << "You won round " << round << "!" << endl;
        printSeperator();
        return true;
    }
    else if (playerGuess > numberToGuess) {
        cout << "Your guess was too high, round " << round << "!" << endl;
        printSeperator();
        lifesCounter--;
        cout << "Number of Lives: " << lifesCounter << endl;
    }
    else {
        cout << "Your guess was too low, round " << round << "!" << endl;
        printSeperator();
        lifesCounter--;
        cout << "Number of Lives: " << lifesCounter << endl;
    }
    return false;
}

bool playRounds(int& lifesCounter, int upperRandomLimit) {
    int numberToGuess;
    for (int round = 1; round < 3; round++) {
        numberToGuess = 1 + (rand() % upperRandomLimit);
        while (!guess(lifesCounter, numberToGuess, round, upperRandomLimit)) {
            if (lifesCounter == 0) {
                cout << "Game Over! Actual Answer: " << numberToGuess << endl;
                return false;
            }
        }
    }
    return true;
}

int main() {
    srand(time(0));
    string playerNamer;
    int lifesCounter = 5;

    cout << "Hello, what is your name? ";
    cin >> playerNamer;
    cout << "Welcome to guess the number, " << playerNamer << "!" << endl;
    printSeperator();
    cout << "Number of lifes you have: " << lifesCounter << endl;

    if (!playRounds(lifesCounter, 10)) {
        return 0;
    }
    lifesCounter += 5;
    cout << "You got more lifes! Now you have: " << lifesCounter << endl;
    cout << "For the hard level, you have to guess a number from 15!" << endl;
    playRounds(lifesCounter, 15);
    return 0;
}

P.S.: It's very hard to win when you have just 5 lifes for all 4 guesses. ¯\_(ツ)_/¯


Keep database lookup in memory and get values in frequent

Some quick notes:

LUApplicationParams is not a good method name. It doesn't tell me what it does, and moreover it isn't even a verb.
m_LUApplicationParams isn't a good name for a field or property. I'm not a fan of the "m_" naming, it contains an obscure abbreviation or acronym (LU), and it doesn't tell me what it contains, which is especially bad considering this is a Dictionary<string, Dictionary<string, string>>.
I'd move all of the logic inside if (m_LUApplicationParams == null) to a separate method. I even wonder whether this would be the right place for such logic (although I have done such things myself).
blLU doesn't tell me anything, even when it is used like var blLU = new LU();.
Why do you do DataTable dt = new DataTable();? It's pointless since the next line assigns a value to dt anyway.
"LangId" is used three times. Suppose you ever need to change it: wouldn't it be handier if it were a constant?
dt.Rows[i]["LangId"].ToString() is used three times: then why not assign it to a variable?
GuidId is a parameter and thus should be CamelCase. But is GuidId even a proper name, considering that the other code suggests it is actually an id to identify the langhuage: "LangId"?
What does variable represent? Even the field name isn't helping, since that is "Variable" also. I'd hate to be the next person to maintain this code since obviously a lot of information is missing from it.
You do .FirstOrDefault() and then immediately use the .Value of the result; but what if there is no value?
Also, .FirstOrDefault() suggests multiple values are possible, is that a possibility you want? And why would the first result be the correct one?
Why do you do .ToString() to the result of .FirstOrDefault().Value? Why do you fear that the value of a Dictionary<string, string> key-value pair wouldn't be a string?
You do .Where and then .FirstOrDefault: replace this by .FirstOrDefault(y => y.Key == variable).

If you need to fetch a specific value from a DataRow, why not extract such code to a method?

private string GetValue(DataRow row, string key)
{
    return row[key].ToString();
}

Avoid doing Dictionary.ContainsKey: if you need to use the value of said key, use Dictionary<TKey, TValue>.TryGetValue.

var row = dt.Rows[i];
var languageId = GetValue(row, "LangId");

Dictionary<string,string>() contentByVariable;
if(!m_LUApplicationParams.TryGetValue(languageId, out contentByVariable))
{
    contentByVariable = new Dictionary<string,string>();
}

contentByVariable.Add(GetValue(row, "Variable"), GetValue(row, "Content"));
m_LUApplicationParams[languageId] = contentByVariable;

But if I were you I'd rethink this entire logic. A Dictionary<string, Dictionary<string, string>> is ugly and unwieldy; IMHO the nested dictionary should be a custom class.

I also feel this code is odd and possible buggy: data is retrieved for an applicationId yet this parameter is completely absent in m_LUApplicationParams. The GuidId that is passed is assumed to be present as a key in m_LUApplicationParams, same for the variable.


Including file based on user input: Efficiency and Security

Assuming nobody but you can place files in the directory, this will be safe because you are checking the input page against a pre-defined list of page files. Additionally, this code makes the white list dynamic and throws an exception if the page is not found.

As @tim said in the comment, he found this code to be about 5 times slower then yours. So that's good to keep in mind if you ever decide to use this.

Every .php page you put in the pages/ directory will automatically be callable.

if (isset($_GET['p'])) {
    $page  = $_GET['p'] . '.php';
    $pages = array_map('basename', glob('pages/*.php'));

    if (in_array($page, $pages)) {
        include('pages/' . $page);
    } else {
        throw new Exception('Page "' . $page . '" does not exist.');
    }
} else {
    echo 'Hi';
}


You're right to suspect that using eval stinks: it really does.

You can define the values of grades as tuples of functions and a parameter:

def greater_than_or_equal(score, x):
    return score >= x

def less_than(score, x):
    return score < x

grades = {
    'A': (greater_than_or_equal, 0.9),
    'B': (greater_than_or_equal, 0.8),
    'C': (greater_than_or_equal, 0.7),
    'D': (greater_than_or_equal, 0.6),
    'F': (less_than, 0.6),
}

Now you can write a get_grade function that returns the correct grade using the evaluator and a parameter:

def get_grade(score):
    for key in sorted(grades):
        evaluator, param = grades[key]
        if evaluator(score, param):
            return key

I converted the code that just prints the key and quits to a function,
so that you can verify the correct behavior using assertions:

assert 'F' == get_grade(0.1)
assert 'F' == get_grade(0.5)
assert 'D' == get_grade(0.6)
assert 'D' == get_grade(0.61)
assert 'C' == get_grade(0.7)
assert 'B' == get_grade(0.8)
assert 'A' == get_grade(0.9)
assert 'A' == get_grade(0.91)
assert 'A' == get_grade(1)

Actually, using a dictionary for grades doesn't make a lot of sense.
It could be just a list of tuples in the correct order so that you can even skip the sorting step:

grade_evaluators = (
    (greater_than_or_equal, 0.9, 'A'),
    (greater_than_or_equal, 0.8, 'B'),
    (greater_than_or_equal, 0.7, 'C'),
    (greater_than_or_equal, 0.6, 'D'),
    (less_than, 0.6, 'F'),
)

def get_grade(score):
    for evaluator, param, grade in grade_evaluators:
        if evaluator(score, param):
            return grade


Count swaps needed to order a list of integers

I don't have time to really look at the code well or do a full review, but what did stick out to me was the repeated calls to arr.index(i). That's an expensive call that will require, in the worst case, a full iteration of arr each time.

At the very least, that call should be done once then cached. Really though, that information is already available to you without searching if you use enumerate:

def minimum_swaps(arr):
    count = 0
    correct = [(x+1) for x in range(len(arr))]
    while arr != correct:
        for i, x in enumerate(arr):  # I changed what was i to x, then made i the index
            if x != i+1:
                a = x
                b = arr[x-1]
                arr[x-1] = a
                arr[i] = b
                count += 1
                break

    return count

I also renamed some variables. i is an awful name for an element that isn't itself an index, and the function name should be in snake_case instead.


Finding the names of students with the second-lowest score

Your code seems reasonable, if you consider the use of nested lists to be a requirement.  It is clearly written enough that you could just omit most or even all of the comments.  You could simplify the determination of the second-lowest score using itertools.groupby().

It is customary to use _ as the name of a "throw-away" variable whose value will never be used, such as studentrecord in

students = [[input(), float(input())] for studentrecord in range(n)]

I wouldn't blame Python for being the wrong language for this challenge.  Rather, the advice to use nested lists is poor.  This problem would be much more naturally solved if you classified the students by their score.  That would be easily accomplished using a dictionary, specifically a defaultdict(list).

from collections import defaultdict

students_by_score = defaultdict(list)
for _ in range(int(input())):
    name = input()
    score = float(input())
    students_by_score[score].append(name)

second_lowest_score = sorted(students_by_score)[1]
for student_name in sorted(students_by_score[second_lowest_score]):
    print(student_name)

If I had to use a nested list in the solution, I'd still convert it to a dictionary first.  =)

Furthermore, I would consider a list of tuples to be more appropriate than a list of lists for this situation.  A list is good for homogeneous data of variable length.  A tuple, on the other hand, has a connotation of being a fixed number of elements, possibly of different data types.  (Tuples in Python also happen to be immutable.)  Although the nested list works just fine, and the Python interpreter doesn't care, I would choose tuples here because they would convey the right connotation.