Linux: Raku script to open files from terminal and ask for deletion

If I just run your program without any arguments, this is what I get:
Usage:
  foo.raku <pattern> <ext> [<del>] -- Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion

That's not super helfpul, so let's tackle that first.
#| Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion
sub MAIN(
    $pattern is copy, #= The pattern to match against (use 'all' to match everything)
    Str $ext, #= The extension for the file
    Str $del? where ( $del ∈ < del nodel > ) #= Options for opening ('del' or 'nodel', defaults to 'nodel')
        = "nodel"
) {
   ...
}

This produces much nicer output:
Usage:
  foo.raku <pattern> <ext> [<del>] -- Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion

    <pattern>    The pattern to match against (use 'all' to match everything)
    <ext>        The extension for the file
    [<del>]      Options for opening ('del' or 'nodel', defaults to 'nodel')

One thing you'll note is that the #= syntax doesn't play nicely with default values, so while I normally prefer using #= for parameters, the #| might be better when you have defaults.  I personally like to let it breathe a bit more when doing this, but YMMV.
#| Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion
sub MAIN(

    #| The pattern to match against (use 'all' to match everything)
    $pattern,

    #| The extension for the file
    Str $ext,

    #| Options for opening ('del' or 'nodel', defaults to 'nodel')
    Str $del? where {$del <del nodel>} = "nodel"
) {
    ...
}

You'll notice I adjust the $del where clause a bit.  Where clauses expect a block, and using parentheses like you did along with the default value can cause problems IME where the equals sign gets gobbled into the block implied block, so explicit blocks are safest.  Because you've set a default value, you don't need to mark it as explicitly optional.
Now let's look at your main code.  First we have the line
my @files = '.'.IO.dir(test => /.*$pattern.*\.$ext/);

First, instead of '.'.IO, you can use $*CWD, which identifies the purpose a bit better.  Your regex pattern is a bit off also.  Let's comment it and you'll see what's going on:
    my @files = $*CWD.dir:
        test => /
            .*        # match any characters
            $pattern  # then the pattern
            .*        # then any characters
            \.        # then literal period
            $ext      # then the extension
        /);

Regexen declared with / / aren't anchored to the start or end, so the initial .* isn't necessary.  OTOH, you will want an explicit end so you can do
    my @files = '.'.IO.dir:
        test => /
            $pattern  # the pattern
            .*        # then any characters
            \.        # then literal period
            $ext      # then the extension
            $         # and end the filename
        /);

It might add a few lines to your code, but commenting regex is a very good idea and can help you catch bugs sometimes.
Now in your main logic block
    for @files -> $file {
        my @args = 'xdg-open', $file.basename;
        my $command = run @args;
        $command.exitcode == 0 or die "system @args failed: $!";
        if $del eq 'del' {
          my $delete = prompt("\n \n Delete file $file (s/n) ");
          next if $delete ne "s";
          say "mv $file /tmp/$file";
          $file.IO.move("/tmp/$file");
        }
        my $exit = prompt("\n Press 'q' to end, return to continue ");
        last if $exit eq q{q};
    }

Separating out your arguments for run into a separate variable is nice, although obviously not strictly necessary.  Because the result of run is truthy based on its success, and we don't use the exit code anywhere else, we can just put the run inside the unless clause.  If that's compacting too much into too small of a space for you, or if you'll need to use the exit code for later expansions of the script, you could use my $command = run @args; fail '...' unless $command.  (ht Brad in comments).
One thing to consider is if you really want to die.  I don't know the xdg-open command personally, so not sure its mechanics.  If you do need to die (terminates the entire script), then by all means do so.  But since each file is being handled separately, perhaps you'd prefer to warn the user and continue with the others.  In that case, you could use a fail, optionally with a CATCH handler to provide more detailed support:
    for @files -> $file {
        my @args = 'xdg-open', $file.basename;

        fail "system @args failed: $!"
            unless run @args;

        if $del eq 'del' {
            my $delete = prompt("\n \n Delete file $file (s/n) ");
            next if $delete ne "s";
            say "mv $file /tmp/$file";
            $file.IO.move("/tmp/$file");
        }

        my $exit = prompt("\n Press 'q' to end, return to continue ");
        last if $exit eq 'q';

        CATCH {
           .message.say;
           next if prompt "Would you like to continue processing other files?" eq "y";
           exit 0;
        }
    }

You'll notice I also gave it a little bit of extra space.  Think of it like separating paragraphs in your code.  I would recommend against using q{q} to match q, just use 'q'.  The special quote structures have their place, but this doesn't feel like one of them.
For the final bit of code, the same thing I mentioned about the regex will apply.  For the output:
    say "-" x 60;
    for @files -> $file { $file.Str.say }
    say "-" x 60;

Works well, but the middle line can be greatly simplified to .Str.say for @files.


Pass by const reference to prevent copying and modification:
int expressiveWords(std::string const& base_string, std::vector<string> const& words)
                                ^^^^^^                                  ^^^^^^

bool is_stretchable(std::string const& base_string, std::string const& words)
                                ^^^^^^                          ^^^^^^

    for (auto const& word : words)
              ^^^^^^

This prevents the strings being copied into the function. It will also catch situations were you accidentally try and modify the string.

Please add braces {} around sub blocks.
It will save you one day without you even knowing. Issues caused by missing braces are notoriously hard to find because they are caused when sombody else does something nasty that affects your code (multi line macros come to mind).

One variable per line:
   int left_a = 0, right_a = 0;

Its not going to hurt you to add an extra line and it makes the job easier for the next person.

Not sure it is worth it.
But just to be complete you could use a standard algorithm to count.
    int count = 0;

    for (auto &word : words)
        if (is_stretchable(base_string, word))
            count++;

    return count;

    // ---

    return std::count(std::begin(words), std::end(words),
                      [&base_string, this](auto const& word){return is_stretchable(base_string, word);});


Root to leaf path with given sum in binary tree

Give your operators some breathing space.

    if (!node) {
        return sum == 0;
    }

    return hasPathSum(node->left,  sum - node->data) ||
           hasPathSum(node->right, sum - node->data);

Note that return expression needs no parenthesis.
sum - node->data seems more natural to be expressed once:

    sum -= node->data;
    return hasPathSum(node->left,  sum) ||
           hasPathSum(node->right, sum);

I see no edge cases except possible overflows.


Haskell tips/why doesnt this scale linearly?

Just a quick observation: as the length of values and centers increase, the list indexes (!!) are increasingly inefficient. Try values :: Vector Float, centers :: Vector Center with Data.Vector.(!) and see if performance improves.

I'm trying to see what other improvements can be made, I have a few in mind but its difficult to understand how your code works without the full program. Would you mind linking to a pastebin?


Instead of diving into cumbersome and lengthy regex expressions consider the following improvement/correction:

The main thesis for the underlying aspect is:

  Numeric literals containing a decimal point or an exponent sign
  yield floating point numbers.

https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex

Therefore Python treats values like 53.5e93, -90e3 as float type numbers.

Eventually I would proceed with the following approach (retaining those cute icons) including additional small optimizations:

from typing import TypeVar, Optional

def is_numeric(input_string: Optional[str]) -> bool:
    """
    Returns True for valid numbers. Acceptable types of items: str or None
    """
    if input_string is None:
        return False

    try:
        input_string = input_string.strip()
        float(input_string)
    except ValueError:
        return False
    return True

if __name__ == "__main__":
    # ---------------------------- TEST ---------------------------
    DIVIDER_DASH = '-' * 50
    GREEN_APPLE = '\U0001F34F'
    RED_APPLE = '\U0001F34E'

    test_input_strings = [None, "0  ", "0.1", "abc", "1 a", "2e10", "-90e3",
                          "1e", "e3", "6e-1", "99e2.5", "53.5e93", "--6", "-+3", "95a54e53"]

    count = 0
    for string in test_input_strings:
        print(DIVIDER_DASH)
        count += 1

        if is_numeric(string):
            print(f'{GREEN_APPLE} Test {count}: `{string}` is a valid number.')
        else:
            print(f'{RED_APPLE} Test {count}: `{string}` is not a valid number.')

The output:

--------------------------------------------------
 Test 1: `None` is not a valid number.
--------------------------------------------------
 Test 2: `0  ` is a valid number.
--------------------------------------------------
 Test 3: `0.1` is a valid number.
--------------------------------------------------
 Test 4: `abc` is not a valid number.
--------------------------------------------------
 Test 5: `1 a` is not a valid number.
--------------------------------------------------
 Test 6: `2e10` is a valid number.
--------------------------------------------------
 Test 7: `-90e3` is a valid number.
--------------------------------------------------
 Test 8: `1e` is not a valid number.
--------------------------------------------------
 Test 9: `e3` is not a valid number.
--------------------------------------------------
 Test 10: `6e-1` is a valid number.
--------------------------------------------------
 Test 11: `99e2.5` is not a valid number.
--------------------------------------------------
 Test 12: `53.5e93` is a valid number.
--------------------------------------------------
 Test 13: `--6` is not a valid number.
--------------------------------------------------
 Test 14: `-+3` is not a valid number.
--------------------------------------------------
 Test 15: `95a54e53` is not a valid number.


This code seems to be a specific BucketSort made for a specific program. I would instead create a more generic BucketSort:

public static <E extends Comparable<E>> void bucketSort(E[] array) {
    // ...
}

public static <E> void bucketSort(E[] array, Comparator<E> comparator) {
    // ...
}

Note there is two methods; one is for a class that implements the Comparator interface, and one to allow a Comparator to be passed as the Comparator for the class, where there is no comparator, or if you want to compare it in a different way.

Then the only problem is that you don't know the bounds for the buckets; the simple way would be to use bounds provided by the calling method:

public static <E extends Comparable<E>> void bucketSort(E[] array, E[] separators) {

}

public static <E> void bucketSort(E[] array, E[] separators, Comparator<E> comparator) {

}

The separators will be the upper limit of the bucket right before it; and the uppermost bucket will catch everything that is larger than the largest bound.

Now for the actual code:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class BucketSort {

    public static <E extends Comparable<E>> List<E> bucketSort(E[] array,
            E[] separators) {
        Comparator<E> comparator = new Comparator<E>() {

            @Override
            public int compare(E element1, E element2) {
                return element1.compareTo(element2);
            }

        };
        return bucketSort(array, separators, comparator);
    }

    public static <E> List<E> bucketSort(E[] array, E[] separators,
            Comparator<E> comparator) {
        final int numOfBuckets = separators.length + 1;
        // Create Buckets
        // Used ArrayList because we don't need the functions of a LinkedList
        List<Bucket<E>> buckets = new ArrayList<Bucket<E>>(numOfBuckets);
        for (int i = 0; i < numOfBuckets; i++) {
            buckets.add(new Bucket<E>());
        }
        // Sort into Buckets
        for (E element : array) {
            // Use binary search
            buckets.get(bucketNumber(element, separators, comparator)).getItems().add(element);
        }
        // Sort buckets
        for (Bucket<E> bucket : buckets) {
            bucket.getItems().sort(comparator);
        }
        // Combine Buckets and return
        for (int i = 1; i < numOfBuckets; i++) {
            buckets.get(0).getItems().addAll(buckets.get(i).getItems());
        }
        return buckets.get(0).getItems();
    }

    private static <E> int bucketNumber(E element, E[] separators,
            Comparator<E> comparator) {
        return bucketNumber(element, separators, 0, separators.length,
                comparator);
    }

    private static <E> int bucketNumber(E element, E[] separators, int low,
            int high, Comparator<E> comparator) {
        if (low + 1 == high) {
            return low;
        }
        int searchIndex = (high - low) / 2 + low;
        int compareResult = comparator
                .compare(element, separators[searchIndex - 1]);
        if (compareResult == 0) {
            return searchIndex;
        }
        return compareResult < 0 ? bucketNumber(element, separators, low,
                searchIndex, comparator) : bucketNumber(element, separators,
                searchIndex, high, comparator);
    }

}

class Bucket<E> {

    private List<E> elements;

    public Bucket() {
        this.elements = new LinkedList<E>();
    }

    public Bucket(Collection<E> elements) {
        this.elements = new LinkedList<E>(elements);
    }

    public List<E> getItems() {
        return elements;
    }

}

Yes, I know it looks 10x more complex than it need to be, but this can be used for further applications.

Since you asked for an explanation of the separators array...

The separator's array is there so that the method can know where to separate it into buckets. For example:

separator = [2, 5, 8, 11]
array = [1, 7, 2, 6, 4, 8, 12, 10, 13, 0, 5, 3, 9, 11]

Then the buckets would be:

buckets = [ [0, 1] , [2, 3, 4] , [5, 6, 7] , [8, 9, 10] , [11, 12, 13] ]


The easiest way to solve this with one dictionary is to simply create an action for the Button.ButtonClickedEvent calls:

public static readonly Dictionary<KeyCode, Button.ButtonClickedEvent> KeysUIElementsWithButtonEvents = new Dictionary<KeyCode, Button.ButtonClickedEvent>
{
    { KeyCode.P, SpellbookButton.onClick },
    { KeyCode.Escape, SettingsMenuButton.onClick },
};

public static readonly Dictionary<KeyCode, Action> KeysUIElementsWithActions = new Dictionary<KeyCode, Action>
{
    { KeyCode.LeftAlt, SwitchCursorState},
};

Can be one Dictionary<KeyCode, Action>:

public static readonly Dictionary<KeyCode, Action> KeysUIElementsWithActions = new Dictionary<KeyCode, Action>
{
    { KeyCode.P, () => SpellbookButton.onClick.Invoke() },
    { KeyCode.Escape, () => SettingsMenuButton.onClick.Invoke() },
    { KeyCode.LeftAlt, SwitchCursorState }
}

Then this:

private void CheckUIKeysCollection<T>(Dictionary<KeyCode, T> collection)
{
    foreach (var item in collection)
    {
        if (Input.GetKeyDown(item.Key))
        {
            if (Cursor.lockState == CursorLockMode.Locked)
            {
                Settings.Settings.SwitchCursorState();
            }
            if (item.Value is Action)
            {
                (item.Value as Action).Invoke();
                continue;
            }
            (item.Value as Button.ButtonClickedEvent).Invoke();
        }
    }
}

Becomes this:

private void CheckUIKeysCollection(Dictionary<KeyCode, Action> collection)
{
    foreach (var item in collection)
    {
        if (Input.GetKeyDown(item.Key))
        {
            if (Cursor.lockState == CursorLockMode.Locked)
            {
                Settings.Settings.SwitchCursorState();
            }
            item.Value.Invoke();
        }
    }
}

No more generics, no more casting, no more inferences. Simply create an action that calls the ButtonClickedEvent.Invoke() method for the appropriate Button.

You could, also, create a method that does that for you:

public void ClickButton(Button button)
{
    button.onClick.Invoke();
}

Then make your dictionary:

public static readonly Dictionary<KeyCode, Action> KeysUIElementsWithActions = new Dictionary<KeyCode, Action>
{
    { KeyCode.P, ClickButton(SpellbookButton) },
    { KeyCode.Escape, ClickButton(SettingsMenuButton) },
    { KeyCode.LeftAlt, SwitchCursorState }
}

This also means it's simpler to click buttons from anywhere in your code: simply call ClickButton(Button), instead of Button.onClick.Invoke().

Apart from that:

Using is then as is not recommended, simply use as then check if it's null:

var temp = value as string;

if (temp != null)
{
    Console.WriteLine(temp.Length);
}


Number of capture groups in a regular expression in php

You might consider non-capturing groups

(?:/*pattern*/)

These will match your regex but won't normally be operated on in whatever code is running the regex you're evaluating.


To first answer your question about the die/1, you are using COPY to get a range of multiple values out of the source block.  You probably want SET to get a single value:

>> parse [d12] [copy die word! (probe die)]
[d12]
== true

>> parse [d12] [set die word! (probe die)]
d12
== true

So concretely:

dice-rule: [
    (total: 0)
    some [
        set die word!
        (total: total + roll 1 get die)
    |
        set n integer!
        set die word!
        (total: total + roll n get die)
    ]
]

Broad dialect design concern: you've decided that a symbolic word that looks up to an integer will represent a dice roll of that integer value.  You then have another meaning for literal integer values.  This ties your hands a bit because it means you can't do ordinary variable substitution.

For instance, what if instead of:

dice: [d2 20 d100 d10 5 d6]

I wanted to write:

x: 20
y: 5
dice: [d2 x d100 d10 y d6]

You could use get-word for this form of non-dice substitution:

dice: [d2 :x d100 d10 :y d6]

But the general heuristic of coming up with dialects is to only dig out a small bit of keyword space, so such an "ugliness" isn't necessary most of the time.  Most dialects pick out a finite set of keywords, but there's probably nothing universally wrong with taking all the d* words.

Yet consider a possible alternative, more like the substitutions in parse, where brackets would be optional:

dice: [
    die 2
    20 [die 100]
    [die 10]
    5 die 6
]

Which you might then allow as substitutions, maybe:

d2: [die 2]
d100: [die 100]
d10: [die 10]
d6: [die 6]

dice: [d2 20 d100 d10 5 d6]

Further, I'd think that the dialect (which you might call dice-roll) should provide all the values of the roll.  It's easy enough to sum if that's what people want...but sometimes you might want the highest value, or lowest, or know if there were any doubles of the same value/etc.

Other quick notes.  If you know b is a block, say so in the function specification:

calculate: function [b [block!]] [
    ...

That checks the type at the callsite, and in Red it offers more of an advantage for static typing in the compiler.

I'd define roll before I defined the dice-rule.  Also, by using a func instead of a function you are allowing result to bleed into the calculate function body.  If you don't have a good reason for that, I'd avoid it... func shouldn't be used for performance reasons, but rather when you really do not want to introduce a new context.

Especially if you go with my suggestion to make die a word in your dialect, I might use another word for the integer representing the number of possibilities on the die...perhaps something like radix.


Firstly and unfortunately, there isn't an immediate plan to replace the entity specific ADO.NET with an ORM.

That's fine.

This is more questionable:

private int GetSqlOutputParam() { return 1; }

It would be much clearer to declare this as a descriptively named constant near the top of the class (being class-level scoped):

private const int defaultEntityId = 1;

But that's far from being what's making that code hard to test.

  I would like to start by making the code a little more testable by
  removing all persistence calls from the business logic layer, or
  separating the actual logic away from these calls while keeping them
  in the same layer. Instead of update() and read() littered throughout
  those manager classes, the object would be passed around as much as
  needed.

A class such as an OrderHeader exists to hold data. Nothing less, but also and more importantly nothing more. It's a Plain Old CLR Object, a POCO. You hit the nail on the head, that's exactly what you need to do. Move the ADO.NET code into its own class.

As much as I dislike this pattern when it's used on top of Entity Framework, if I had to refactor some ADO.NET code into its own class, I'd probably write something like a repository:

  This blog post (click the diagram) explains how dependency inversion enables testing.

  (I am not the author of the blog this link points to, it's pure coincidence that this guy's name is Mat. I'm not this Mat's Mug.)


EDIT: Possible race condition

I would not accept this code to production without proper documentation containing good proof, that it works as expected. lock (node.Previous) could get interrupted by another Remove changing node.Previous after it was passed to Monitor.Enter which smells too much (it will lock removed node instead of the one it should). Changing the order of locks may introduce dead-lock (starvation).

Let us start by Insert(1); Insert(2); Insert(3) and then call Remove from three different threads. 3rd thread will call lock (node.Previous) which contains two parts - first fetching node.Previous and then calling Monitor.Enter. Let us suspend this Remove(3) in between - fetching Node(2), but not yet calling Monitor.Enter (or suspend inside, but before it can do anything). Let us now finish Remove(2), which will change Node(3).Previous = Node(1). Let us continue 3rd thread, which will lock removed Node(2) (instead of Node(1)) and Node(3) reaching line node.Previous.Next = null. It won't crash here because lock introduces memory barrier (thus node.Previous will trully read Node(1), not the locked Node(2)). Let us suspend 3rd thread here and start 1st thread calling Remove(1), locking _root, Node(1) passing if (node.Next == null) going to else lock (node.Next). Let us now suspend this thread and continue in 3rd thread that was about to do node.Previous.Next = null. Compiler will probably cache node.Next in 1st thread, but what if it does not? lock (null). We could rewrite it (var next = node.Next; if (next == null) { ... } else lock (next)), now 1st thread will block until 3rd finishes, but is still left with node.Next = null possibly crashing in if (node.Next.Prevous == node) and even if we change that to if (next.Previous == node) next.Previous = ... it changes state of removed node which you could try to remove again... and it is all looking like not worth the effort.

Single ReaderWriteLockSlim is safe to use and the performance will still probably be good enough. Using lock only for writing (Insert, Remove) and leaving GetEnumerator without any locking may still be possible - read my original answer (3rd point).

Original answer

I will leave my original answer here as there may still be some valuable information, but I do not trust the locking now. It won't dead-lock and although I cannot proove race-condition corrupting the state (not one that could not be fixed), I myself will never use such collection, unless somebody can describe unbreakable proof that it is safe.

My reasoning why the locking is safe

All the locks are taken in same order (from root to end, forward direction), which means removal of newer nodes can block threads that are currently trying to remove older node, but there is no loop for possible starvation - the thread removing newer node will block the other temporarily, do its job and then the other can continue. There is small incosistency in Insert where you first lock the node that will become the last and then lock the last node (which is reversed order of locking), but I believe you don't even have to lock the inserted node, because it won't be visible until _end = _end.Next = node;
You always lock _end before changing it (the node _end points to). You also hold the lock of the node that will become _end after the operation (_end.Previous if removing, not necessary in Insert because nobody can see the node until you publish it by _end.Next = node and only GetEnumerator() can see it, Remove would need to lock _end first, which it cannot, until you finish inserting).
GetEnumerator does not need any lock, because removed nodes retain their Next (which is internal - some private nested interface could maybe protect it even better a bit like friend in C++, but internal appears to be sufficient for your use-case). That means that even if you remove the node that is current in GetEnumerator, you can still safely iterate. Nobody can reinsert the node or modify Next. current.Next is always node that at least existed when you started iterating (as long as pointer assignment is atomic).

Lines I deem unnecessary / redundant

lock (node) inside Insert - already described, lock (_end) is enough (and the order should be lock (_end) lock (node) to preserve the order of locking - forward).
if (node.Previous.Next != node) return; inside Remove. How could that happen? Not in normal usage, but if we consider that you could possibly call Remove multiple times for the same node. In that case, I would mark removed nodes by Previous = null and to make Remove not corrupt the state if you pass node from different list, I would change _root + _end to single doubly-linked node (add Previous to BaseNode) and make the list hybrid - null-terminated in forward direction and root-terminated in backwards direction (cyclic, starting with _root.Previous = _root). That can be implemented in such a way, that Remove could be static (not that it should, but could - does not need to access _root, all it needs is the node). That means that Remove could safely remove nodes from any list.

Style / design / naming

Node is too generic for global space (and you should use namespace). I would make it public nested (I hope you can still make the list implement IEnumerable<Node>), have Next and Previous private, add private interface to Node with Insert and Remove that will be called by the list (and Insert only as Insert => _root.Insert(value) and Remove => ((INode)node).Remove(), while having INode _root as well as Next and Previous) to protect everybody including yourself from modifying Next/Previous in unacceptable way.

P.S.: Having Next typed as Node (as you currently have) may be better for performance (needing ((INode)_root).Insert(value) which is safe cast, compiler knows it is valid). The originally proposed version (having INode-typed Next) would need casting in GetEnumerator that would have to be runtime-checked.


Is this binary search close to idiomatic OCaml?

Generally speaking, yes. I only have a couple of minor remarks.

let cmpx = cmp x in

Using partially-applied functions is actually slightly slower with the native-code compiler. The cmp function (like most functions) isn't going to do anything until it gets all its arguments, so cmpx under the hood is fun y => cmp x y. It's faster (not by much, but it can matter in an inner loop) if you write let delta = cmpx x (Array.get arr mid) below.

Speaking of which, arr.(mid) is exactly identical to (Array.get arr mid), but more usual. If you're going for speed, write Array.unsafe_get arr mid, which will save a few cycles, at the expense of putting the onus on you to verify that you are not making an array access out of bounds (here, it's easy to see that you are not).

You have many superfluous parentheses; they are a little surprising to a habitual Ocaml programmer. let … in … has lower precedence than anything else, and if … then … else … has lower precedence than arithmetic and function calls. This is how I'd write your function:

let binsearch ~arr ~cmp x =
  (* Assuming arr is ordered according to cmp, then [bs min max] is an   *)
  (* index of a value v in arr such that [(cmp x value) = 0] between     *)
  (* min (inclusive) and max (exclusive).                                *)
  let rec bs min max =
    if min >= max then
      None (* we are down to an empty slice of the array *)
    else
      (* mid is always strictly less than max because min < max. *)
      let mid = (min + max) / 2 in
      let delta = cmp x (Array.unsafe_get arr mid) in
      if delta = 0 then Some mid else
      if delta < 0
      then bs min mid
      else bs (mid + 1) max
  in bs 0 (Array.length arr);;

(Details of when to put newlines, especially relative to in, are matters of taste.)


Long switch statement to lookup fifty-something commands

Giant switch statements are a code smell.  In Java, the usual remedy is to refactor using the Replace Conditional with Polymorphism recipe.

However, I think your problem runs even deeper.  I raise the following objections:

Why should this code exist at all?  Shouldn't getCommand(commandType, agentId); just return the appropriate result for all values of commandType?  Or are there specific command types that you want to disable?  The latter possibility seems disturbing.  If this code is, say, part of a permission-checking system to allow only certain types of commands, I would say that the permission-checking system is woefully underdeveloped.
Why does getCommand(…) return a String?  What use could a constant-to-string translation possibly have?

I wish I could give you more constructive suggestions, but unfortunately, you haven't presented much context in the question to allow a deeper analysis.


The HTML you submitted was invalid. I changed the following things so your html would be valid:

Don't put
 tags inside a table. Header tags are used for headings only. Don't use headings to make text BIG or bold. Use CSS for positioning and font sizing.
In a table, the
 tag is the first tag that should appear.
In the  tag, the attribute alt is required. The alt attribute specifies alternate text for an image if the image cannot be displayed.

Your HTML validated:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

Food you love to eat

                I love eating food . All types of food are good for health. I like fruits in them. Fruits are good for health.


Java implementation of the caesar-cipher

In my opinion, the main problem with your code is the duplication, here is my advices.

1) Put the ui code out of the conditions.

The only issue there, if the choice is invalid, you can either show a default string, or throw an exception.

        if (decision == 1) {
            out = encrypt(field, shift);
        } else if (decision == 2) {
            out = decrypt(field, shift);
        } else {
            out = "Invalid choice!";
        }

        JTextArea msg = new JTextArea(out);
        msg.setLineWrap(true);
        msg.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(msg);
        scrollPane.setPreferredSize(new Dimension(300, 300));
        JOptionPane.showMessageDialog(null, scrollPane);

Or

        if (decision == 1) {
            out = encrypt(field, shift);
        } else if (decision == 2) {
            out = decrypt(field, shift);
        } else {
            throw new IllegalStateException("Invalid choice!")
        }

        JTextArea msg = new JTextArea(out);
        msg.setLineWrap(true);
        msg.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(msg);
        scrollPane.setPreferredSize(new Dimension(300, 300));
        JOptionPane.showMessageDialog(null, scrollPane);

2) In the encrypt & decrypt, to create the string containing the result, i suggest that you use java.lang.StringBuilder instead of concatening the String; you will gain some performance.

    public static String decrypt(String text, int n) {
        int x = 0;
        int y = 0;
        StringBuilder out = new StringBuilder(); //Empty string for result.
        while (x < text.length()) {
            if (text.charAt(x) > 64 && text.charAt(x) < 91) {
                if (text.charAt(x) - n < 65) {
                    y = 26;
                }
                out.append(text.charAt(x) - n + y);
            } else {
                out.append(text.charAt(x));
            }
            x++;
            y = 0;
        }
        return out.toString();
    }

3) In the encrypt & decrypt, extract the text.charAt(x) in a variable, to remove the duplicates.

    public static String decrypt(String text, int n) {
        int x = 0;
        int y = 0;
        StringBuilder out = new StringBuilder(); //Empty string for result.
        while (x < text.length()) {
            final char currentChar = text.charAt(x);

            if (currentChar > 64 && currentChar < 91) {
                if (currentChar - n < 65) {
                    y = 26;
                }
                out.append(currentChar - n + y);
            } else {
                out.append(currentChar);
            }
            x++;
            y = 0;
        }
        return out.toString();
    }

4) The encrypt and decrypt methods are pretty similar, you can probably merge them if you want.

    //Encryption
    public static String encrypt(String text, int n) {
        return operation(text, n, true);
    }

    //Decryption
    public static String decrypt(String text, int n) {
        return operation(text, n, false);
    }

    public static String operation(String text, int n, boolean isEncryption) {
        int x = 0;
        int y = 0;
        StringBuilder out = new StringBuilder(); //Empty string for result.
        while (x < text.length()) {
            final char currentChar = text.charAt(x);

            if (currentChar > 64 && currentChar < 91) {
                if (isEncryption ? (currentChar + n > 90) : (currentChar - n < 65)) {
                    y = 26;
                }
                out.append(isEncryption ? (currentChar + n - y) : (currentChar - n + y));
            } else {
                out.append(currentChar);
            }
            x++;
            y = 0;
        }
        return out.toString();
    }
```


Since it is really difficult to tell what letter maps to what, it will be much easier to validate your code (for yourself & future maintainers) if you write out the dictionary directly:

CHAR_TO_MORSE = {
    'A': '._',
    'B': '_...',
    'C': '_._.',
    'D': '_..',
    'E': '.',
    'F': '.._.',
    'G': '__.',
    'H': '....',
    'I': '..',
    'J': '.___',
    'K': '_._',
    'L': '._..',
    'M': '__',
    'N': '_.',
    'O': '___',
    'P': '.__.',
    'Q': '__._',
    'R': '._.',
    'S': '...',
    'T': '_',
    'U': '.._',
    'V': '___.',
    'W': '.__',
    'X': '_.._',
    'Y': '_.__',
    'Z': '__..',
}
MORSE_TO_CHAR = {v: k for k, v in CHAR_TO_MORSE.items()}
CHAR_OR_MORSE_TO_INVERSE = {**CHAR_TO_MORSE, **MORSE_TO_CHAR}

Avoid string concatenation (+) when possible (mostly for performance):

print(' '.join("{}: {}".format(k, v) for k, v in CHAR_TO_MORSE.items()))

Very minor but check exit condition before parsing:

if user_input == 'EXIT':
    break
user_list = user_input.split()

What happens if the input contains neither a single char nor valid morse? Your program will eat it, potentially at the confusion of the user. Maybe you can default to printing a question mark; something like:

print(' '.join(CHAR_OR_MORSE_TO_INVERSE.get(c, '?') for c in user_list))

Note that this uses a single dictionary lookup per item user_list, which is about as efficient as you could ask for.


If you don't want to write to the file directly and want to "apply" the changes at once, instead of writing to a temp file, you can keep the changes in memory - in a list of strings:

from sys import argv
from datetime import datetime
import os

if __name__ == '__main__':
    _, typed = argv
    filename = typed + ".txt"
    save_location = os.path.join('/home/user/', filename)

    print(save_location)
    print("Aditor: a digital typewriter, Type: d when done")

    date = datetime.now().strftime("%Y/%m/%d")

    cache = ["\n", date]
    while True:
        entry = input()
        cache.append("\n")

        if entry == 'done' or entry == 'd':
            break

        cache.append(entry)

    with open(save_location, "a") as f:
        f.writelines(cache)

Note that I've removed everything related to handling the temp file.

Also there were some other changes applied in the code above:

using 4 spaces for indentation
used _ for a "throwaway" variable (the script name is not used)
fixed the variable naming - words need to be separated with an underscore - save_location instead of savelocation (PEP8 reference)
checking for "done" using simple comparisons with done and d
using strftime() to dump a datetime into string
putting the code to under if __name__ == '__main__': to avoid the code to be executed if imported
organized imports per PEP8 (reference)


I would make the function take an optional argument.
This argument $mode could be your user defined logging level that would skip the normal logic to determine the reporting level.

An example could be:

public function set_error_reporting($mode = null) {

    $reporting = null;

    if(!is_null($mode)) {

        $reporting = $mode;

    }else{

        switch($this->debug_mode) {

            case 0:
                $reporting = 0;
                break;

            case 1:
                $reporting = E_ALL;
                break;

            case 2:
                $reporting = E_ALL;
                ini_set('log_errors', 1);  // Enable error logging
                break;

            default:
                $reporting = null;
                break;

        }
    }

    // Check if no reporting level was selected

    if(is_null($reporting)) {
        // throw exception (preferred) or emit an error.
    }

    error_reporting($reporting);
}

Then to set the error reporting level automatically.

$obj->set_error_reporting();

Or if you would like to specify another reporting level from a config file.

$level = E_ALL & ~E_NOTICE;  // Log all errors except notices.

$obj->set_error_reporting($level);

This will require you to fetch the reporting level configuration from outside the function. You could also add more case statements to the switch if you know they will be used beforehand.

Let me know if you have any questions or there is something you would like to point out.

Best regards.


Shell Script (Bash) to sum multiples of different arguments below a number

Arithmetic operations

If you look closely, something is a bit odd here:

for (( i = 0; i <= $limit; i+=$1 )); do

Ideas? How about: i is written without a dollar, but limit is written with a dollar... In fact you can drop the dollar from limit too, and the expression will be slightly simpler. From $1 you cannot drop it, as the meaning of 1 would be taken literally, because it's numeric, unlike the others.

The same is true for commonMultiple here, you can drop the dollar:

for (( i = 0; i <= $limit; i+=$commonMultiple )); do

The general rule is, in arithmetic operations within ((...)) you don't need to use the dollars in variable names.

Don't use backticks

Instead of this:

commonMultiple=`expr $1 \* $2`

This is the recommended writing style for sub shells:

commonMultiple=$(expr $1 \* $2)

Don't use expr

It's better to avoid expr, and you can do the same thing easier using Bash arithmetics, for example:

((commonMultiple = $1 * $2))

The for loops can be simplified similarly, instead of:

for (( i = 0; i <= $limit; i+=$1 )); do
    sumArg1=`expr $sumArg1 + $i`
done

You can write:

for (( i = 0; i <= limit; i+=$1 )); do
    ((sumArg1 += i))
done

Apply the same thing everywhere.


Computing the mean of 25000 values is summing up the values and dividing by 25000.
Computing the mean of 50000 values (the original 25000 plus 25000 new values) is summing up the values and dividing by 50000.  This means (no pun intended) you are adding up the first 25000 values over and over again each time you compute the mean.  And adding up 25000 values takes time.  As the length of the list grows, the time it takes to sum it grows as well.  Total complexity: \$O(n^2)\$

You could create a running total, and compute the mean yourself.

class CAP:

    def __init__(self, ...):
        ....
        self._sum = 0
        self._count = 0

    def update_capacitance(self):
        ...
        self._sum += sum(self.timeline[self._count:])   # Only add in the new samples
        self._count = len(self.timeline)
        DC_bias = (self._sum / self._count) / 1000

Feel free to use np.sum() if it is faster, or to ensure the required precision in the sum.

Appending values one-at-a-time to timeline is itself a time consuming process.  If you know you are accumulating samples in blocks of 25000 points, you could pre-allocate a buffer of 25000 points with np.empty(), and fill that in.  When it is full, after summing this small block into the running total, you could np.concatenate() to a larger timeline array.  Or append it to a list of buffers, and created a new buffer for the next block, and concatenate all the blocks together at the end.

You could also create a list of the means of these smaller buffers, and compute the mean of that list.  This may help avoid precision issues you would encounter in totaling a few million points.


It can be helpful to run hlint to see if it spots some improvements.  In this case, it notes that:

you can replace concat $ map with concatMap on line 13
you can replace flip (,) $ index with (,index) on line 14 if you enable the TupleSections extension, or at least drop the dollar sign if you don't

A few additional things it misses are:

you can drop the in let on line 25
you can replace sortBy (compare `on` snd) with sortOn snd in line 26

It's also generally accepted as good practice to put type signatures on top-level functions.  You may feel it looks cluttered, but it really helps others understand your programs.  For example, I had to add them before I started working on your program, just so I could figure out what was going on.

A larger stylistic issue is that idiomatic Haskell code typically doesn't create a lot of bindings for intermediate results that are only used once.  I suspect that you've gone this route (labelling untabbedLines and wordsedLines, etc.) for two reasons -- first, you're probably more used to an imperative programming style that lays out an algorithm as a series ordered steps, and all these bindings are helping you think through the process ("first, I remove the tabbed comments, second I make the lines into words, third I number them, etc., etc.); second, you may be using it as a kind of self-documenting coding style, but I think comments make better documentation than awkward camelcase pseudonouns like wordsedLines.

So, a more usual way of writing your preprocess would be:

preprocess input
  = concatMap indexDown
  $ flip zip [1..]
  $ map words
  $ map (takeWhile (/= '\t'))  -- comments start with tab
  $ lines input
  where
    -- number each word on the line with the index
    indexDown (words', index) = map (,index) words'

Howoever, it's also pretty standard replace the pattern foo x = f $ g $ h $ k x with the point-free form foo = f . g . h . k.  It's possible to get carried away with point-free code, but this particular transformation is pretty routine.  Some people might prefer to collapse the map over the lines, too:

preprocess
  = concatMap indexDown
  . flip zip [1..]
  . map (words . takeWhile (/= '\t'))
  . lines
  where
    -- number each word on the line with the index
    indexDown (words', index) = map (,index) words'

Also, in situations like this with maps at multiple levels (lines and words), it's worth considering if a list comprehension might not be easier to understand:

preprocess' :: String -> [(String, Int)]
preprocess' input =
  [ (w, i)
  -- get each numbered line of words
  | (i, ws) <- zip [1..]
               $ map (words . takeWhile (/= '\t'))
               $ lines input
  -- and process each word
  , w <- ws ]

A similar consideration applies to findDupes.  It would be more usual to collapse it into a single functional pipeline in point-free form:

findDupes :: [(String, Int)] -> Map.Map String [Int]
findDupes = Map.filter ((>1) . length)
          . Map.fromListWith (flip (++))
          . map (fmap (:[]))

However, I think map (fmap (:[])) is probably too clever by half.  At the very least, it would be clearer to import second from Data.Bifunctor and write map (second (:[])), though even better would be to just use a lambda which makes the intended transformation clear at a glance:

map (\(w,i) -> (w,[i]))

A rewrite of printDupes would probably look like:

printDupes :: Map.Map String [Int] -> IO ()
printDupes dupes =
  forM_ (sortOn snd $ Map.assocs dupes) $ \(w, idxs) ->
    putStrLn $ "Duplicated element " ++ w ++
               " found on positions: " ++
               (intercalate ", " $ map show idxs)

(Here, forM_ comes from Control.Monad and is just a flipped version of mapM_.)

One additional stylistic issue regards your handling of IO.  Here, the main function is responsible for actually performing input and then calls on a pure function to perform the processing.  When it comes time to generate output, though, it passes off that responsibility to another function.  Haskell programs are usually carefully organized around their IO, with a clear division of responsibility between the IO and the pure processing, and it's usual to have input and output all handled at the same "level".  I realize that sounds a little fuzzy and hand-wavy, but it boils down to this -- it would be more usual to localize input and output in main and have the remainder of the program (including printDupes) be pure.  So, printDupes would instead look something like:

printDupes :: Map.Map String [Int] -> String
printDupes =
  unlines . map render . sortOn snd . Map.assocs
  where render (w,idxs)
          = "Duplicated element " ++ w ++
            " found on positions: " ++
            intercalate ", " (map show idxs)

I also personally find it a little odd that findDups takes a list [(String,Int)] but then returns a Map String [Int].  The Map seems like an implementation detail, and it "feels" like the function ought to return a [(String,[Int])], and it might as well sort this list while it's at it.

Anyway, with all those changes and some renaming of functions, the final program might look like:

{-# OPTIONS_GHC -Wall #-}

import qualified Data.Map as Map
import Data.List

main :: IO ()
main = interact (renderDups . findDups . getWords)

getWords :: String -> [(String, Int)]
getWords input =
  [ (w, i)
  | (i, ws) <- zip [1..]
               $ map (words . takeWhile (/= '\t'))
               $ lines input
  , w <- ws ]

findDups :: [(String, Int)] -> [(String, [Int])]
findDups = sortOn snd . Map.assocs
         . Map.filter ((>1) . length)
         . Map.fromListWith (flip (++))
         . map (\(w,i) -> (w,[i]))

renderDups :: [(String, [Int])] -> String
renderDups = unlines . map render
  where render (w,idxs)
          = "Duplicated element " ++ w ++
            " found on positions: " ++
            intercalate ", " (map show idxs)


Optimizing performance of hashing array algorithm's implementation

The Good

The code is fairly readable, horizontal spacing is good.

The variables are declared as they are needed.

You didn't use using namespace std; which is very good for a beginner.

Macros in C++

Macros are included in C++ to support some backward compatibility with the C programming language that it grew out of, but they generally aren't used in C++ because they aren't type safe. Replacements for macros are inline functions, and lambda expressions or closures.

An alternate to what is in the code is to use typedef. A second alternative is to use using ll = long long;.

The best thing might be to find what types C++ supports and use that instead. You can find a list of the types provided by the cstdint header file here.

Another alternative is to just use long long rather than shortening it. C++ is not a scripting language and C++ coders are used to things like this.

Beginning a Variable or Function with Double Underscore.

Function names and variables should start with letters rather than underscores, double underscore is reserved for special usage.

Variable Names

Single letter variable names make the code very hard to understand, I don't even have a clue what c, q, l, r or v are or I would try to guess at their meanings.

Variables i and j are used as indexes into the vector, it would be better if these variables were of type size_t rather than long long because size_t is defined as unsigned and can't be negitive. It would very rare to have an array or vector that would require the address space of a long long.

One Variable Declaration Per Line

The code contains this line

        ll l, r, v;

To make the code more maintainable each variable should be declared and initialized on it's own line.

        ll l = 0;
        ll r = 0;
        ll v = 0;

Vertical Spacing

To make the code more readable it needs some vertical spacing, one line between logical blocks:

#include <vector>
#include <iostream>

using ll = long long;

ll __hash__(const std::vector<int> &arr) {
    ll front = arr[0];
    for(ll i = 1; i < arr.size(); i++){
        front = arr[i] - front;
    }
    return front;
}

int main() {
    std::vector<int> arr;

    ll size;
    std::cin >> size;
    for (ll i = 0; i < size; ++i) {
        ll c;
        std::cin >> c;
        arr.push_back(c);
    }

    ll q;
    std::cin >> q;
    for (size_t i = 0; i < q; ++i) {
        ll l, r, v;
        std::cin >> l >> r >> v;
        for(size_t j = l - 1; j < r; ++j){
            arr[j] += v;
        }
        std::cout << __hash__(arr) << std::endl;
    }

    return 0;
}


Looking for primes with all-different digits

You can use itertools.permutations() to generate your sequences of unique digits. Also consider using itertools.groupby() to organize things nicely.

So first you can create all your non-dup-digit numbers as strings:

nodups = [''.join(s) for s in permutations('1234567890', 6)]

As Josay mentioned in a comment, '0123456789' can also be expressed as string.digits in python.

And Daerdemandt reminds us to remove numbers starting with 0. For efficiency's sake, let's just construct a generator instead of a list.

nodups = (''.join(s) for s in permutations('1234567890', 6) if s[0] != '0')

Now if you were to call the list() constructor on this you'd get something like:

['123456', '123457', '123458', '123459', '123450', '123465', '123467', '123468', '123469', '123460'...]

Then you need to organize by hundreds digits, more specifically everything except the last 2 digits ([:-2]):

hundo = groupby(nodups, lambda n: n[:-2])

Now hundo contains some nested generators so it might be hard to inspect on the surface, but if you unpacked everything inside you'd find something like this:

{'1235':
        ['123546',
         '123547',
         '123548',
         ...
        ],
 '1234': ['123456',
          '123457',
          '123458',
          ...
        ]
  ...
}

Then organize each hundred-digit-group further by the tens digit, more specifically the second-to-last digit ([-2]):

hundreds = {h:{t:v for t,v in groupby(ns,lambda n: n[-2])} for h,ns in hundo}

That line is a bit of a mouthful, imagine the variables as

h -> hundreds group
t -> tens group
v -> the values in the tens group
ns -> the values in the hundreds group

You can kind of read it like "make a dictionary that maps each hundreds group to (a dictionary mapping each tens group in that hundreds group to the values in that tens group)."

Now they're organized to test in a structured way. Your check is, if I'm not misreading the problem statement:

all hundreds groups contain any (some) tens group with all not-primes

Or, in python:

all(
    any(
        all(not is_prime(int(n)) for n in ns)
        for ns in tens.values()
       )
    for tens in hundreds.values()
   )

If you want to log the counterexample, you could define a memoized_is_prime() function and use a global variable:

counter_example = None
def memoized_is_prime(n):
    global counter_example
    counter_example = n
    return is_prime(n)

You'd just have to access the counter_example variable afterwards if your check returns False.

Although note that the global keyword is not strictly necessary here, and using global-style patterns is discouraged in general. It it fine in this tiny program but if you were to extend this code in any way you'd probably want to encapsulate your memoization.

I haven't tested this, feel free to try it out and let me know if you have any questions.


F# program to generate a Map of substrings frequencies

Fortunately you're already following the functional idioms entirely. So that's a very good thing.

The only things I would comment on are a few minor details:

let occurrence = (head :: other |> Array.ofList |> String)

Those parenthesis are superfluous.

let updatedMap = match occurrenceTable.ContainsKey (occurrence) with
                 | true -> occurrenceTable.Add(occurrence, occurrenceTable.[occurrence] + 1.0)
                 | false -> occurrenceTable.Add(occurrence, 1.0)

In this case, you have a lot of whitespace to the left of the match conditions, usually in this case  I just break the match to a new line and then work from there.

let updatedMap =
    match occurrenceTable.ContainsKey (occurrence) with
    | true -> occurrenceTable.Add(occurrence, occurrenceTable.[occurrence] + 1.0)
    | false -> occurrenceTable.Add(occurrence, 1.0)

It's generally easier to read.

let total = Map.fold (fun acc key value -> acc + value) 0.0 occurrenceTable

I absolutely love to see fold used! I think it's far overlooked and definitely has many use cases.

In regards to this method:

let rec countOccurrences (input:string) (occurrenceTable:Map<string, float>) length =

You nailed tail-call recursion. I would be willing to bet that if you looked at the IL for this code you would see a beautiful tail. call in there. Excellent work!

Overall, beautiful work. I think you did a phenomenal job with this code. :)


Most of it looks fine to me, but why do you have void methods with out parameters? This makes no sense to me, and only serves to make usage more awkward. As such I would recommend:

public T Get()
{
    if (isDisposed)
        throw new ObjectDisposedException("Protected object is disposed");
    byte[] serializedObject = pBin.Get();
    T result = ULBinConvert.Deserialize<T>(serializedObject);
    serializedObject.Clear();
    return result;
}

Secondly, I don't like a lot of your variable names. You're not paying by the character, so there's no real benefit in shortening them at the cost of making it a slower read. pBin is significantly less readable than protectedBinary

You should also refrain from putting things like array into the variable name unless there is no better way to describe the variable. Most of the time it is unnecessary, as it is in pBArray or outArray.


Picking a random neighbouring cell, but only picking previously-visited ones if there aren't any unvisited

Using straight linq you could get to two iterations over Neighbours, assuming Neighbours is a class and not a struct.

var neighbour = current.Neighbours.FirstOrDefault(n => n.DeadEnd) ?? current.Neighbours.Where(n => !current.Linked(n)).First();

Pretty similar to yours except we using FirstOrDefault to return null if not found and using the ?? to execute the 2nd iteration if it's null.

If it is a struct then you would need to compare the FirstOrDefault to default.  At that point I would just do the FirstOrDefault and write an If statement on next line comparing it to default.

If you want to do it in one iteration then will need to break out into a foreach loop. The downside is it will be calling the Linked() method even if it will never be used. As needs to store the value just in case it can't find DeadEnd.

Neighbour defaultValue == null;
foreach (var neighbour in current.Neighbours)
{
    if (neighbour.DeadEnd)
    {
        return neighbour;
    } else if (defaultValue == null && !current.Linked(neighbour))
    {
        defaultValue = neighbour;
    }
}

return defaultValue;

Without knowing what Linked does - aka does it have side effects or performance issues.  This might not be the best answer.

As you can see from my review there are questions: Neighbours a class or struct?  Should post the source code for Neighbours.  What does Linked method do?  Because of this the code can't fully be reviewed and is not complete.  I would suggest you update your question to get better answers.


Looks great! I'm going to rehash the things that @Mike Shepard said because he's absolutely right but he wrote them in a comment, so I'll expand on them a bit first, and add a few more.

Approved Verbs

PowerShell has a concept of approved verbs. You can see them by typing Get-Verb at the prompt, but you should really look at the MSDN page on approved verbs for the rules and help with selecting appropriate verbs.

For your function I like the Split or Expand verbs, like Split-Object or Expand-Property.

Convert might also be appropriate based on the description, but it doesn't quite sound right to me.

Comment Based Help

Not too much to say about this that isn't covered in about_Comment_Based_Help, but yeah it's definitely good to have. One of the things that I think is overlooked is the .LINK keyword.

If you decide to publish this somewhere, you can use this to link to online documentation or examples or support.

Get-Help MyFunction -Online will automatically open a browser window to the first .LINK URL (you can have more than one listed).

Avoid Aliases

Not everyone agrees with this, but I do.

I love and use aliases all the time at the prompt, but when writing scripts, I use the full names of functions, cmdlets, parameters, etc. I truly think it makes things clearer and more readable.

In your script:

% should be ForEach-Object
select should be Select-Object

Tab completion makes it easier since you don't have to type all of the longer names.

CmdletBinding Attribute

This is minor, but you may want to use [CmdletBinding()] for your function. Obviously, it's not necessary since your function works, but it's worth reading about_Functions_CmdletBindingAttribute to get an idea of what it does, what it can do with its options, and how it might change the way your function works.

Parameter Naming

Your -Properties parameter should be named -Property. It is convention in PowerShell to use singular names, even for things that may accept or return multiple objects.

Parameter Binding

The -Properties and -ExpandProperty parameters are both optional, but calling the function with one or both of them missing gives less than stellar results.

So the function should be updated either to gracefully handle situations where they are missing, or they should be made mandatory (like -InputObject).

Select Redundancy

$x | select $Properties | select *, @{Name="$ExpandProperty";Expression={$y}}

You could avoid doing 2 selects there by combining $Properties and the hashtable used for $y:

$x | select ($Properties + @{Name="$ExpandProperty";Expression={$y}})

Or you could pre-append them:

$props = $Properties + @{Name="$ExpandProperty";Expression={$y}}
$x | select $props

Semicolons

You use a semicolon after your simple assigns for some reason:

$x = $_ ;
$y = $_ ;

They do no harm, but typically they are used to separate multiple statements on a single line. If you really wanted to use them in concert with line breaks, at least be consistent and do it everywhere. But, yeah actually just don't use them.

Inconsistent Coding Style

This is only concerning the placement of braces. In the process block you use C# style where the opening brace is on its own line, and in the rest you seem to use the style more common in PowerShell where the opening brace is on the same line as the preceding statement.

In some sense, this is a matter of opinion, but sometimes it makes a difference in the way the code executes, and for that reason, I always use the latter format (brace does not get its own line).

Either way you decide, be consistent.

Closing

All in all, great job!


Never swallow exceptions silently like this:

} catch (ClientProtocolException e) {
    } catch (IOException e) {
}

You'll have a nasty time debugging hidden problems because of that.  At the very least, print some diagnostic message to System.err.  Furthermore, you couldn't responsibly continue trying to parse an incomplete result, so you should abort the processing instead.

Basically, if you don't know what to do with an exception, you should probably propagate it.  In fact, you already declared that getLocationInfo() can throw an IOException, so why bother catching IOException at all?


Simple hashing code with excessive conditional statements

You should really take a look at argparse: the argparse module makes it easy to write user-friendly command-line interfaces. It will even take care of writing the help for you.

Even if you will apply very little of the following (since you should really use the argparse module), I'll give you some advice anyway.

str.lower()

This:

if hashmethod == "MD5":
    hashCalculator(filename, "md5")
elif hashmethod == "SHA1":
    hashCalculator(filename, "sha1")
elif hashmethod == "SHA224":
    hashCalculator(filename, "sha224")
elif hashmethod == "SHA256":
    hashCalculator(filename, "sha256")
elif hashmethod == "SHA384":
    hashCalculator(filename, "sha384")
elif hashmethod == "SHA512":
    hashCalculator(filename, "sha512")

could just be:

hashCalculator(filename, hashmethod.lower())

Coding style

Follow the official coding style, the main rules are summarized here.

getattr()

This:

if hashmethod == "md5":
    m = hashlib.md5()
elif hashmethod == "sha1":
    m = hashlib.sha1()
elif hashmethod == "sha224":
    m = hashlib.sha224()
elif hashmethod == "sha256":
    m = hashlib.sha256()
elif hashmethod == "sha384":
    m = hashlib.sha384()
elif hashmethod == "sha512":
    m = hashlib.sha512()

could just be:

m = getattr(hashlib, hashmethod)

Multiple line strings

Don't do this:

print "\n"
print "----------------------------------------"
print "\tWelcome to Hash Calculator"
print "----------------------------------------"
print "\n"
print "--help"
print "\n"
print "In order to calculate the hash value of a file, your command line syntax"
print "must be written as below:-"
print "\n"
print "\thashcalculator -f [file] -h [hash method]"
print "\teg. hashcalculator -f notepad.exe -h SHA1"
print "\n"
print "The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512"

Do this instead:

msg = """
----------------------------------------
\tWelcome to Hash Calculator
----------------------------------------

--help

In order to calculate the hash value of a file, your command line syntax
must be written as below:-
\thashcalculator -f [file] -h [hash method]
\teg. hashcalculator -f notepad.exe -h SHA1

The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512"""

print msg


Preparing form data for a POST request with fetch

Can this generalization be simplified further?

return new URLSearchParams(formData)


Compressing a 'char' array using bit packing

Conditional jumps are murder on throughput due to branch-misprediction. Consider simply using a lookup-table instead:
const static uint8_t map[] = { 0, 1, 2, 0, 3 };
*out = (uint8_t)
    ( (map[in[0]] << 0)
    | (map[in[1]] << 2)
    | (map[in[2]] << 4)
    | (map[in[3]] << 6));

There are many architectures where shifting is more expensive than masking, but I doubt there are any where the reverse holds. Thus, the following code, even though it probably requires one extra machine code instruction (3 shifts vs. 4 masks) is likely to be faster:
const static uint8_t map[] = { 0x00, 0x55, 0xaa, 0x00, 0xff };
*out = (uint8_t)
    ( (map[in[0]] & 0x03)
    | (map[in[1]] & 0x0c)
    | (map[in[2]] & 0x30)
    | (map[in[3]] & 0xc0));

By the way, how do you handle the tail of up to 3 bytes? Or is your data guaranteed to be a multiple of 4 bytes long?
Also, your inner loop currently duplicates the first byte of every 4-byte-chunk four times.
Your comments are blatantly superfluous; at best they repeat the code. Say why you do something, not what you just did.


Globals are indeed a bad thing. They are old and full of security issues as well as being nearly impossible to debug. Stay away from them at all costs. Instead, pass those variables as a parameter into any function that needs them and have the function return any modifications if necessary. Once you start learning OOP then you can use class properties in place of globals, but parameter injection is the only solution for procedural programming. Well, you could also use constants, but you don't want to go flashing your password into the global scope that way. At least, I'm pretty sure that is a bad idea. It sounds bad... My experience with security and SQL databases is a bit limited, so you might want clarification here. Database names and non-sensitive information should make fine constants though.

Speaking of constants, typically that is what config files are for. For storing site constants so that they can be reused. You define() a constant by giving it a name, conventionally in caps separated by underscores, and a value and use it almost the same way as a variable, except without the $. For example:

define( 'DB_NAME', 'name' );
//implementation
$info[ 'database' ] = DB_NAME;

Another problem here is that you are not using those globals even though you went to all the trouble of making them. Instead, you immediately wrap them into an associative array. This seems kind of redundant. What's wrong with using the variables as they are? You don't appear to be using that $info array anywhere else and besides adding clutter, you are just making your code harder to read by using longer instances of the same data.

Finally, in regards to your problem, you could use your .htaccess file to advantage, but this really depends on the situation. I would not use this for database connections as it would enforce that connnection on EVERY page, which does not seem necessary. It would be helpful in including the config file in every page though, which is why I mention it.

php_value auto_prepend_file "config.php"

As I said, I would not recommend the above for database connections. If you have a number of pages that require a database connection, I would use a "template" to create this connection, then use specific "views" to do certain tasks. This way you only have to write the code once and you can dynamically change which action is performed. For instance, here is an extremely basic, barebone example. Please don't just copy-paste this, its for demonstration purposes only. Extrapolate from it.

Template

<?php
//create db connection
$db;//db should be available in local scope
include $_GET[ 'view' ] . '.php';
?>

Sample View

<?php
$db->stuff();//do some stuff with db
//print results
?>

The template is the page you would call, but a GET parameter would define what action to perform by loading another page with the database specific actions to take. Whatever variables are in the local scope in the template will also be available in the local scope on the view. Which is why we are able to use the $db as if it were a global. Though this is typically frowned upon because, just like globals, it is hard to figure out where those variables are coming from without the proper context. Again, this is just to give you an idea.


A genric extension method to filter Linq-EF queries

I think you might run into some design ugliness with the in the future because you are now coupling the knowledge that an entity could be filtered by a certain property to each entity.

Imagine a requirement comes in to filter by Course - what would that look like in your design?

Are you going to add a Course property to your IFilterable - but then what if an entity currently implementing IFilterable doesn't have a Course? So you then might need to add another IFilterable interface like an ICourseFilterable and another Filter method to go with it. And then if you want to filter on another entity ... seems quite cumbersome and involved to me.

I think the simplest and most flexible way forward is to actually move the matching responsibility into the SearchCriteria. So instead of having a SearchCriteria you rename it to EmployeeSearchCriteria and give it a method to match a particular employee:

public class EmployeeSearchCriteria
{
    private int _CostCenterId;
    private Gender _Gender;
    ... // other fields to match

    public EmployeeSearchCriteria(int costCenterId, Gender gender, ...)
    {
        _CostCenterId = costCenterId;
        _Gender = gender;
        ...
    }

    public bool Matches(Employee e)
    {
        return e.CostCenterID == _CostCenterId && e.Gender == _Gender && ... ;
    }
}

Then you can do your filtering via:

var list = context.Courses.Where(c => sc.Matches(c.Employee)).ToList();

And in the future if you want to filter entities by Course you create a CourseSearchCriteria with a method bool Matches(Course c) which you then can use as

var list = context.Employees.Where(e => sc.Matches(e.Course)).ToList();

The advantage is that the filtering by specific entities is encapsulated into single classes with single responsibilities and you do not have to litter your code with all these filter interfaces.

The concern that an entity can be filtered is now removed from the entity and kept separate which is always a good thing. The more an entity has to know what might happen to it the more complex your code structure will become.


Your code becomes spaghetti rather easily with this approach. I suggest you move out your logic into separate modules for each route. Even cleaner, put them in a single folder so you can easily look for them. Something like this:

// app.js
var animalsModule = require('routes/animals');
var goats = require('routes/goats');

animals.route(router.route('/animals'));
goats.route(router.route('/goats'));

// animals.js
exports.route(route){
  route.get(...);
  route.post(...);
  route.put(...);
};

req.issue = issue;

I'm not sure if you should be altering objects you don't own, especially the request object. Doing this, req becomes your "global", a universally accessible but easily pollutable object. Removing this middleware might cause potential breakage in the future.

    req.issue.url = req.body.url;
    req.issue.reporter = req.body.reporter;
    req.issue.title = req.body.title;
    req.issue.description = req.body.description;
    req.issue.browser = req.body.browser;
    req.issue.device = req.body.device;

This code will break if the issue middleware is removed. If you write this way everywhere, you will get something like "assigning property to undefined" errors. Additionally, from what I can tell, this middleware will always run, regardless if you actually need issue or not.

I suggest you fetch issue only when needed, not all the time, and only in the location where its actually needed, not in the very available req object.

delete req.body._id;

There's a saying "Don't modify objects you don't own". Unless body was yours to begin with, don't be deleting properties off objects that don't come from your code. You might have unintentionally removed something that some other part of the app, a third-party module even, that needs the property.


Compute bounding rectangle given 2 points quickly and efficiently

Using a completely different tack... the simplest way to do this would be to use the native mechanisms available in the AWT toolkit....

For a regular Rectangle

public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
    return new (Line2D.Double(p1, p2)).getBounds();
}

For a Rectangle2D

public static Rectangle2D computeBounds(Point2D.Double p1, Point2D.Double p2) {
    return new (Line2D.Double(p1, p2)).getBounds2D();
}

Results

I have put this all together in a test harness, to measure the performance, and included two additional tests for you to consider:

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Point2D.Double;
import java.awt.Rectangle;
import java.util.Arrays;
import java.util.Random;

@SuppressWarnings("javadoc")
public class Bounds {

    private static abstract class BoundIt {
        private final String name;
        public BoundIt(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        abstract Object computeBounds(Point2D.Double p1, Point2D.Double p2);
    }

    private static final BoundIt[] solvers = {
        new BoundIt("OPMinified") {

            @Override
            // Minified Version
            public Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
                double dx = p2.x - p1.x, dy = p2.y - p1.y;
                return new Rectangle((int) (dx < 0 ? p2.x : p1.x),
                    (int) (dy < 0 ? p2.y : p1.y), (int) Math.abs(dx), (int) Math.abs(dy));
            }

        },

        new BoundIt("OPReadable") {

            @Override
            // Readable Version
            public Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
                double dx = p2.x - p1.x;
                double dy = p2.y - p1.y;

                int x = (int) (dx < 0 ? p2.x : p1.x);
                int y = (int) (dy < 0 ? p2.y : p1.y);
                int w = (int) Math.abs(dx);
                int h = (int) Math.abs(dy);

                return new Rectangle(x, y, w, h);
            }

        },

        new BoundIt("KeepDouble") {

            @Override
            // Readable Version
            public Rectangle2D computeBounds(Point2D.Double p1, Point2D.Double p2) {
                double dx = p2.x - p1.x;
                double dy = p2.y - p1.y;

                double x = dx < 0 ? p2.x : p1.x;
                double y = dy < 0 ? p2.y : p1.y;
                double w = Math.abs(dx);
                double h = Math.abs(dy);

                return new Rectangle2D.Double(x, y, w, h);
            }

        },

        new BoundIt("Native") {

            @Override
            // Readable Version
            public Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
                return new Line2D.Double(p1, p2).getBounds();
            }

        },

        new BoundIt("Native2D") {

            @Override
            // Readable Version
            public Rectangle2D computeBounds(Point2D.Double p1, Point2D.Double p2) {
                return new Line2D.Double(p1, p2).getBounds2D();
            }

        },

    };

    public static final void testRound(int id, boolean print, Point2D.Double[] as, Point2D.Double[] bs) {

        Object[] results = new Object[as.length];

        for (BoundIt solver : solvers) {
            long time = System.nanoTime();
            for (int i = 0; i < as.length; i++) {
                results[i] = solver.computeBounds(as[i], bs[i]);
            }
            time = System.nanoTime() - time;

            int hc = 0;
            for (Object o : results) {
                hc ^= o.hashCode();
            }
            if (print) {
                System.out.printf("Solved Rep %d Solver %10s in %.3fms (hash %d)\n", id, solver.getName(), time / 1000000.0, hc);
            }
        }
    }

    public static void main(String[] args) {
        int datacnt = 409600;
        double span = 100;
        double offset = - span / 2;
        Random rand = new Random(0);

        Point2D.Double[] data = new Point2D.Double[datacnt << 1];

        for (int i = data.length - 1; i >= 0; i--) {
            data[i] = new Point2D.Double(offset + span * rand.nextDouble(), offset + span * rand.nextDouble());
        }

        Point2D.Double[] as = Arrays.copyOfRange(data, 0, datacnt);
        Point2D.Double[] bs = Arrays.copyOfRange(data, datacnt, data.length);
        data = null;

        System.gc();

        for (int i = 0; i < 100; i++) {
            System.out.println("\n\nProcessing round " + i);
            testRound(i, i >= 90, as, bs);
        }
    }

}

The reults from that test look like:

Processing round 97
Solved Rep 97 Solver OPMinified in 16.059ms (hash 1545060352)
Solved Rep 97 Solver OPReadable in 15.169ms (hash 1545060352)
Solved Rep 97 Solver KeepDouble in 15.726ms (hash -2058404443)
Solved Rep 97 Solver     Native in 26.782ms (hash 1558544384)
Solved Rep 97 Solver   Native2D in 12.478ms (hash -2058404443)

Processing round 98
Solved Rep 98 Solver OPMinified in 13.386ms (hash 1545060352)
Solved Rep 98 Solver OPReadable in 16.300ms (hash 1545060352)
Solved Rep 98 Solver KeepDouble in 13.484ms (hash -2058404443)
Solved Rep 98 Solver     Native in 59.174ms (hash 1558544384)
Solved Rep 98 Solver   Native2D in 14.190ms (hash -2058404443)

Processing round 99
Solved Rep 99 Solver OPMinified in 14.764ms (hash 1545060352)
Solved Rep 99 Solver OPReadable in 14.199ms (hash 1545060352)
Solved Rep 99 Solver KeepDouble in 13.572ms (hash -2058404443)
Solved Rep 99 Solver     Native in 30.009ms (hash 1558544384)
Solved Rep 99 Solver   Native2D in 13.721ms (hash -2058404443)


Before anything else: add tests
To be on the safe side before any review of an algorithmic problem, I tend to ensure the code is testable and tested. On that point, the problem is nice for three reasons:

for a given well defined input (a list), it returns a clear output (a string)
it is easy to generate test cases for the different cases
a few example are provided

You should start by rewriting your function so that it returns things instead of printing them. Then, you can write automated tests.
For instance, you can write the following tests:
# From the problem
assert almostSorted([4, 2]) == "yes\nswap 1 2"
assert almostSorted([3, 1, 2]) == "no"
assert almostSorted([1, 5, 4, 3, 2, 6]) == "yes\nreverse 2 5"
# Generate various small strings
for i in range(10):
    l_i = list(range(i))
    assert almostSorted(l_i) == "no"  # WRONG
    result_reversed = almostSorted(list(reversed(l_i)))
    if i < 2:
        assert result_reversed == "no" # WRONG
    elif i < 4:
        assert result_reversed == "yes\nswap %d %d" % (1, i)
    else:
        assert result_reversed == "yes\nreverse %d %d" % (1, i)
    for j in range(i):
        for k in range(j+1, i):
            l_swap = list(range(i))
            l_swap[j], l_swap[k] = l_swap[k], l_swap[j]
            result_swap = almostSorted(l_swap)
            assert result_swap == "yes\nswap %d %d" % (j+1, k+1)
            l_rev = list(range(i))
            l_rev[j:k+1] = l_rev[j:k+1][::-1]
            result_rev = almostSorted(l_rev)
            if k - j >= 3:
                assert result_rev == "yes\nreverse %d %d" % (j+1, k+1)
            else:
                assert result_swap == "yes\nswap %d %d" % (j+1, k+1)

You could also use a proper testing framework but this is the first step.
It is enough to see an issue spotted by Martin. R in the comment. This is enough easy to fix and I'll let you deal with this.
Except for that, your code seems to be working fine which is a great news even if the test suite is far from perfect.
Spoiler alert: more issues are found later.
Style
There is an official standard Python style guide called PEP 8. This is highly recommended reading. It gives guidelines to help writing code that is both readable and consistent. The Python community tries to follow these guidelines, more or less strictly (a key aspect of PEP 8 is that it provides guidelines and not strict rules to follow blindly).
It deals with various aspects of the code style: naming conventions, indentation convention, etc.
You'll find various tools to try to check whether your code is PEP 8 compliant and if is it not, to try and fix this:

pycodestyle package (formerly known as pep8) to check you code

pep8online to check your code with an online tool

autopep8 package to fix your code automatically

Also, this is also checked by various linters: pylint, pyflakes, flake8, etc.

In your case, the naming convention of the function seems to be off:

checkSorted should be check_sorted or even better is_sorted.

almostSorted should be almost_sorted (or is_almost_sorted ?)

Regarding the naming, 2 other details could be improved:

arrays are usually called list in the Python universe. Thus, lst may be a better argument name than arr.

sorted is the name of a builtin. Thus, having a local variable named the same way could lead to issues in more complex code. In your case, you don't even need that variable in the first place...
(There are other PEP8 "issues" about spacing but nothing very interesting to me).

Same logic but different
The logic to check is the list is sorted and the logic to find first item out of order from the left look the same but shaped in a different way.
Actually, a closer look shows that the logic itself is different in a subtle way: identical consecutive values are not handled the same way in both places. This can be shown by writing more tests with equal values:
for i in range(10):
    l_equal = [42] * i
    assert almost_sorted(l_equal) == "yes"
    l_i = list(range(i))
    assert almost_sorted(l_i) == "yes"
    result_reversed = almost_sorted(list(reversed(l_i)))
    if i < 2:
        assert result_reversed == "yes"
    elif i < 4:
        assert result_reversed == "yes\nswap %d %d" % (1, i)
    else:
        assert result_reversed == "yes\nreverse %d %d" % (1, i)
    for j in range(i):
        for new_val in (0, 42):
            l_almost_equal = [42] * i
            l_almost_equal[j] = new_val
            assert "yes" in almost_sorted(l_almost_equal)

I'll stop the review here to let you deal with the issue found.
Before finding the problem, I was about to suggest something along the lines of:

instead of checking is the list is sorted first, you could try to find the first out of order value and if you do not find it, then the array is sorted.

the for loop in is_sorted is clearer that the while loop, I reckon you should use the former rather than the later.

For instance, you could write something like:
# Find first item out of order from the left
for i in range(len(lst)-1):
    if lst[i] > lst[i+1]:
        first_ooo_left = i
        break
else: # no break: sorted already
    return "yes"


Very good.

A few things I would change:

Declare variables as close to the point of usage as possible.

int amount;
int bettingAmount;
int guess;
int dice;
std::string playerName;

This is very C like to declare all your variables at the top.
By declaring them close to the point of usage you don't need to look around for them they should be close to where you are using them. Also C++ has the concept of construction/destruction on objects which comes in useful and is applies at the point of creation.
Validate that your read worked.

std::cin >> amount;

If the user types in "Kevin" then your whole program will stop working. Any time you have user input it is best to read a line of text (as users interact with the terminal a line at a time). Then parse and validate that data out of line (so that failure does not set the bad bit on the stream (because you will need to reset that).

while(true)
{
    std::string   userInput;
    std::getline(std::cin, userInput);

    std::stringstream userInputStream(userInput);
    if (userInputStream >> amount)
    {
        // The user entered a valid number and not text.
        //
        // If you care you may want to check that they did not
        // enter text after the number like "10 Bob"
        // Personally I would not bother for version one

        break;   // exit the loop.
    }
    else
    {
        // invalid Input
        std::cerr << "Invalid Input: Try again\n";
        // Loop re-enters.
        // User trys again.
    }
}

I prefer all sub blocks to have {} around them

if(bettingAmount > amount)
    std::cout << "Your betting amount is more than your current balance\n\nRe-enter data\n ";

// I would write like this:
if(bettingAmount > amount)
{
    std::cout << "Your betting amount is more than your current balance\n\nRe-enter data\n ";
}

This makes it easier to read. Also when modifying the code and needing to add more statements you don't need to remember to add the {}.
Don't re-seed rand.

srand(time(0));

You only need to do this once in the application. Do it as main() is entered. Don't do it again. It breaks the randomness. It's not required for a simple application like this. But if you want to do better then I would look at using the new random number generates that are part of C++11. It will be good practice (rand() is not very good).

Even so the overall structure is still very C-Like.
You could practice your OO style here.

int main()
{
    Game       game;

    HumPlayer  human;
    while(!human.hadEnough())
    {
        game.play(human);
    }

    CompPlayer computer;
    while(!computer.hadEnough())
    {
        game.play(computer);
    }

    std::cout << (human.score() < computer.score())
               ? "The time of the computer overlords has arrived.\n";
               : "Still time before this silly machines are smart.\n";
}


The sqrt-prime function neither needs nor uses the last-guess argument.  It can be safely eliminated:

(define (sqrt-prime guess x)
  (if (good-enough? guess x) guess
      (sqrt-prime (better-guess guess x) x)))

You may call the function thus:

(define (sqrt x) (sqrt-prime 1.0 x))

I feel that, other than this minor change, your program is succinct enough.


Function that builds dictionary based on lambda params

Ronnie,
You have a good starting point for the problem you are trying to solve.
To answer your concerns:

Is there a better way to work with the expressions that are passed in.
I think what you have done is fine. You are using Expression to let user specify methods/properties in type safe way. The only thing I would change is to use Expression<Func<T, object>>[] instead of Expression<Func<T, dynamic>>[] as dynamic will invoke the compiler at run time.

Can the expressions parameter be better constrained by a more appropriate type?
I don't think you can specify additional constraints at compile time but you can definitely add code to validate the expression at runtime.

Is there a better way to derive the cache key?
I think your cache key is fine. If you want to be more conservative, you can include Type.AssemblyQualifiedName. I would worry about it only if I was releasing to general public and not if I am using this class as part of a team.

With that said, here's the full re-factored code along with my notes. I hope it helps.
void Main()
{
    var ronnie = new Person();
    ronnie.Name = "Ronnie";
    ronnie.Address = "Greensboro, NC";

    var dictionary = ObjectToDictionaryConverter.GetDictionary(ronnie, x => x.Name, x => x.Address);

    // In following example, we are trying to pass in an expression which is not valid for our object.
    // Running this code will throw an appropriate exception like
    // Expression value(UserQuery+<>c__DisplayClass0).anotherDictionary.Keys is invalid.
    // Expression Property/Member Type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
    //, expecting Type: UserQuery+Person

    //var anotherDictionary = new Dictionary<string, string>();
    //var dictionary = ObjectToDictionaryConverter.GetDictionary(ronnie, x => anotherDictionary.Keys);

    //I don't think you can enforce this constraint at compile time (I am not sure about it, I would love to be proved wrong.)

    Console.WriteLine(dictionary["Name"]); //Prints Ronnie
    Console.WriteLine(dictionary["Address"]); //Prints Greensboro, NC

}

public class Person
{
    public string Name { get; set; }

    public string Address { get; set; }
}

// Why would you name a class like 'DictionaryThing'? It doesn't explain anything about what the class does.
// Let's give it a more descriptive 'ObjectToDictionaryConverter' name. You may prefer some other name but
// make sure that you put same thought in to naming your class as the code which goes inside the class.

// Next, the original code was doing two things
// 1. Inspecting the expression to derive a key
// 2. Create the dictionary from the input object (while also catching the expression details)

// Following SRP, let's separate it out in two classes so that each class is responsible for doing one thing.
// This also means that you can use the Expression inspection code somewhere else if you choose to.
public static class ObjectToDictionaryConverter
{
    //Always spell out the variable name in its full. (expCache -> expressionCache)
    static ConcurrentDictionary<string, Delegate> expressionCache = new ConcurrentDictionary<string, Delegate>();

    public static Dictionary<string, object> GetDictionary<T>(T obj, params Expression<Func<T, object>>[] expressions)
    {
        //Always validate your arguments.
        if(ReferenceEquals(obj, null))
            throw new ArgumentNullException("obj");

        if(expressions.Length == 0)
            throw new ArgumentException("You must specify at least one expression.");

        foreach (var expression in expressions)
        {
            if(expression == null)
                throw new ArgumentException("You can not specify NULL expression.");
        }

        var result = new Dictionary<string, object>();

        foreach (var expression in expressions)
        {
            //The purpose of ExpressionDetail is to inspect our expression
            var expressionDetail = ExpressionDetail.Create(expression);

            //A lambda expression can be a valid expression referring to a property or function.
            //But for our need, we will need to compile this expression to a delegate and run on object of Type T, let's make
            //sure that expression refers to the correct type.

            //IMPORTANT: We should not put this check in ExpressionDetail class. It is not
            //the responsibility of ExpressionDetail to enforce this type constraint.
            //This type constraint is only needed for ObjectToDictionaryConverter class.
            if(expressionDetail.DeclaringType != typeof(T))
                throw new InvalidExpressionException("Expression " + expression.Body + " is invalid. Expression Property/Member Type " + expressionDetail.DeclaringType.FullName + ", expecting Type: " + typeof(T).FullName);

            //expressionDetail has properties like 'Name', 'FullName', 'Delegate'
            var func = (Func<T, object>) expressionCache.GetOrAdd(expressionDetail.FullName, expressionDetail.Delegate);

            result[expressionDetail.Name] = func(obj);
        }

        return result;
    }
}

public class ExpressionDetail
{
    private ExpressionDetail()
    {

    }

    public MemberInfo MemberInfo { get; private set; }

    public LambdaExpression Expression { get; private set; }

    //By figuring out MemberInfo from the Expression,
    //we can now have all these read-only properties to get expression detail.
    public string Name { get { return MemberInfo.Name; } }

    public Type DeclaringType { get { return MemberInfo.DeclaringType; } }

    public string FullName { get { return DeclaringType.FullName + "." + Name; } }

    //Depending on performance requirement, you may want to use Lazy<T> to calculate this value
    //only once.
    public Delegate Delegate { get { return Expression.Compile(); } }

    //We are expecting a lambda expression which should either point to a method or a property access.
    //To get body, we have to handle the case of expression being UnaryExpression
    //To learn more: http://stackoverflow.com/questions/3567857/why-are-some-object-properties-unaryexpression-and-others-memberexpression
    private static Expression GetBody(LambdaExpression expression)
    {
        //We don't validate arguments here only because it's a private method.

        var unaryExpression = expression.Body as UnaryExpression;
        return unaryExpression != null ? unaryExpression.Operand : expression.Body;
    }

    //In your original method, you returned the name.
    //However, it could be even more useful to get the MemberInfo and store it.
    //Now we will have access to Name as well as the Type in which the property/method is declared.

    // There are lots of edge cases here.
    // Refer to: http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression and update this method to handle the edge cases that you care about.
    private static MemberInfo GetMemberInfo(Expression expression)
    {
        //We don't validate arguments here only because it's a private method.

        var memberExpression = expression as MemberExpression;

        if(memberExpression != null)
            return memberExpression.Member;

        var methodCallExpression = expression as MethodCallExpression;

        if(methodCallExpression != null)
            return methodCallExpression.Method;

        return null;
    }

    public static ExpressionDetail Create(LambdaExpression expression)
    {
        if(expression == null)
            throw new ArgumentNullException("expression");

        var body = GetBody(expression);

        var memberInfo = GetMemberInfo(body);

        if (memberInfo == null)
                throw new InvalidExpressionException(
                    string.Format("The expression '{0}' is invalid. You must supply an expression that references a property or a function.",
                        expression.Body));

        return new ExpressionDetail { MemberInfo = memberInfo, Expression = expression};
    }

}


Naming

The names are very poor. Consider these renames:

n -> seconds
t -> unit
x -> input

Make the most out of regex

If you only allow "s", "m", or "h" as units, then instead of [a-zA-Z] you could use [smhSMH] in the regex.

Formatting

The formatting is really too compact. It's recommended to put spaces around operators.

use strict

It's recommended to use strict always.
It can help catching bugs.

Alternative implementation

Applying the above suggestions (and a bit more), consider this alternative implementation:

use warnings;
use strict;

my $seconds;

# input could be 1, 1s , 1m or 1h
my $input = $ARGV[0];
if ($input =~ /^([0-9]+)([smh]?)$/i) {
    $seconds = $1;
    my $unit = lc($2);
    my $multiplier = 1;
    if ($unit eq "h") {
        $multiplier = 3600;
    } elsif ($unit eq "m") {
        $multiplier = 60;
    }
    $seconds *= $multiplier;
} else {
    die;
}

$| = 1;  # force flush output on every write
while ($seconds) {
    print $seconds;
    sleep 1;
    my $len = length($seconds);
    print "\r", " " x $len, "\r"; $seconds--;
}


Applying 'Uncle Bob's Clean Code' on this small exercice

CreateArray1to30() could be renamed to CreateQuestions()
ReturnAllCombinationsOfInputtedList() could be renamed to Combinations() or QuestionCombinations()
ReturnAllCombinationsOfInputtedList() does too much. The call to .Distinct() is unecessary, and can be replaced with correct indices in the first place. Furthermore, the aTest array is entirely useless and could be replaced by using firstQuestion and secondQuestion directly.
Strings are a non ideal data structures for the exams, as you use a different format when printing them out

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleAppHelpingAlexWithExercices
{
    struct ExamTicket {
        public int Question1, Question2;
        public ExamTicket(int Question1, int Question2) {
            this.Question1 = Question1;
            this.Question2 = Question2;
        }
    }
    class Program
    {
        //**************************************************************************
        // How many different exam tickets with two different questions can be made,
        // from a syllabus with 30 questions
        //**************************************************************************
        static void Main(string[] args)
        {
            int[] questions = CreateQuestions();
            var combinations = new List<ExamTicket>(Combinations(questions));
            foreach (var combination in combinations) {
                Console.WriteLine($"{combination.Question1} and {combination.Question2}");
            }
            Console.WriteLine("Total unique combinations: {0}", combinations.Count);
        }

        static IEnumerable<ExamTicket> Combinations(int[] questions)
        {
            for (int i=0;i<questions.Length;++i) {
                for (int j=i+1;j<questions.Length;++j) {
                    yield return new ExamTicket(questions[i],questions[j]);
                }
            }
        }

        static int[] CreateQuestions()
        {
            return Enumerable.Range(1, 30).ToArray();
        }
    }
}


Hiding and revealing toggle responds very slow

All this adding/removing classes are too much for this functionality. This makes it also very slow.

You can iterate over all div elements, and say if div is !== hidden, than hide it.

After that, you get the clicked element with $(this), and just say

$(this).next().slideToggle();

This is not proper code, but since you don't have thousands of divs to iterate over, just hide every open div, and open the clicked one.

Maybe you have the problem of you want to close the already open one, so just make two if's. The first one should be like:

  if($(this).next().style.visible === "true"), hide it, if not, hide
  every visbile div and make just the next to the clicked one visible.

This should be much faster, because you don't add/remove/readd classes.