Hackerrank challenge - Dictionaries and Maps in Erlang

There are two things you can do differently that would help:

read all the input at once, and then process it
store values such that they can be output directly, without formatting

The code below first reads all the input in chunks of 4096 characters, accumulating a list of chunks. It then reverses the list, flattens the list into a large string, and splits the entire string on newlines. After that, it converts the first element of the resulting list to an integer N, and then processes N names and numbers from the remainder of the list by storing them in a map. The value stored isn't just the phone number, but the required output string "<name>=<number>\n". Once all the entries have been processed, the rest of the input is queries, which are then processed one-by-one against the map. Query processing uses maps:get/3 with the string "Not found" used as the default for lookups that fail. This allows the return value from maps:get/3 to be unconditionally output directly to stdout.

-module(solution).
-export([main/0]).

main() ->
    queries(store(read_all())).

read_all() ->
    read_all([], io:get_chars("", 4096)).
read_all(In, eof) ->
    [H|T] = string:tokens(lists:flatten(lists:reverse(In)), "\n"),
    {list_to_integer(H), T};
read_all(In, Data) ->
    read_all([Data|In], io:get_chars("", 4096)).

store(Data) ->
    store(Data, #{}).
store({0, Queries}, M) ->
    {Queries, M};
store({N, [Name,Number|T]}, M) ->
    store({N-1, T}, maps:put(Name, lists:flatten([Name,"=",Number,"\n"]), M)).

queries({[], _}) ->
    ok;
queries({[Query|Queries], M}) ->
    io:put_chars(maps:get(Query, M, "Not found\n")),
    queries({Queries, M}).

I created an input file containing 9000 entries to be stored and used it to measure this solution to be about 150 times faster than solutions that read the input line by line, as measured by running the solution on the command line in a bash shell like this:

time erl -noshell -s solution main -s init stop < input

and subtracting out the overhead of starting and stopping the Erlang VM, measured like this:

time erl -noinput -s init stop

On my machine, this overhead is ~1.20s. The original solution for input with 9000 entries and 3 lookups takes ~6.25s, while the solution I've posted here runs in ~1.23s, which means it imposes hardly any overhead over that of the VM startup and shutdown.


Presumably, once a duplicate is found you don't need to continue looping:

if (attachments.attachments[j].name === acceptedFiles[i].name) {
    duplicate = true;
}

With JavaScript, the best thing would be to wrap up your for loops in a function:

function containsDuplicate(acceptedFiles, attachments) {
    for (var i = 0; i < acceptedFiles.length; i++) {
        for (var j = 0; j < attachments.attachments.length; j++) {
            if (attachments.attachments[j].name === acceptedFiles[i].name) {
                return true;
            }
        }
    }
    return false;
}

As this is a problem that applies to multiple languages, look at the break keyword.


Retrieving database values through properties

Properties in Standard Modules

Standard modules can have Properties, but as @Rubberduck pointed out, they're not necessarily intuitive (although they do force you to qualify a call with the module name, so there's that as a redeeming quality). You could write public methods instead, but you could also create a class, and if you wanted to avoid the need to New it up, you could give that class a Predeclared attribute.  A class would better reflect the stateful nature of the settings, and would give you the flexibility of abstracting the persistence of settings from the retrieval and usage of settings.

Right now, your approach looks up the value from the underlying table every time, and writes it to the table every time. That's time consuming disk access and page locking. It might be better to load the settings on demand, use/change the settings, and then save them on exit.

Variable Names

pValue is presumably short for parameterValue. Why not use the full name, or better still, something like keyName? pValue could be confused for the statistical term P-Value, or a user might infer that the p is Hungarian notation, but guess at what type that notation represents.

SQL Injection

Kudos for using the StringFormat (presumably from @Mat'sMug's CR question), but you're building a SQL statement on the fly, and a malicious user, or inadvertent user could cause an error, or worse, by providing a parameter with a single-quote in the pValue. What happens if the user supplied "', AdminMode = TRUE, AdminName = '"?

At the very least, sanitize your inputs. Better still, parameterize your queries and leave a sign up saying that Johnny DropTables isn't welcome.

LateBound `PageFrame` property

You're explicitly returning an Object, which forces usage of the property to be late-bound. You probably know the type of the return value, why not use it?

If you know the return-type will always be an instance of InnserSubForm, then return that type:

Public Property Get PageFrame() As Form_InnerSubForm
    Set PageFrame = Forms.frmMain.SubForm.Form.InnerSubForm
End Property

If the subform is set dynamically, and you only know the return type will be a Form, then return that base type:

Public Property Get PageFrame() As Access.Form
    Set PageFrame = Forms.frmMain.SubForm.Form.InnerSubForm
End Property

Clarifying the Form type

Access has built-in Form objects, but also allows the use of VBA UserForms. It might be helpful to qualify the type as Access.Form:

Public Property Get Page() As Access.Form

Be careful with properties matching built-in control names

Page is the name of a built-in type, but you're using it to return a Form. That might be confusing for users of the property.

Accessing the `Forms` object

The Forms object extends the names of open forms at run-time. That means you're using late-bound code and you're not getting any Intellisense. Worse still, if the form isn't open, or it's in the wrong state, the call will fail. At the very least, you should have some error handling.

Using the default instance of the form

Access creates a default predeclared instance of a form (much like VBA creates a default predeclared instance of a UserForm), but Access only does this if the form is open. However, it is also possible to create instances of the Access form (and, I'd argue, is the preferable way to deal with Forms and UserForms).

Your code is intimately tied to the default instance, and should perhaps be made capable of handling any instance of the form. See this example to see how a form with a default caption of "foo" is handled by VBA:

  Dim frm As Form_frmMain
  Set frm = New Form_frmMain

  frm.Caption = "Bar"

  'Print the current instance's caption - Bar
  Debug.Print frm.Caption

  'Print the early-bound default instance's caption - Foo
  Debug.Print Form_frmMain.Caption

  'Print the late-bound default instance's caption - Foo
  Debug.Print Forms.frmmain.Caption

`CurrentDb` is a function used like an object

CurrentDB is a function that returns a pointer to a Database. It's a member of the Application class, but note this text from an old KB article:

  The following example attempts to use the CurrentDb function to return a
  pointer to the database that is currently open in Microsoft Access. Because
  the code does not assign that database to an object variable, the pointer
  returned by the CurrentDb function is temporary and becomes invalid after
  the TableDef object is set. Consequently, any later references in your code
  to the TableDef object variable will result in an error.

That is, usage of Database members against CurrentDB, like CurrentDB.Execute or, more correctly, CurrentDB().Execute can be unreliable and result in error Object Invalid or Not Set. You'll have more reliable code if you first assign the result of CurrentDB() to a local variable, and then access the Execute method from that variable.

Dim db As Database
Set db = Application.CurrentDb()
db.Execute StringFormat("UPDATE WmSettings SET [_ActiveKey]='{0}';", pValue), dbFailOnError


You should first do OrderBy and then you should do ThenBy instead of doing another OrderBy. What you are currently doing is that you are re-ordering everything after your first OrderBy.

public IEnumerable<ReadingValue> Hourly(IList<ReadingValue> readings)
{
    var sortedReadings = readings.OrderBy(x => x.DateTimeOfReading.TimeOfDay)
        .ThenBy(x => x.DateTimeOfReading.Date)
        .ThenBy(x => x.DateTimeOfReading.Year);

    return sortedReadings;
}


Is it needed to "beautify" this Stack implementation?

class Stack

Stack (or any other collection) is a prime example of type that should be generic.

private int _length;

I think length is not a good name for this. You should rename it to something like _maxLength, or even better, _maxCount (see below).

Also, I'm not completely sure if this feature is necessary, but it could make sense (for example System.Collections.Generic.Stack<T> doesn't have anything like this, but System.Collections.Concurrent.BlockingCollection<T> does).

_length = 10;

I don't think 10 is a reasonable default here. It would certainly be unexpected to me. A much better default would be infinity. Or maybe don't have a default at all.

public List<int> Members

Unless absolutely necessary, you should never expose private implementation details like this. Using this member, anyone can do anything to the underlying collection (including adding items beyond the allowed maximum number).

If you want to be able to iterate over the items in the collection, you should implement IEnumerable<T>.

public int Length

The name Length makes some sense for arrays, but not so much for other collections. For consistency with other collections, the best name would be Count.

return (_members.Count == 0);

The parentheses are not necessary here.

if (_members.Count < _length) _members.Add(member);
else throw new Exception("The Stack is full.");

You probably shouldn't write the body of if and else on the same line like this. Putting them on a line of their own will make your code clearer to read.

throw new Exception("The Stack is full.")

You shouldn't throw Exception directly, you should create your own type that inherits from Exception and throw that. Alternatively, you could use an existing exception type, like InvalidOperationException.

if (!IsEmpty)
{
    …
}
else throw new Exception("The Stack is empty.");

You could simplify this by reversing the condition and putting the exception first. This way, the main code will be less indented.

public partial class Form1 : Form

You should name your forms with more descriptive names, even if it's something as simple as MainForm.

lbStack

This form of Hungarian notation is usually frowned on. If you want to indicate that the variable is a list box, you can name is something like stackListBox.

(int)rnd.Next()

You don't need a cast here, Next() already returns an int.


String manipulation with std::adjacent_find

First impressions: nicely presented code; good use of the appropriate standard library functions and classes.

A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>).  Perhaps call it compress?

I'd suggest extracting the constant 3 to give it a meaningful name.

Can we eliminate the break with some reorganisation of the loop?  Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()?  (I haven't fully thought that through; it might not be better.)

We can avoid constructing a new string here:

        result += std::string(dist, *it);

by using the overload of append() that takes two iterators:

        result.append(dist, *it);


You should use an ENUM or a class for the list of commands.

E.G:

public ENUM Command
{
    private String value;

    SUMMON("Summon"),
    ATTACK("Attack"),
    HEAL("Heal")

    public Command(String value) { this.value = value; };
}

// String cmd = Commands.valueOf(sc.next());
// if (cmd == Command.HEAL) ...
// ( Or better yet, use a switch statement)

You should also be dealing with invalid input. (E.g in the default of the switch).

You've mentioned Magic the gathering, but your class name is Yugioh. As we all know, those are two very different games.

The variable 'health' is declared twice, I don't think the name makes sense for 'Summon'.

The case for 'Heal' looks overly complicated. You shouldn't need to create a 'newQueue'. Try to take away X amount of health for each item (either using a for-loop or lambdas). No need to re-order the queue.


Dijkstra in C++ to find shortest path for every vertex of a directed graph

I'm sure it'll be fairly easy for you to confirm if your code is working (you can find test cases all over the place), so I'm not looking too closely at correctness, so much as overall logic.

So, on the whole, it seems to make logical sense, but it's not an efficient implementation of Dijkstra. As you know, Dijkstra's algorithm involves having an ever increasing collection of nodes and picking the smallest path out of your collection (it's that simple).

The main flaw is in your minDistance() method. What you're doing there is effectively iterating over all the nodes you've selected and finding the shortest part out. That's an O(n) operation. This step in Dijkstra is crucial and should be done in O(log N) time. This can be done using a set or a heap. Since you always want the minimum path out, all you need to do is keep track of the paths out and pick the min at each stage.

As I mentioned, you can do this with a set/heap. I think this example should help clear this up.


In this code:

if len(addr) <= 8:
    val = int(addr, 16)
    if val <= (1 << 16):  # val <= 0xffff (ie: first 64k)
        return True
elif addr.startswith('ffffffff'):
    addr = addr[8:]  # 8 == len('ffffffff')
    val = int(addr, 16)
    if val >= ((1 << 32) - (1 << 16)):  # val >= 0xffffffffffff0000 (ie: last 64k)
        return True

You can replace the inner if statements with return statements:

if len(addr) <= 8:
    val = int(addr, 16)
    return val <= (1 << 16)  # val <= 0xffff (ie: first 64k)
elif addr.startswith('ffffffff'):
    addr = addr[8:]  # 8 == len('ffffffff')
    val = int(addr, 16)
    return val >= ((1 << 32) - (1 << 16))  # val >= 0xffffffffffff0000 (ie: last 64k)

This is possible because if these conditions are false,
the execution will reach the return False at the end of the function.
The reason to rewrite this way is so that the reader doesn't have to follow the execution path until the end of the function,
he can know on these lines that no further statements will be executed,
the return value is already decided at these points.

Some of the comments are incorrect and misleading:

if val <= (1 << 16):  # val <= 0xffff (ie: first 64k)

if val >= ((1 << 32) - (1 << 16)):  # val >= 0xffffffffffff0000 (ie: last 64k)

1 << 16 is 0x10000, not 0xffff.

(1 << 32) - (1 << 16) is 0xffff0000, not 0xffffffffffff0000.

Following the naming conventions of Python,
the function isweird should be named is_weird instead.


Obtaining all repeated characters' position in a string using Java Stream API

You do not need encodeString and you do not even need a Pair class. You only use this method to build a list of each index with the character of the string at that index. Instead, you can directly use an IntStream that will go over the indexes of each character of the String.

Map<Character, List<Integer>> map =
    IntStream.range(0, str.length())
             .boxed()
             .collect(Collectors.groupingBy(str::charAt, HashMap::new, Collectors.toList()));

This creates an IntStream going from 0 to the length of the String (excluded). We turn this primitive Stream into a Stream<Integer> using boxed: we will need to box each index to store them in a list anyway, and having a Stream of objects enable us to use the built-in groupingBy(classifier, mapFactory, downstream) collector.

This collector groups each element of the Stream by the classifier given. In this case, the classifier is a function returning the character at the index considered. It is using the method-reference str::charAt (which would be equivalent to the lambda expression i -> str.charAt(i)). The downstream collector is used to collect all elements that are classified to the same key; in this case, it is simply toList() which will collect the indexes into a list. By default, groupingBy isn't specified to return a specific Map implementation (the current Oracle JDK returns a HashMap but that cannot be relied upon). Since we're going to post-process that map, giving HashMap::new as the map supplier makes sure that we end up with a HashMap.

The Stream API doesn't offer a way to do a GROUP BY HAVING, like we would like here (in SQL jargon), so 2 passes are needed. The second one can be simplified though: instead of creating a new Stream pipeline, we can use

map.values().removeIf(l -> l.size() <= 1);

to remove every entry from the map where the value is a list that has a size less than 1. This works because values() returns a view of the map, so changes to it reflect through the map. And then removeIf gives us the ability to remove the elements matching the given predicate.

So all in all, you can have:

public static Map<Character,List<Integer>> charMaps(String str) {
    Map<Character, List<Integer>> map =
        IntStream.range(0, str.length())
                 .boxed()
                 .collect(Collectors.groupingBy(str::charAt, HashMap::new, Collectors.toList()));
    map.values().removeIf(l -> l.size() <= 1);
    return map;
}


Strings have a .zip() method; calling .toList() is superfluous.

Instead of .filter(…) and .length(), use .count(…).

I'm not a fan of the name current, which has a connotation of iteration.

Avoid omitting braces with if statements.  If you want to do so, put the body on the same line to avoid accidents.

object Hamming {
  def compute(s1: String, s2: String): Int = {
    if (s1.length != s2.length) throw new IllegalArgumentException()
    s1.zip(s2).count(pair => pair._1 != pair._2)
  }
}


Linking to an image asset from a JavaScript file in Symfony 2

There might be a better way to retrieve the web directory, I would not know. However, there are other things to ponder upon.

Naming : loadBkrndImg -> loadBackgroundImage looks so much better
Naming : currentBkrndImgNum, enough said..
The background image number ought to be a parameter to loadBackgroundImage, not a global
You are creating an Image() object, assign the src value ( which can trigger the loading of the image ) , and then throw away the image. You could just put the url in a string.
You could preemptively centralize the retrieval of the asset folder

I would counter-suggest the following :

function getAssetFolder( subfolder )
{
  var folder = '/bundles/macppages/';
  return subFolder ? ( folder + subfolder + "/" ) : folder
}

function loadBackgroundImage( number )
{
  var url = getAssetFolder( 'images' ) + 'bkrnd.0' + number + '.jpg';
  $('body').css("background-image","url('" + url + "')");
}


This doesn't look like a Sieve of Eratosthenes.  This sure looks like trial division:

  while(numbersIterator.hasNext()){
      int number = numbersIterator.next();
      if(number % prime == 0){ //Remove all multiples of the number.
          numbersIterator.remove();
      }
  }

Unless I'm misunderstanding what your iterators are doing.  A simple SoE will have something that looks like:

for i from 2 to sqrt(n):          /* Loop from 2 to square root of max */
  if A[i]:                        /* If this location indicates prime, */
    for j from i*i to n step i:   /* then for each multiple of i,      */
      A[j] = false;               /* mark composite                    */

See the examples at RosettaCode or Wikipedia for example.  For comparison, RosettaCode's Trial Division task has a loop like your function.

So the immediate performance issue is that a sieve will be much faster than trial division.


From the design perspective, I see these possible conceptual problems:

The data structure doesn't help in determining if the required invariant holds or not.
Tree holds information that is outside of its scope - its level in the tree. This means, among other things, that a node can't be shared between multiple trees, which is something you want when manipulating trees (a new tree is just a slightly modified version of an old one, sharing most of its nodes).
Your design focuses only on creating a tree from a list. If you don't need any other operations, that's fine, but if you want to do more operations later, like insertion/deletion, merging trees, etc., it's going to be problematic. In particular, for some operations, when the total height of the tree must change, you'll have to update the whole tree. Most likely, it'd be possible to find an arbitrarily long sequence of operations, each taking O(n) time (where n is the number of nodes in the tree).

All these problems relate to having the node's level in Tree, which is currently sort-of unused. If instead you kept there the height of the subtree rooted at a node, you would be able to:

Easily check that a function keeps the required invariant when creating/manipulating nodes.
Each Tree value would be self-contained, depending only on its own subtree, thus can be shared within multiple trees.
Following from 2., you can implement the operations on trees in such a way that each takes just O(log n).

Also I'd suggest you to have a look at various balanced tree implementations (unless you want to explore it yourself, which is a good exercise).

On the other hand, if your aim is only to have a balanced tree, without the need of modifying it later, you could somewhat relax your requirement, and just require that the height of the tree is at most 1+log{2} n. Then you'd be able to create the tree incrementally, without knowing the total length of the input list: at a particular point, the algorithm tries to fill a node of height h. If it's full and there are more incoming data, it starts to build another node of height h+1. So the left subtree will be always a full binary tree.

From the syntactical point of view, it's very good that you annotate all functions with their
types, the only thing I'd improve is to have a fixed line length limit to increase readability.


Find the combination of matches which are closest to each other

A few things I noticed while looking over the code:

You don't need the import scala.math.Ordering._ statement. It's not buying you anything.
It would be easier to read/follow the code if you used better variable names.
12345 actually isn't a very big Int. Int.MaxValue would be better.
If this val size = args(0).toInt is zero then this println(a(pa), b(pb), c(pc)) will throw.
According to a hint from the IntelliJ IDE, array.length is more efficient than array.size because .size "requires an additional implicit conversion to SeqLike to be made."

But the real problem is that you're using Scala, a functional language, to write imperative code with many mutable variables, making the code more verbose.

Your algorithm is efficient and limits the number of while loop iterations, so how to express it in a functional manner: recursion.

def minDif[N:Numeric](x :Seq[N] ,y :Seq[N] ,z :Seq[N]
                     ,curSet :Seq[N] ,curDiff :N) :Unit = {
  import Numeric.Implicits._
  import Ordering.Implicits._

  if (x.isEmpty || y.isEmpty || z.isEmpty)
    println(curSet.mkString(","))  //done
  else {
    val newSet  = Seq(x.head, y.head, z.head)
    val newMin  = newSet.min
    val newDiff = newSet.max - newMin
    val (nxtSet, nxtDiff) = if (curDiff > newDiff) (newSet, newDiff)
                            else                   (curSet, curDiff)
    newSet match {
      case Seq(`newMin`,_,_) => minDif(x.tail, y, z, nxtSet, nxtDiff)
      case Seq(_,`newMin`,_) => minDif(x, y.tail, z, nxtSet, nxtDiff)
      case Seq(_,_,`newMin`) => minDif(x, y, z.tail, nxtSet, nxtDiff)
    }
  }
}

// a b and c have already been populated and sorted
minDif(a, b, c, Seq(), Int.MaxValue)

The minDif() method is tail recursive so it is compiled to an equivalent while loop under the hood.

Notice that I used Seq as the collection type. This allows minDif() to accept many different types as input: Array, Stream, Vector, etc. Since there is no indexing into any collection there is little advantage in restricting it to just arrays.

Also the element type is Numeric so this will work with Int, Float, Long, etc.


First of all, it's a good thing that you asked, only a few do care about handling errors.

Unfortunately, the way you choose is frowned upon, in both cases. Luckily, I've got a couple articles that cover your question in every possible detail:

a generalized one, PHP error reportig will show you the right approach for handling errors in general
a direct answer to your question, How to connect to MySQL using PDO would provide a ready-made connection code

Error handling

The idea here is that a module or a part of code should never treat errors by itself. This function should be delegated to the application level. Your database interaction code should only raise an error, which would be handled according to the site-wide configuration elsewhere.

So your goal with PDO is just to make it throw an error (in the form of Exception). As to how it will be handled should be defined elsewhere. It will make your error reporting uniform and both programmer- and user-friendly.

Connection

Another issue is a function.

  I use it as a function and call it always when I need a database connection.

If you call it more than once, it will create many connections to the database server and this number is not infinite. A connection should be made only once. So in its current form this function is rather useless. Given you have to create a $pdo variable only once, an include file would serve as well.

So let's create it

$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
     $pdo = new \PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

Handling query errors.

Like it was said above, do not handle errors in your code. We already configured PDO to throw exceptions in case of error, that's all. So just write your query execution code right away, without any conditions:

$stmt = $pdo->prepare("SELECT a FROM b WHERE c = :c")) {
$stmt->execute(array(':c' => $c));
$result = $stmt->fetch();
echo 'All fine.';


Getting and checking value from a mixed object array HTTP endpoint

Optional chaining can be used not only with object property lookup with dot notation, but also with bracket notation, by putting ?. before the [:

const data = { res: {}};
console.log(data?.res?.accounts?.[0]?.contacts?.[0]?.location == null)

Just to be thorough, you can also use optional chaining with function calls:

const data = { res: { }};
console.log(data?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));

const data2 = { res: { accounts: [{ contacts: [{ location: 'foobarbaz' }] }] } };
console.log(data2?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));

const data3 = { res: { accounts: [{ contacts: [{ location: 7 }] }] } };
console.log(data3?.res?.accounts?.[0]?.contacts?.[0].location?.includes?.('foobar'));

That said, having so many nested properties whose existence is uncertain is a bit of a code smell, because any time you want to look something up, you'll have to check the existence of all intermediate properties first. Despite the fact that you can do it concisely with optional chaining nowadays, it's quite a strange data structure. If you have control over fetchLocation, consider if you can refactor it so that fewer intermediate properties may be missing. (For example, if you could change it so that every account has a contacts array, and the array might be empty (but not null nor undefined), that'd be a step in the right direction).
Also, keep in mind that optional chaining is extremely new syntax. If this is going to be running on a public website, make sure to transpile your code down to ES6 or ES5 for production so that those with older browsers can consume your code.
On another note, you might consider using === instead of ==. ESLint rule: eqeqeq. == has some pretty odd behaviors involving type coercion that developers shouldn't be forced to look up in order to be 100% confident of what logic a particular section of code is implementing. For example, you could use ?? instead, to handle cases of undefined or null:
const location = data?.res?.accounts?.[0]?.contacts?.[0]?.location;
return location ?? null;

(Or, if location will always be a non-empty string, you could return location || null, which might be a bit better)
Also, the conditional operator is not in any of the code in your question or this answer. The conditional operator uses syntax of the form:
const resultingExpression = condition ? expression1 : expression2;


Lock-free queue with doubly linked list correctness

C11 atomic library

I you want to avoid the "legacy" functions, one solution would be to use the C11 atomic operations library. It is not widely supported yet. I know that GCC has been working on it, but I don't know if the 4.9 release already implements all the operations. Anyway, had you a compliant compiler, you could use standard atomic types and atomic operations.

For example, here are your functions ckLinkedListPushBack and ckLinkedListPopFront rewritten with the C11 atomic module:

void ckLinkedListPushBack(LinkedList *pList, void *pNode)
{
    atomic_fetch_add(&pList->size, 1);

    LinkedListNode *dummy = &pList->dummy;

    LinkedListNode *ptr = (LinkedListNode *)pNode;
    LinkedListNode *tail;

    ptr->pNext = dummy;

    while (1)
    {
        tail = dummy->pPrev;
        ptr->pPrev = tail;
        if (atomic_compare_exchange_strong(&dummy->pPrev, tail, ptr))
        {
            tail->pNext = ptr;
            break;
        }
    }
}

LinkedListNode *ckLinkedListPopFront(LinkedList *pList)
{
    LinkedListNode *dummy = &pList->dummy;

    LinkedListNode *ptr, *next, *dnext;

    ptr = dummy->pNext;
    if (ptr == dummy)
    {
        return NULL;
    }

    while (1)
    {
        next = ptr->pNext;
        if (atomic_compare_exchange_strong(&next->pPrev, ptr, dummy))
        {
            dnext = dummy->pNext;
            atomic_compare_exchange_strong(&dummy->pNext, dnext, next);
            break;
        }
    }

    atomic_fetch_sub(&pList->size, 1);
    return ptr;
}

In order for it to work, you would have to declare size to be an instance of atomic_uint_least32_t (fixed size types are not provided for atomics).

typedef struct

You can make clearer the LinkedListNode declaration by separating the typedef from the actual declaration:

typedef struct tagLinkedListNode LinkedListNode;

struct tagLinkedListNode
{
    LinkedListNode * volatile pNext;
    LinkedListNode * volatile pPrev;
};


How can this layered PHP architecture be improved?

Factory

Three things about this:

Consider using an autoloader (see PRS-0). Then you don't have to bother about, where files get included.
A Factory is used to create a set of objects, which depends on some context. For example, you could have a Filter and a Renderer for XHTML or HTML5. In order not having to check which one is needed again and again, you have an XhmtlFactory and an Html5Factory with createFilter() and createRenderer() methods.
Factory methods usually are named create....

In your context, a Factory is not helping you.

DB Connection

Don't use static methods, if you can avoid it. Inject dependencies whereever possible. Do not (finally) handle errors within your classes. Leave that up to the caller. The method to get an instance is usually called getInstance() (and is one of the few cases, where static calls are reasonable). The initialization is then made in a private constructor.

class Conn
{
    private $conn = null;

    /**
     * Establish PDO DB connection
     */
    private function __construct(Config $conf)
    {
        try {
            self::$conn = new PDO($conf->dsn, $conf->user, $conf->pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        } catch (PDOException $e) {
            $message = $e->getMessage();
            // We remove the username if we get [1045] Access denied
            if (preg_match('/\b1045\b/i', $message)) {
                $message = "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)";
            }
            throw new ErrorException($message);
        }
    }

    /**
     * Get DB connection
     */
    public static function getInstance(Config $conf)
    {
        if (is_null($this->$conn)) {
            $this->conn = new Conn($config);
        }
        return $this->conn;
    }
}

class Config
{
    public $dsn  = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST;
    public $user = DB_USER;
    public $pass = DB_PASSWORD;
}

To make the singleton pattern in Conn complete, the magic method __clone() should made private, so the connection cannot be copied.

Business Logic Layer

Keep the business and data access layer separated. The business layer ideally does not know anything about storage. The data access layer is injected into the business layer.

class Abc implements iAbc
{
    private $data = array();
    protected $dal;

    public function __construct($dal, $id = null)
    {
        $this->dal = $dal;

        if (!is_null($id)) {
            $this->setData($id);
        }
    }

    // __set, __get, __isset is here

    public function one(){};

    public function two()
    {
        $name = 'foo';
        $result = $this->dal->get_some_data($name);
        return $result;
    };
}

Data Access Layer

class AbcDao
{
    private $db = null;

    public function __construct(Conn $db)
    {
        $this->db = $db;
    }

    public function get_some_data($name)
    {
        $sql ="SELECT 123;";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);
        $stmt->execute();

        $result = $stmt->fetchAll();
        return $result;
    }
}

Controller

In your controller, you now really have control.

$config = new Config;        // You could use any other set of config data
$conn   = new Conn($config); // You could use any other storage method
$my_abc = new Abc($conn);
$test   = $my_abc->two();

or, shorter

$my_abc = new Abc(new Conn(new Config));
$test   = $my_abc->two();


You didn't need to hard-code season values like 1 and 2. Just use the nicely sorted repeating values from the rows and detect when the value changes from one row to the next.  With such a generic test, as shown below, you can use one loop and avoid repeated code.

Also note that you seemed to be using the wrong operator, !== the not-identical operator to do an equality test.

if (!($result = mysql_query("SELECT season_num, sub_season_num, esp_num, title, descrip FROM season ORDER BY season_num, sub_season_num", $link))) showerror();
$previous_season = 0; // start with nonsense value to force a heading
while ($row = mysql_fetch_array($result))
{
    $season = $row["season_num"]
    // Ignoring subseason in this version.
    // Decide whether to match both season and sub_season and
    // print both in a new header, complicating this `if` statement
    // OR have a separate, similar `if` statement and separate (sub)header
    // for subseasons. In the latter case, be sure to
    // reset previous_subseason to a nonsense value whenever season changes
    // Otherwise, a subseason header will be missing if a season happens to end
    // on the same subseason number (like 1) that the next season begins with.
    if ($season != $previous_season) {
        $echo "Season $season
";
        $previous_season = $season;
    }
    echo "Episode {$row["esp_num"]}
";
    echo "Title {$row["title"]}
";
    echo "Description {$row["descrip"]}
";
}


Write a function to find the first non-repeated character in a string

After playing a lot with jsperf and having to admit that the regex solution is actually faster, which annoys me.

Your first approach is far superior than your second approach (O(2n) -> O(n^2)) as per Venu
you should cache string.length, looking up the value of a property slows things down

for(var i = 0, length = string.length; i < length; i++){

You can assign More than one and One time with a ternary, also you should cache string[i] and not look it up 3 times:

charCount[c] = charCount[c] ? 'More Than One' : 'One Time';

You do not need var j, just use i again
You used string[i] everywhere else, your return statement should be return string[i];
repeater is a terrible name if you are planning to return a non-repeater ;)
from a design perspective, I would return '' instead of 'Everything is repeated', because really, '' aka nothing is repeating

On the whole I think your code is fine, I am not sure ( besides the magical regex ) how it could be done much faster. You need something to track the character count and I am not sure how you can avoid the second loop.

Update: books.google.com/books?isbn=1118169387 <- This pretty much agrees that your first approach is as fast as it gets ( except for the mind boggling regex ;)


Project Euler #1 Sum of multiples of 3 and 5 python implementation

It'd be more pythonic to use the built-in sum function instead of writing one yourself:

sum(xrange(num, limit, num))

However, this is still doing way too much work -- you don't need to do a for-loop for a series sum, there's a closed-form solution:

def sum_multiples(n, lim):
    last = (lim - 1) // n
    return n * (last) * (last+1) // 2

EDIT: Also, don't call your own function sum, since you hide the built-in one that way.

def sum35(limit):
    return (sum_multiples(3, limit) +
            sum_multiples(5, limit) -
            sum_multiples(15, limit))

print sum35(10)   # 23
print sum35(1000) # 233168


State should always be valid

One of the main issues I see in your class design is that the state of your object is undefined most of the time. If I have a triangle, I want it to be... you know, a triangle. But when you start with:

triangle=Triangle()

You have an object with 3 zero sides. That's a degenerate object. Rather, you'll want to make it so that once you have a Triangle, then it must be valid.

Building up our Triangle

To that end, let's consider get_side(). As a member function, this makes little sense - it doesn't interact with Triangle at all. The get_* naming suggests that it's yielding some sort of member, when actually it's prompting the user for input. So let's rework it as a free function:

def input_side(side_name):
    try:
        return float(raw_input('Enter length of {}:'.format(side_name)))
    except ValueError:
        return None

Catching SyntaxError is questionable - it'd be better to use raw_input and a cast that returns a specific error. Otherwise, what if we had a syntax error? You'd hide it from yourself.

Once we have that, we can use that to call into our Triangle constructor:

triangle = Triangle(
    input_side('adjacent'),
    input_side('opposite'),
    input_side('hypotenuse')
)

where we rewrite the constructor to be:

def __init__(self, adjacent, opposite, hypotenuse):
    self.adjacent = adjacent
    self.opposite = opposite
    self.hypotenuse = hypotenuse

It is much better to simply have your members as members than to hide than in a dictionary. self.hypotenuse is much more direct than self.side['hypotenuse']!

Input Validation

Comparison against None should be done with is, not ==. And if you're iterating over a dictionary with iteritems(), you don't need lookup:

def count_nones(self):
    nones=0
    for side, length in self.side.iteritems():
        if length is None:
            nones+=1
    return nones

though the above can be abridged into:

def count_nones(self):
    return sum(1 for (side, length) in self.side.iteritems()
        if length is None)

Or, now that I'm proposing we not use a dictionary:

def count_nones(self):
    return (self.adjacent is None +
        self.opposite is None +
        self.hypotenuse is None)

But really, you should do all of this external to your Triangle class. As in:

Input your sides
Make sure exactly 2 of them are valid
Calculate the third
Then construct your Triangle with all three sides

Printing

In Python, you would typically add a __str__ method instead of a print sort of method:

def __str__(self):
    return 'Triangle(adjacent={}, opposite={}, hypotenuse={})'.format(
        self.adjacent, self.opposite, self.hypotenuse
    )

namedtuple

If you follow where I'm going up to now - you'll see I've made Triangle a great deal simpler. It doesn't deal with inputs. It doesn't deal with calculations. It's just a triangle. And for simple classes like that, Python has namedtuple:

>>> Triangle = namedtuple('Triangle', 'opposite adjacent hypotenuse')
>>> triangle = Triangle(3, 4, 5)
>>> triangle.adjacent
4
>>> print(triangle)
Triangle(opposite=3, adjacent=4, hypotenuse=5)

Even if you want to allow temporarily invalid Triangles, namedtuple is the way to go since it makes so many other things easier. For instance, since a namedtuple is just like a tuple with benefits, you could count your Nones directly:

triangle = Triangle(input_side('...'), ...)
if triangle.count(None) != 1:
    # do some error logic as appropriate


Filtering array by list of keys in PHP 5.5

I always believe that you should use built in functions wherever possible, as opposed to recreating PHP functionality with loops etc. The main reasons for saying this are that:

We should trust that PHP functions achieve their desired result in an efficient manner, and:
If they are improved in future versions your code doesn't need to change, but just gets better.

That being said, why not something like this:

$matches = array_intersect_key($langs, array_flip($allowed_langs));
var_export($matches);


You can replace

<button onClick={this.toogleWork}>Work</button>
<button onClick={this.toogleRelax}>Relax</button>

with

<button onClick={this.toggleState}>{this.state.work? 'Relax' : 'Work'}</button>;

and

toogleWork = () => this.setState({work: true})
toogleRelax = () => this.setState({work: false})

with

toggleState = () => this.setState(prevState => ({work: !prevState.work}));


Instead of using Task<string>.Factory.StartNew you can do Task.Factory.StartNew.
However, instead of using Task.Factory.StartNew you can use Task.Run. It is simpler and supports more advanced scenarios. See here.


Threads with lambdas and runnable in Java

Your code is fine, but neither the question nor your answer have anything to do with threads. In order to run two separate threads, you need to create a Thread object with your runnable, rather than just calling myRunnable.run(). The first runnable returns to the scope of your main() method before the second is executed, i.e. they are sequential and exist in a single thread.


Reduced mutation

val result = mutableListOf<String>()
for (subWord in smallDictionary) {
    val subWordLength = subWord.length
    (smallDictionary)
        .filter { it.length + subWordLength == wordLength }
        .map { it + subWord }
        .filter { it in searchWords }
        .forEach { result.add(it) }
}
return result.toList()

could be replaced with:

return smallDictionary
    .flatMap { first -> smallDictionary.map { first to it } }
    .filter { it.first.length + it.second.length == wordLength }
    .map { it.first + it.second }
    .filter { it in searchWords }

Optimisation

You could filter the 2 lists so the starting list is only words that start with the same letter as the target word, and the ending list is only words that end with the last letter of the target word, for a large wordlist this in theory could reduce the size of these lists by a large amount.


PEP0008 says use 4 spaces for indentation, it's much clearer where one block starts and another ends that way.

This may be a placeholder but I'll assume your code posted here is real code and say that you should just use if blob_info and remove the pointless pass and else.

if not blob_info:
    pass
else:

I also think you could reformat for better whitespace to make your code more readable. You currently use none and that gives a wall of text effect. This looks nicer:

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):

    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)

        if blob_info:
            data = blobstore.fetch_data(blob_info.key(), 0, 50000)
            img0 = images.Image(image_data=data)
            img = images.Image(blob_key=blob_info.key())

            if img0.width >= 800:
                img.resize(width=800)
                img = img.execute_transforms(output_encoding=images.JPEG)
                self.response.headers['Content-Type'] = 'image/jpeg'
                self.response.out.write(img)
            else:
                self.send_blob(blob_info)

You should also add a docstring to your class at least. I can't suggest one given my limited knowledge of your script but they're always helpful for a class.


You don't really need a design pattern for determinants, just a better algorithm. Generally one of the easiest (and fastest) ways of calculating a matrix determinant is by using what is known as LU-Decomposition. This factors a matrix into two matrices, a lower triangular and an upper triangular matrix. From these, the determinant can simply be calculated as the product of diagonal elements.

Note that you have to be careful when calculating determinants of large matrices; for a 100x100 matrix, it can easily overflow the maximum size of a float (or double). For this reason it's often better to calculate a log-determinant.

On to the actual code you've presented:

data should be passed by const& since it isn't (and shouldn't be) modified:

float determinant(const std::vector<Vector>& data)

Using a template int parameter to choose between determinant sizes is really odd, and is potentially easily misused. What if I use Determinant::determinant<2>(...) on a 3x3 matrix? It'll give me the wrong answer. You should generally try to make your code easy to use and hard to misuse. In this case, that means calculating the determinant size based on the row/column size of the passed parameter. Better yet would be creating a matrix class to encapsulate all of this information.

These days, it generally doesn't make a lot of sense to use float over double unless you really need the speed (and even then, it is often no faster, and can sometimes even be slower on modern hardware). Stick to using double by default.


Bouncy castle 128bit AES/CBC/PKCS7 in java

Some observations:

It is best to always specify the encoding when converting from a string to a byte array:
input.getBytes()     -> input.getBytes("UTF-8")
keyString.getBytes() -> keyString.getBytes("UTF-8")
The IV should be an array of random bytes unique for each encryption, usually created from a CSPRNG. Then prefix the encrypted data with the IV for use during decryption, the IV does not need to be secret.
When using a password it is necessary to derive the key from it with a function such as PBKDF2.


You probably want to reset the margin and padding of li items, too.

Using float to layout elements horizontally is outdated. Using flexbox should be preferred nowadays. That would also make overflow: auto redundant.

Prefer a child combinator instead of a descendant combinator if possible: .dropdown > ul.

A dropdown on hover isn't usable on a touch screen.


React app that interacts with CoinMarketCap API

You're using redux for state management. The problem with mixing local state and redux state is that component render cycles are asynchronous, which oftentimes can cause finicky race conditions. If you're going to use redux, commit to it. If you aren't using any middlewares like redux-thunk, I highly suggest you do so. Dispatching actions and making api calls are ensured to be synchronous when using thunk actions

Your component is "responsible" for too much. It's a violation of the single responsibility principle, makes the component harder to reason, and is [far] more difficult to test. One of the main selling points of redux is the ability to tuck away how data is being passed. It lets you create a separation of concerns and will make your components much easier to reason and maintain. If I were in your position, I would create the following:

Make your api call inside a redux thunk action, and store the raw values in the store

Data calls and transfer are ensured to be synchronous. I would place the data in its entirety, just in case you need the raw data elsewhere

getCoinsData = () => async dispatch => {
    coinsData = await // api call
    const parsedCoinsData = coinsData.map((el) => { // Array#map already creates a new array. No need to spread it
        const {
            market_cap,
            volume_24h,
            percent_change_24h,
            percent_change_24h
        } = el.quote.USD
        return {
            id: el.id,
            name: el.name,
            marketCap: market_cap,
            volume24h: volume_24h,
            percentChange24h: percent_change_24h
        }
    })
    dispatch({
        type: SET_COINS_DATA,
        data: parsedCoinsData
    })
}

Create a selector to create the chart data

Creating a selector to parse/structure the data for your needs is an easy way to hide how the data is being created for your component to use and be able to hold all of the data in its unadulterated state in your redux store.

getChartData = state => {
    const { coinsData } = state.cmcListCallReducer;
    return [
        {
            id: 'CoinMarketCap API response',
            data: coinsData.map((el) => {
                const {
                    id,
                    name,
                    marketCap,
                    volume24h,
                    percentChange24h,
                } = el
                return {
                    id,
                    name,
                    marketCap: '$' + formatCrypto(marketCap, 3),
                    volume: '$' + formatCrypto(volume24h, 3),
                    priceChange: formatCrypto(Math.abs(percentChange24h)) + '%',
                    x: marketCap,
                    y: volume24h,
                    z: Math.abs(percentChange24h)
                }
            })
        }
    ]
}

And then your component would just look like this.

import React from 'react';
import { connect } from 'react-redux';
import ChartContainer from './chartContainer';

class Liquidity extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            minmaxValues: {},
            isLinear: false,
        };
    };

    swapChart = () => {
        this.setState((prevState) => ({ isLinear: !prevState.isLinear }));
    };

    render() {
        const { isLinear } = this.state;
        const { chartData } = this.props
        return (
            <>

Liquidity

                    <button
                        className={'btn btn-primary'}
                        type="button"
                        onClick={() => this.swapChart()}
                    >
                        Switch to {isLinear ? 'logarithmic' : 'linear'}
                    </button>

                <ChartContainer chartData={chartData} isLinear={isLinear} />
            </>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        chartData: getChartData(state)
     };
};

export default connect(mapStateToProps)(Liquidity);
```


The Algorithm

The method logIn can be chunked into small steps:

  public boolean logIn(String name, String password) {

   if( /* user is logged in already? */)

   for (/* every user */)
     if ( /* has name and password */)

   if (/* no match found */)
     for (/* every user */)
       if ( /* can find user with the given name? */ )
}

The logic is more complex than it has to be. The algorithm searches twice if a user with the name exists. A simpler algorithm could look like:

public boolean logIn(String name, String password) {
    User user = // find user by its name

    if (/* no user found */)

    if (user.isLoggedIn)

    return user.hasPassword(password)
}

Data Structure

The method getUsers() looks like it returns a List. Since it is a list and you do not know at which index a concrete user is saved you have to search for the user.

  for (User user: getUsers())
{
  if (user.toString().equals(name))

To check that a user with name does not exists you have to loop through the hole list and this could take some time if you have many users! This is also known as \$O(n)\$ which is a indicator for the time complexity a algorithm can have.

It would be much more performant if we could get a user directly without to search it which would be a time complexity of \$O(1)\$.

We can archive this goal by using a Map instead of a List:

Map<String, User> nameByUser = new HashMap<>();

nameByUser.put("TomZ", new User("TomZ", "aPassw0rt"));
// ..insert some more users

User user = nameByUser.get("TomZ");


Wow, so sorry I missed seeing this question! (Normally I get emails when someone posts something tagged with scheme, but didn't see this one till now. :-()

So, the idiomatic way to build a list in Scheme is to cons elements to the front each time, then reverse the whole list at the end. This is still O(n) on the number of items to insert, so you're no worse off compared to the set-cdr! solution.

However, for this situation, a better solution (IMHO) in your case is actually to use unfold, which takes any given object (not necessarily a list) and results in a list. This is perfect for your situation because you are processing variable numbers of items in your input list at each step, which would make it a poor fit for map, fold, and the like (which processes exactly one item at each step).

Here's an example (require SRFIs 1, 8, and 60):

(define (decode-utf8 bytes)
  (define (invalid byte)
    (list 'invalid byte))
  (define (non-shortest val)
    (list 'non-shortest val))
  (define (end-of-input val)
    (list 'end-of-input val))

  (define (decode-start bytes)
    (define byte (car bytes))
    (define rest (cdr bytes))
    (cond ((< byte #x80) (values (integer->char byte) rest))
          ((< byte #xC0) (values (invalid byte) rest))
          ((< byte #xE0) (decode-rest 1 #x80 (logand byte #x1F) rest))
          ((< byte #xF0) (decode-rest 2 #x800 (logand byte #x0F) rest))
          ((< byte #xF8) (decode-rest 3 #x10000 (logand byte #x07) rest))
          (else (values (invalid byte) rest))))
  (define (decode-rest count minval val bytes)
    (cond ((zero? count) (values ((if (< val minval)
                                      non-shortest
                                      integer->char) val) bytes))
          ((null? bytes) (values (end-of-input val) bytes))
          (else
            (let ((byte (car bytes))
                  (rest (cdr bytes)))
              (cond ((< byte #x80) (values (invalid byte) rest))
                    ((< byte #xC0)
                     (decode-rest (- count 1) minval
                                  (+ (ash val 6) (logand byte #x3F))
                                  rest))
                    (else (values (invalid byte) rest)))))))

  (define (decode bytes)
    (receive (value rest) (decode-start bytes)
      value))
  (define (next bytes)
    (receive (value rest) (decode-start bytes)
      rest))

  (unfold null? decode next bytes))

The real action happens in decode-start and decode-rest, of course; both functions return two values:

the character decoded (or an error)
a reference to the next byte to process

The decode function extracts the first value, while next extracts the second.

If you still want to use a list builder, that's fine too. Here's a simple version: it builds the list when given no arguments, and otherwise appends the arguments given:

(define (make-list-builder)
  (define cur '())
  (case-lambda
   (() (reverse cur))
   ((item) (set! cur (cons item cur)))    ; redundant
   (items (set! cur (append-reverse items cur)))))

(where append-reverse comes from SRFI 1). Note that append-reverse with only one item is identical to cons, so the cons line above is redundant; it just demonstrates how you would do it if you want to add items one by one.

If you want to be able to send messages like in your version, here's how one might implement it:

(define (make-list-builder)
  (define cur '())
  (lambda (msg . args)
    (case msg
      ((add) (set! cur (append-reverse args cur)))
      ((get) (reverse cur))
      ((clear) (set! cur '())))))

In both cases, we keep track of a single variable only, not the start and end of list, because we are prepending elements rather than appending them.

There is still a valid use for the start-and-end approach you had, though: it's a common approach for implementing a queue. You enqueue by using the end reference, set-cdr!ing the new value in, then resetting the end reference; and of course, you dequeue by using the start reference. Here's an example (zero arguments means dequeue; otherwise enqueue the given arguments):

(define (make-queue)
  (define start (list 'queue-head))
  (define end start)
  (case-lambda
   (() (when (null? (cdr start))
         (error "empty queue"))
       (let ((result (cadr start)))
         (set-cdr! start (cddr start))
         (when (null? (cdr start))
           (set! end start))
         result))
   (items (set-cdr! end items)
          (set! end (last-pair end)))))

(here, last-pair comes from SRFI 1).


Displaying elements of a list, in columns

Fancy iteration in Python is often made easier using the itertools module.  For this case, itertools.islice() can help pick out the values for each row.

from itertools import islice

cols = 4
step = 10
vlist = ["Value" + str(i+1) for i in range(100)]

for row in range(step):
    print(', '.join(islice(vlist, row, cols * step, step)), end=", \n\n")


Checking for files that are mentioned as children of other files

General Remarks

Why are your files assigned to properties of an object? Keeping them in an array would be simpler. Or do you wish to store some kind of mapping from id → file? You currently use the file's name as a unique id which would then redundantly appear on both sides of that mapping.

Matching only by file name seems risky to me, but it really depends on your definition of 'child'. Depending on the exact use case, a file path plus name or a file hash value might be a more suitable unique identifier.

I would avoid talking about 'class structure' when describing the structure of anonymous objects. 'class' has a specific meaning, especially since the class keyword has been introduced to JavaScript now. If your files were really instances of a class, you would probably want to use some kind of creational design pattern such as a factory or factory method which avoids the issue of having to deal with incompletely initialized instances until you finally fill in the parents.

Style

The first code sample could be more readable if it weren't squeezed into a single line.

All code samples could benefit from better naming. Instead of file write child, instead of fileInner write parent, instead of curFileName write child.name etc.

Instead of indexOf use includes. Since you already use const, you should also use let instead of var or globals.

Instead of Object.keys use Object.values.

Your first or second example could be written as:
files.forEach(parent => {
  files.forEach(child => {
    if (parent.children.includes(child.name)) {
      child.parents.push(parent.name);
    }
  });
})

Alternatively using for-of-loops:
for (const child of files) {
  for (const parent of files) {
    if (parent.children.includes(child.name)) {
      child.parents.push(parent.name);
    }
  }
}

If files is not an array but an object, replace files with Object.values(files).
Performance
If performance is really an issue, look into the runtime complexity of your operations. By introducing an explicit Map from parent names to children files, the runtime complexity could be reduced to depend linearly on the total number of children only.


ReactJS, Material UI component and code organization

Your file structure is okay, though it is not the "conventional" react folder structure. I personally like your approach better than having lots of nested folders with index.js but this is because my workflow relies on searching files by name, and searching for index.js is impossible — you always have to search by file.

  One quick question: the component src/components/body/UserProfile/UserWorks.js is reused in src/components/body/UserWork/UserWork.js; is it ok to leave them with this structure?

As I understand, UserWorks is some component that shows some sort of preview of works; I think that the structure should be the other way around, UserProfile should depend on UserWorks not the other way around. You might even structure it explicitly that UserProfile and UserWork pages (components) depend on a representation component UserWorks, though naming becomes a bit cumbersome.

Note on using export default

It seems to be standard "good" practice to use export default in Javascript, but I personally don't like it for various reasons and one of them shows in UserWork: you are importing UserWorks as UserRelatedWorks this suggests that UserWorks is used with different intention that is originally designed. Named imports would not eliminate this issue completely but would at least force explicit statement import {UserWorks as UserRelatedWorks} from …

Comments on the code:

lots of unnecessary empty lines, this is a bit unusual. In most cases empty lines are used to group statements together, here they appear to be random and make code harder to read.
you are using classes for div.bio but not for Skeleton though those styles are repeated but bio is not (or should not be)
no matter value of loading you are returning a container with <div className={classes.bio}>, you can return container and resolve content inside of it based on the loading to avoid duplication.

In this code filter method is used incorrectly, the callback should return boolean but in this case returns the object itself or null, this relies on implicit type casting to truthy value and is very confusing

          works.filter(w => {

            if ((!category) || (category === "all")) {
              return w;
            }
            else {
              if (w.category_list.includes(category)) return w;
            }

            return null;

          })

this code should be

works.filter(work => !category || category === 'all' || w.category_list.includes(category))


One thing I would do is wrap this up in a hangman class. That way you could just toss away the hangman instance for a new one if the user ever decided to play again rather than resting all global variables. It would also decouple the handling of user input from the actual game. If the game size would grow this would make catching bugs a lot easier.

But lets focus on some smaller things that are easier to change

chosen = random.choice(word_list)
return chosen

Here your variable has no purpose, I would do

return random.choice(word_list)

Similar kind of story here

if again.lower().startswith('y'):
        return True
    return False

to

return again.lower().startswith('y')

Next is avoid magic constants at all costs, for example

if len(line.strip()) > 3:

What is 3? Why is 3 important here? You should replace this with a global ALL_CAPS variable to represent what 3 is.


Responsive Foundation Orbit Image Gallery

First, I think you'd be better off if you had a representation of the gallery
as data (following the Rule of Representation).
It would go something like this:

A Simpler Method

Get your objects into memory. These can come from a REST API, or you could drop
this into the dom when you're rendering server side. However you like.

var gallery = [
  {
    title: "An image",
    src: "http://placehold.it/1400x348",
    width: 1400,
    height: 348,
    body: 'More hence euphemistic...',
    active: true,
    index: 0
    // any property you'll need to render this item goes here
  },
  // etc...
]

You can have the rendering code that consumes this list. The example shown uses
hyperscript.

var h = require('hyperscript')

function renderOne (slide) {
  h('li', {index: slide.index},
    h('img', {src: slide.src, width: slide.width}),
    h('section', slide.body)
    // and so on...
  )
}
function render (gallery) {
  h('ul#slider', gallery.map(renderOne))
}
// use it like this:
$('body').html(render(gallery))

Then you can listen for events on the containing element and modify the data
accordingly.

$('body').on('click', 'li', function (e) {
  var index = parseInt($(e.currentTarget).attr('index'), 10)
  gallery.forEach(function (slide){
    slide.active = false
  })
  gallery[index].active = true
})

With every property necessary for rendering held in the data representation,
your rendering logic can be very simple. Simple logic is easy to reason about
and breeds fewer bugs. To get an accurate dom after any change, all you need to
do is rerun:

$('body').html(render(gallery))

What about performance? There are excellent tools that abstract the dom into a
virtual dom that determines the minimal change necessary to get the current dom
to match the dom you want. Use those tools (like mercury
  or react).

If you're looking for another example, I did a similar post here.

The Original Method

That would be a significant change in method, however. Here's some ways to make
your current method easier to reason about for a newcomer to your codebase
(See it in action on jsbin here). Note: it was a style choice to omit semicolons and rely on automatic semicolon insertion.

Foundation now has a debounce function in its utils. May as well use that.

var debounce = window.Foundation.utils.debounce
var $copy, isSmall

You might also listen to requestAnimationFrame to get resize events. I left this
as resize.

// Call the script on resize (must support ie8)
var listen = window.addEventListener ? window.addEventListener : window.attachEvent
listen('resize', debounce(checkGallery), 250)

The logic is easy to follow if methods are mostly in the order they're called.

$(function(){
  // when swapping widgets, clone original state
  $copy = $('#slider').clone()
  checkGallery()
})

Descriptive names for complex boolean questions tend to increase clarity.

function checkGallery () {
  var wasSmall = isSmall
  isSmall = window.matchMedia('(max-width: 767px)').matches

  // only swap widgets if necessary
  if (wasSmall !== isSmall) initGallery(isSmall)
}

function initGallery (small) {
  // reset to inital state
  $('#hero').html(clone())

  if (small) {
    initAccordion()
  } else {
    initOrbit()
  }
}

This retains the selected slide when swapping widgets. I believe this is
not how the original worked, but I believe this was a desired behavior. I'd
point out that this logic is hard to follow for a newcomer to your codebase.
This function is a good example of why simple rendering logic + more complex
data structure is the way to go.

function clone () {
  $html = $copy.clone()

  // retain active item
  index = $('#slider > li').index($('#slider > li.active'))
  console.log('index', index)
  if (index > -1) $html.find('> li:eq('+index+')').addClass('active')

  return $html
}

This way, we don't bring foundation JavaScript into the mix unless we're using
it.

function initAccordion () {
  $('#slider').on('click', 'li', function (e) {
    $(e.currentTarget).addClass('active').siblings().removeClass('active')
  })
}

function initOrbit () {
  $('#slider').attr('data-orbit', '').foundation({
    orbit: {
      slide_number: false,
      timer: true,
      timer_speed: 8000,
      next_on_click: false
    }
  })
}

The only change necessary in CSS is this:

@media screen and (max-width: 767px) {
  #slider > li .slider-content {
    display: none;
  }
  #slider > li.active .slider-content {
    display: block;
  }
}


Rule of Three.

int main()
{
    extra::Optional<int> x = Optional<int>of(new int(5));
    extra::Optional<int> y(x);   // This still compilers.

    // But your problems don't appear until here
    // at the end of scope.
}

Design

Why do you force the construction of optional objects via the static methods?

    static Optional<T> of(const T &v);
    static Optional<T> of(T *v);

Why not allow people to just construct the objects in the normal way. It would seem more  natural to create objects of this type just like any other object!

Move semantics

You may not want copy semantics (since you are basically implementing a smart pointer. But you could do with implementing move semantics on your object.

Overall

I don't see the need.

If you want to return a pointer (but make sure it is managed). Then pass back a std::unique_ptr<T>.

If you are doing this as a learning exercise that's different. I'll give it a good going over once you have fixed the problems around the rule of three. But that is such a fundamental problem there is no point in reviewing this code further (Though in future version I would like a justification for the static of() methods and examples of why they are needed).


I think it would be better to not convert the List to a Set, but just check if they are the same size and if one contains all of the other (as it is done in HashSet) like so:

public static boolean test(Object o1, Object o2){
    try{
        Collection<?> c1 = (Collection<?>)o1,
                      c2 = (Collection<?>)o2;
        return (c1.size()==c2.size())&&c1.containsAll(c2);
    }
    catch(Exception e){
        return false;
    }
}


I think you can pass in the controller to the "stories" render function and use the model hook :

App.IndexRoute

App.IndexRoute = Ember.Route.extend({
    renderTemplate: function(){
        this.render();
        this.render('stories', {controller: App.StoriesController});
    }
});

App.StoriesController

App.StoriesController = Ember.ArrayController.extend({
    model : function() {
        return App.Story.find();
    }
});


Optimize MySQL double select inside for-loop

Three major points:

Executing SQL queries in a loop will nearly always cause a performance problem.  You want to formulate a query that gives you all the data you want.
mysql_query() and similar functions are deprecated; use mysqli or PDO instead.
Composing your query by concatenation and interpolation, without escaping, could easily lead to an SQL injection vulnerability.  Better yet, use a database interface that supports placeholders for parameters so that you don't have to worry about escaping.

A better solution would go something like this:

function bookings_between($booking_state, $start, $end) {
    $formattedStart = date('Y-m-d', $start);
    $formattedEnd   = date('Y-m-d', $end);

    $query = mysql_query("
        SELECT the_date, COUNT(id)
            FROM ".T_BOOKINGS."
            WHERE id_state=$booking_state
                $sql_condition AND
                the_date BETWEEN '$formattedStart' AND '$formattedEnd'
            GROUP BY the_date;")
        or die ("Error getting states<br>".mysql_error());

    $results = array();
    while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
        $results[$row[0]] = $row[1];
    }
    return $results;
}

$booked = bookings_between(1, $start, $end);
$reserved = bookings_between(4, $start, $end);

The results are not in the same format as your original.  This returns the bookings in associative arrays, keyed by the date (as formatted by MySQL).  Days that have no bookings will not have an entry.  If you need to, you can post-process $booked and $reserved back into a data structure compatible with the original code.  The big win, though, is that you execute just two queries instead of two queries per day of the period in question.


It's hard to pick on such simple and straightforward code.
The one thing that stands out to me is the distance between the line where you declare the root variable, and the lines where you actually use it.
Let me quote an interesting paragraph from Code Complete:

  The code between references to a variable is a “window of vulnerability.” In the window, new code might be added, inadvertently altering the variable, or someone reading the code might forget the value the variable is supposed to contain. It’s always a good idea to localize references to variables by keeping them close together.

Indicators of this window of vulnerability are the measurements of variable "span" and "live time":

Variable "span": the number of lines between references to a variable. When a variable is referenced multiple times, the average span is computed by averaging all the individual spans. The smaller the better.
Variable "live time": the total number of statements over which a variable is "live". This is a count of lines between the first reference and the last. Again, the smaller the better.

By declaring root and scene at the top and using only at the button,
you have a large "window of vulnerability",
and high average spans and life times.
You can reduce these negative indicators by pushing these declarations down in your method to where the variables are actually used.


From a quick once over:

JsHint.com has very little feedback, good!
Consider using use strict to activate strict mode
Avoid console.log
Both beforeSend , error and complete should be customizable by the caller
success() returns ( PlainObject data, String textStatus, jqXHR jqXHR ) you should pass all 3 to success_callback
JavaScript is lowerCamelCase, success_callback -> successCallback
member_id: 1, <- Maybe this is sample code, this magic constant deserves a comment
I wonder if AjaxRequest should know about "/ajax-member/, from a DRY perspective
for (i in response.achievements) {, response.achievements seems to be an array, please use a regular for loop to iterate over arrays, it will prevent hard to find bugs at a later stage
Find a good templating library, you need it, consider Handlebars
I think your Ajax class could be expanded, getAchievements and getComments are clearly a result of copy pasting code


Optimize jQuery image gallery for production

It's quite fine, but it can be simplified a little bit.
In the HTML, the img elements all have the same style value.
It would be better to remove the style attribute from all the img,
and define in the stylesheet instead:

#gallery img {
    max-width:150px;
    max-height:50px;
}


Data Class code smell? Java object is modified by multiple methods in a row

Basically, whenever you find yourself doing something like:
MyDataStructure data;

call1(data); // modifies data
call2(data); // modifies data
call3(data); // modifies data

you have a big indicator, that the data structure should indeed be a class:
MyDataClass dataClass;

dataClass.call1();
dataClass.call2();
dataClass.call3();

If the call chain depends on a given order, encapsulate this in the class as well:
MyDataClass {

   public void doComplexTask() {
       call1();
       if (resultIsNotGood) throw Exception...

       call2();
       ...
       // you get it
   }

   private call1() { ... } // not exposed any more
}


Select first value if exists, otherwise select default value

The shorter query I can think of is

SELECT COALESCE(MAX(Data), 'Default Value')
FROM   Configuration
WHERE  Name = 'NameOfConfiguration';

If the configuration is present it'll take it.
If the configuration is not present the MAX will generate a NULL value (the MAX of nothing is NULL) that will be coalesced to the default value

There is a more generic approach that takes care of what said by Martin Smith in his comment, but is more verbose (using the hypothesis that the configuration name are unique)

WITH Param AS (
  SELECT ID, Data
  FROM   Configuration
  WHERE  Name = 'NameOfConfiguration'
  UNION ALL
  SELECT NULL, 'Default Value'
)
SELECT TOP 1
       Data
FROM   Param
ORDER BY ID DESC

The ID of the Default Value is set to NULL to avoid to use a magic number.
From the BOL: NULL values are treated as the lowest possible values.

IMO a general solution should be used only where a specific one is not possible, and that doesn't seems the case. Also in a generic case the Default Value will need to be a valid value for the datatype of the configuration values otherwise the UNION will return a conversion error.


Python: check if all array values are same

You are iterating over the list, and copying elements that have a certain property to the correct list, then checking whether it's of the size of the original list. In other words, you're checking whether all elements fulfill a certain condition, in other words:

return all(object[number].text == "Sample" for number in array)


Simple substitution encryption with Scala

encipher() deserves to be a full function with two parameters rather than just a closure within main().  It should take a key parameter first, because you can think of enciphering with a key as a transformation to be applied to the text.  (For that matter, I suggest swapping your args(0) and args(1) as well.)  The function would be more usable if it accepts and returns strings instead of lists.

Instead of writing args(0) twice and args(1) twice, you should assign text and key more appropriately, by not munging them prematurely with .toUpperCase.toList.  I also suggest using destructuring to assign both values at once.

With the changes above, main() can look very clean.

As for the encipher() function, you can simplify it by using

for-comprehensions instead of repeated concatenation to an empty string
pattern matching instead of if-else.

object SimpSub {
  private val alphabet = ('A' to 'Z').toList

  def encipher(key: String, text: String): String = {
    // Build the cipher alphabet by concatenating the key to
    // the alphabet and removing duplicate letters
    val cipherAlphabet = (key.toUpperCase.toList ::: alphabet).distinct

    val cipherText = for (c <- text.toUpperCase) yield c match {
      case ' ' => ' '
      case _   => cipherAlphabet(alphabet.indexOf(c))
    }
    return cipherText.mkString
  }

  def main(args: Array[String]) {
    val Array(text, key) = args

    println("Plaintext: " + text)
    println("Key: " + key)
    println("Ciphertext: " + encipher(key, text))
  }
}


CSV lookup problem solved with CoffeeScript

Your lookupIndex may not work as intended unless the value you're using for the lookup is unique across all rows. You'll always find the last row in the CSV data, since the reduce function that creates lookupIndex will overwrite any existing lookup key/value with a new row number. That may not be a problem, but it is a limitation in your function.

You're doing a few things that you don't strictly need in CoffeeScript:

Explicit returns
Parentheses around function arguments
A "JS-style" IIFE, when CoffeeScript has the do keyword
You can define multi-line strings in CoffeeScript; just use 3 quotes (like Python)
CoffeeScript also has a for..of object iterator which would probably be more readable than your reduce calls (although semantically different)

Admittedly, the first 2 post are as much a question of context and preference. Sometimes you do need parentheses (e.g. when chaining function calls), and sometimes an explicit return is more readable. Still, though, your syntax seems a little funky in some places (for instance omitting commas in the call that to compile_csv_list, yet including the parentheses?)

In more general terms:

You're mixing snake_case and camelCase. Just stick to camelCase as that's the JS (and thus CoffeeScript) convention. For instance you'll see that assert.deepEqual is camel-cased. Speaking of convention; 2 spaces of indentation is the most common rule.
You're requiring assert, presumably for use in your tests - but you also use it in the function itself. That seems like a bad idea. Especially since you can just throw your own, possibly more detailed, exception whenever you want.
You could consider checking the header line for the lookupKey before parsing the rest of the lines.
I hope your CSV data is fairly easy to deal with; otherwise I'd find a full featured CSV parsing library, if I were you. Right now, you're just splitting on newlines and commas - but CSV may contain strings with commas in them, and which aren't "cell" delimiters. And a string may contain quotes - in which case the outer string has two quotes around it or something, if I recall correctly... CSV is a bizarre format with no simple rules for escaping things. The only real way to parse it, if you want to be thorough, is to go byte by byte; a regex just won't cut it.

Anyway, here's a version with some style changes. The only functional difference is that it doesn't use assert in the function itself.

compileCSVSearch = (csv, lookupKey)->
  [header, rows...] = csv.split("\n").filter(Boolean).map (line) -> line.split ","

  columnIndex = header.indexOf lookupKey
  throw "Can't find a '#{lookupKey}' column" if column is -1 # consider throwin ag proper Error obj

  lookupTable = {}
  for row, i in rows
    value = rows[columnIndex]
    lookupTable[value] = i

  (lookupValue) ->
    index = lookupTable[lookupValue]
    return unless index?
    copy = {}
    copy[key] = value for own key, value of rows[index]
    copy

# Tests

do ->
  assert = require "assert"

  csvText = """ip,name,desc
               10.49.1.4,server1,Main Server
               10.52.5.1,server2,Backup Server\n"""

  csvByName = compileCSVSearch csvText, "name"

  assert.deepEqual csvByName("server2"),
    ip: "10.52.5.1",
    name: "server2",
    desc: "Backup Server"

  assert.equal csvByName("server9"), undefined


Using Grand Central Dispatch to fetch data from Parse.com and update UI asynchronously

First off, I don't know Swift.  These are generic issues that should be addressed in all written code, and I'll leave the Swift-specific stuff to the experts.

Comments

//execute slow task

Comments should say why the code is the way it is, not a generic comment that doesn't tell us anything constructive.  If there is an issue with the code being slow, document why it is slow, and maybe state why you haven't been able to fix it for future reference.

Spacing

    }

}

We definitely don't need that much whitespace hogging our screens.  It forces code off the screen, it increases scrolling, and generally slows us down when reading and understanding the code.

Indentation

} else {

    if let errorMessage = error?.userInfo?["error"] as? String {
        self.showErrorView(error!)
        }
    }

Your indentation is off there.  Each closing brace should have the same level indentation as the opening brace, unless they are on the same line, which is rare.

Naming

Your names should state what the function does or variable is, and only what the function does or variable is, and the variable/function shouldn't be/do anything but what the name says it is/does.

done() tells me nothing about what the function does.

qos doesn't tell me what the variable does, what it contains, or what it is used for.

self.loadObjects() appears to do UI updates, according to the comment.  Loading an object is not the same as displaying it, and loading and displaying from a single method violates the Single Responsibility Principle.


First of all it is always helpful to format your code properly (I now used the default code convention for Java):

int inputarray={3,5,2,6,7};
int inputlength=inputarray.length;
while (inputlength != 0) {
    for (int i = 0; i < inputlength-1; i++) {
        inputarray[i] = inputarray[i+1] + inputarray[i];
    }
    inputlength--;
}
System.out.println(inputarray[0]);

Also it is better to test for inputlength < 0 because then the termination of the loop is much more likely...

For performance tuning:

Try to create a formula for your problem to calculate the result. Your example could be reduced to 3 + 4*5 + 6*2 + 4*6 + 7...

Find a formula such like Gauss did for summing up the parts...


Condense repetitive jQuery .click function

Steps to fix this:

Add class 'amount-button' to all buttons
Add attribute data-mobileamount to all buttons and assign values like
100, 200, .. to each button.

For example:
<button class="amount-button" data-mobileamount="100" >Mobile Amount 100</button >
<button class="amount-button" data-mobileamount="200">Mobile Amount 200</button>

 (function($) {
  var mobileAmount = 300;
  $('.amount-button').click(function() {
    $('*').removeClass('-amount-active');
    $(this).addClass('-amount-active');
    mobileAmount = $(this).data('mobileamount');
  });
})( jQuery );


How to simplify a discord bot remote tool

This depends on the nature and purpose of the process.
For example, you might schedule your process as a coroutine, and cancel its execution with Future.cancel: https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel
Your process killing method is aggressive and quite risky, some more context around why you're cancelling processes and the nature of the processes would be useful for providing answers.


Persist data by serializing/deserializing objects that are sent to it

There is no point in catching the IOException and then throwing a new exception. You only loose information here. Either handle it or remove the try-catch altogether.

Also, use using to always dispose IDisposable objects.


You can build the LINQ query in several steps by appending new where clauses

IEnumerable<receipt> query = ReceiptList;
if (customer != null) {
    query = query.Where(x => x.CustomerId == customer.ID);
}
if (number != null) {
    query = query.Where(x => x.Number.Contains(number));
}
if (date != null) {
    query = query.Where(x => x.Date == date);
}
...
ReceiptListView = query.ToList();

This reduces the complexity from O(2ⁿ) to O(n)


First program with scraping, lists, string manipulation

You can use enumerate in order not to play with counter.

for counter,entry in enumerate(entries):
    if counter == 6:
        locations.append(entry.get_text().encode('ascii'))

states and cities would probably be a better name for collections of states/cities.
You can use unpacking when splitting the string

For instance :

for i in locations:
   city, state = i.split(", ")
   cities.append(city)
   states.append(state)

You don't need to store locations in a list and then iterate over the locations, you can handle them directly without storing them.

This is pretty much what my code is like at this stage :

#!/usr/bin/python

from bs4 import BeautifulSoup
from collections import Counter
import urllib2

url='http://olympics.usahockey.com/page/show/1067902-roster'
soup = BeautifulSoup(urllib2.urlopen(url).read())

cities = []
states = []

for table in soup.findAll("table", { "class" : "dataTable" }):
    for row in table.findAll("tr"):
        for counter,entry in enumerate(row.findAll("td")):
            if counter == 6:
                city, state = entry.get_text().encode('ascii').split(", ")
                cities.append(city)
                states.append(state)

print Counter(states)
print Counter(cities)

Now, because of the way American cities are named, it might be worth counting the cities keeping their state into account (because Portand and Portland are not quite the same city). Thus, it might be worth storing information about city and state as a tuple.

This is how I'd do it :

#!/usr/bin/python

from bs4 import BeautifulSoup
from collections import Counter
import urllib2

url='http://olympics.usahockey.com/page/show/1067902-roster'
soup = BeautifulSoup(urllib2.urlopen(url).read())

cities = []
for table in soup.findAll("table", { "class" : "dataTable" }):
    for row in table.findAll("tr"):
        for counter,entry in enumerate(row.findAll("td")):
            if counter == 6:
                city, state = entry.get_text().encode('ascii').split(", ")
                cities.append((state,city))

print Counter(cities)
print Counter(state for state,city in cities)

Also, something I have forgotten but might be useful to you is to use defaultdict if all you want is to count elements.

from collections import defaultdict

url='http://olympics.usahockey.com/page/show/1067902-roster'
soup = BeautifulSoup(urllib2.urlopen(url).read())

cities = defaultdict(int)
for table in soup.findAll("table", { "class" : "dataTable" }):
    for row in table.findAll("tr"):
        for counter,entry in enumerate(row.findAll("td")):
            if counter == 6:
                city, state = entry.get_text().encode('ascii').split(", ")
                cities[state,city] += 1


Use of TLS

I'm not completely sold on your use of TLS. This looks like a premature optimization to me, that said if you have measured and it improves your performance then keep it.

Static member

I think it would be better style to not have this static member but this is highly subjective.

Readability

Your code here:

    for (auto id = lock_is_free; ; id = lock_is_free) {
        if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }
        id = this_thread;
        if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }
    }

is very difficult to read for me. In fact I'm struggling to understand what the intended behaviour is. To me it looks like what you really wanted was:

// If we're being locked recursively, this will always compare false
// (insert your desired memory_order here) because no one can fiddle
// with `lock_owner` while we have the lock. If we're not entering
// recursively then this will always compare true because the thread
// doing the checking can only be in one place at one time.
if(lock_owner.load() != this_thread){
    // Okay so it's not a recursive call.
    do{
        auto id = lock_is_free;
    }while(!lock_owner.compare_exchange_weak(id, this_thread,
                                             std::memory_order_acquire,
                                             std::memory_order_relaxed));
}
// Okay in any event, recursive or not we have the lock now.
lock_count++;
return;

Note: I change compare_exchange_strong to compare_exchange_weak this is recommended when you call compare_exchange in a loop as per std::atomic::compare_exchange (cppreference.com).

I would much prefer this implementation of unlock()

void unlock(){
    assert(lock_owner.load() == std::this_thread::get_id());
    assert(lock_count != 0);

    --lock_count;
    if(lock_count == 0){
        lock_owner.store(lock_is_free, std::memory_order_release);
    }
}

Following the style of std::mutex::unlock() stating that calling unlock when the calling thread doesn't own the lock is undefined behaviour we can simply satisfy ourselves with the two asserts to aid during debug-time.


I would definitely recommend using enumerations. As this is December 2011, I would imagine your compiler supports an explicit underlying type on enumerations (GCC supported this since 4.4 and Visual C++ now supports it in 11.0). As a side note, <cstdint> is supported by visual c++ now (as of 10.0).

As an addenum to traditional c-style enumerations:

enum state : std::int8_t {
    S_UNKNWON,
    S_HIGH,
    S_LOW
};

Or adding scope to the enumeration's memebers (avoid polluting global scope):

enum class state : std::int8_t {
    unknown,
    high,
    low
};

state status = state::unknown;

Of course, after looking at boost::tribool, I would recommend that over anything -- unless you really need to ensure that state is exactly 1 byte.


With respect to your title_screen function:

You are not using the standard python functions for operating on paths. Try using pathlib:

from pathlib import Path

Assets_base_path = Path('/path/to/assets')

def title_screen():
    background = Assets_base_path / 'title_screen.png'

In your while not enter_game loop, you are setting the enter_game
status from the event loop, but that won't affect anything until the entire loop is completed. I'd suggest moving that code down to the bottom
of the loop.
Your code calls this line:

game_display.blit(pygame.image.load(background), (0, 0))

over and over again. The loaded image should be cached - just load it into a variable outside the loop, instead of reading it from disk each time.
You have this code:

font = pygame.font.Font(fonts_path + 'Futura.ttf', font_size)
game_display.blit(font.render(str('An RPG'), True, Color.Black), (500, 111))

And a similar statement elsewhere in the function. I would suggest writing a helper function that does this work for you. Something like this:

def show_text(locn, text, *, color=None, font=None):
    global Game_display

    if font is None:
        font = get_current_font()

    if color is None:
        color = Color.Black

    Game_display.blit(font.render(text, True, color), locn)

Then you can just write:

  futura = pygame.font.Font(Fonts_path / 'Futura.ttf', font_size)
  # NB: Might have to use str() if pygame.font doesn't support pathlib

  show_text((500, 111), 'An RPG', font=futura)

In your collision-detection code, you have repeated code. I'd suggest that you write a function to handle updating your rectangle position:

future = copy(player)
move_rect(future)
future.refresh_rect()

Furthermore, you are concatenating two lists and then discarding the result, when all you really need to do is check the lists separately:

if pillar_hits or wall_hits:
    pass
else:  # No hits

Finally, you might consider just keeping the future-player variable, which is a copy() of player, when you accept the move:

else:  # No hits
    player = future


I think that you can rewrite the code in a more OO way, with the help of an NSDictionary and setting up a sort of command pattern.

You can store a sum of the two enumerator value as a key of the Dictionary in this way :

NSDictionary *dicAngles = [[NSDictionary alloc] initWithObjectsAndKeys:
        (UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft), -(M_PI / 2.0),     (UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeRight), (M_PI / 2.0),
(UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft), (M_PI / 2.0),
(UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeRight), -(M_PI / 2.0),
 nil];

Once you have the dictionary you can avoid the if - else control flow in this way :

 CGFloat angle = 0;
 //Retrieve the angle from the dictionary
 angle = [dicAngles objectForKey: ( fromInterfaceOrientation + appOrientation )];

It is only an example and not tested, but could be a more elegant solution i think ...


Is ToEnumerable for multiple items a good practice?

As developers we're pretty used to where the keys for all kinds of brackets, braces and parenthesis are and while I agree you may save (a negligible amount of) twists and turns of the wrist, you're just substituting keystrokes for keystrokes, IMO.

You've already made me (as a colleague) have to remember this exists, as opposed to what I know naturally within the language itself; I've no aversion to such a thing, obviously it is part of our job to build on things with the language, but only in cases where it is a concern - this really isn't a concern. Also, I now have to potentially type even more to get my list.

Or is it a concern?..

With all the other keystrokes required from day-to-day second-to-second that utilise modifier keys I think we can rule out the 'saving' this seems to want to achieve, when you look at it relatively.

On the other hand, for the most part we use a powerful IDE (I pity you if this isn't the case), any modern IDE will give you many shortcuts for productivity (such as Visual Studio's snippet insertion, Intellisense and auto-completion) which means we don't need to create unique constructs for such trivial concerns. Sure, it also means your construct can be utilised just as quickly, but becomes redundant as it isn't necessarily quicker. The argument could then be put forth that using these tools stands to mitigate human error.

And, what's wrong with an array? If you don't want something to be treated as an array, use a collection of different sorts.


Instead of defining the IExtractor interface, wouldn't it be simpler with a function?

In this question, I assume that ExtractorName is a stand-in for something you'd really want the extractor to do, because otherwise, as the OP is stated, the extractor doesn't really do anything. In this case, an extractor is nothing by a string, but I assume that in reality, it'd be a function.

This would enable you to make the Extractor module simpler:

module Extractor =

    let private fooExtractor url =
        if url = "foo"
        then Some "Foo Extractor" // Stand-in for actual implementation
        else None
    let private barExtractor url =
        if url = "bar"
        then Some "Bar Extractor" // Stand-in for actual implementation
        else None

    let private extractors = [fooExtractor; barExtractor]

    let create url =
        extractors
        |> List.choose (fun candidate -> candidate url)
        |> List.tryHead

Each element of extractors is a function with the type string -> string option. In order to be useful, the return value should probably be another function that you can subsequently call; something like string -> ('a -> 'b) option.

Note the use of List.choose to pick only those functions that return Some 'a. Instead of the object-oriented Try/Parse pattern, you can indicate match success or failure with an option value.

Usage can be simplified as well:

let input = "https://www.customsite.com?fd=cWz5d"
match Extractor.create input with
| Some x ->
    // do stuff with extractor
    printfn "%s" x
| None -> printfn "%s" "No extractor found; exiting."

Here, we're simply printing the name of the extractor, since x is a string, but if you imagine that x was instead a function, you'd be able to call it.