Better way to achieve looped output result

Review

Your answer is perfectly fine for this usage, I would keep that.  If you were that deep in loops generally it would be a sign that something was wrong, but for this task it is perfectly okay.

I would recommend using upper case only for constants.

Over Optimisation

This is actually a lot simpler than the other answers are making it out to be.  The best answer in terms of performance (which is a silly thing to aim for) that I can think of is:

$end = pow(4, 4);

for($i = 0; $i < $end; ++$i)
{
    echo 1111 + base_convert($i, 10, 4), PHP_EOL;
}

Addition is quite a cheap operation for a processor to perform.  Comparing the benchmarks from Elias Van Ootegem's answer shows that the above code is significantly quicker.  This is due to the loop running only on the numbers that it needs to and not having to check a string.  It also does not introduce any pre-computed magic numbers.

OP Time taken:    0.00325608253479
Elias Time taken: 0.0021388530731201
Pauls Time taken: 0.0016560554504395

The code I used for the benchmark was:

// OP version
$start = microtime(true);
for ($a=1;$a<5;++$a)
    for ($b=1;$b<5;++$b)
        for ($c=1;$c<5;++$c)
            for ($d=1;$d<5;++$d)
                echo $a, $b, $c, $d, PHP_EOL;
                //comma's are more efficient then dots here
echo 'OP Time taken: ', microtime(true) - $start, PHP_EOL;

// Elias version
$start = microtime(true);
for($i=156;$i<625;++$i)
{
    $str = base_convert($i, 10, 5);
    if (strstr($str, '0') === false)
        echo $str, PHP_EOL;
}
echo 'Elias Time taken: ', microtime(true) - $start, PHP_EOL;

// Paul Version
$start = microtime(true);
$end = base_convert(3333, 4, 10) + 1;

for($i = 0; $i < $end; ++$i)
{
    echo 1111 + base_convert($i, 10, 4), PHP_EOL;
}
echo 'Pauls Time taken: ', microtime(true) - $start, PHP_EOL;

Overkill

If you do want to generalise the output you could create a function such as the one below (This is complete overkill, but demonstrates that the solution does not come from magic numbers.):

/**
 * Count in a base that has been offset from zero.
 *
 * @param int $digits The number of digits to use.
 * @param int $offset The offset from zero that the base uses.
 * @param int $base   The base to count in.
 */
function countInAnOffsetBase($digits, $offset, $base)
{
    $end = pow($base, $digits);
    $offset = str_repeat($offset, $digits);

    for ($i = 0; $i < $end; ++$i)
    {
        echo $offset + base_convert($i, 10, $base), PHP_EOL;
    }
}

countInAnOffsetBase(4, 1, 4);
// Or try 3, 4, 5 to count from 444 to 888 using the digits 4, 5, 6, 7, 8

This is almost as quick as the version I proposed at the top of this post.

Note

The function and method above assume that the number will not roll over the base (for base 10, the offset + base must be less than 10).  An even more general function would specify the output base:

/**
 * Count in a base that has been offset from zero.
 *
 * @param int $digits The number of digits to use.
 * @param int $offset The offset from zero that the base uses.
 * @param int $base   The base to count in.
 * @param int $base   The base to output the count in.
 */
function countInAnOffsetBase($digits, $offset, $base, $outputBase)
{
    if ($offset + $base > $outputBase)
    {
        throw new OverflowException(
            'offset and base cannot be greater than outputBase otherwise ' .
            'the value will overflow.');
    }

    $end = pow($base, $digits);
    $offset = intval(str_repeat($offset, $digits), $outputBase);

    for ($i = 0; $i < $end; ++$i)
    {
        echo base_convert(
            $offset + intval(base_convert($i, 10, $base), $outputBase),
            10,
            $outputBase),
            PHP_EOL;
    }
}


Check equality of an objects array property and a nested object property

Short review;

Unless you are writing inline functions, you should stick to using function
Using semicolons is preferred, it takes skill and knowledge to avoid the pitfalls of not using semicolons
You assign in 1 statement the value of categorizedItems and return it in the next, you might as well return immediately
In essence you do a find within a map, not too fast, I would create a lookup structure before the map
itemList seems like a terrible name, I would call it categories

I would counter-propose the following;

const items = [{name: 'test', value: 1, category: 'a'}, {name: 'test2', value: 2, category: 'b'}, {name: 'test3', value: 3, category: 'c'}];
const categories = {testnum1: {name: 'test123', category: 'a'}, testnum2: {name: 'test234', category: 'b'}};

function getCategorizedItems(items, categories){
  //Desired output; [{name: 'test', itemCategory: 'testnum1'},{name: 'test2', itemCategory: 'testnum2'}]
  const categoriesMap = Object.fromEntries(Object.entries(categories).map((entry) => [entry[1].category, entry[0]]));
  return items.map(item => ({name: item.name, itemCategory:categoriesMap[item.category]})).filter(item => item.itemCategory);
}

console.log(getCategorizedItems(items, categories));


Counting number of `1` digits in the value of \$11^n\$

You should put your programming skills aside for a bit and think. Think mathematically, what it actually means.

$$ 11^n = (10+1)^n $$

Lets say a=10, b=1 => \$(a+b)^n\$, this can be expanded using pascal triangle:

   1
  1 1
 1 2 1
1 3 3 1
...

I suppose everybody knows how this continues...

It then goes like this:

$$ (a+b)^n = {n \choose 0} a^n b^0 + {n \choose 1} a^{n-1} b^1 + \dots + {n \choose n} a^0 b^n $$

You can notice that since b=1 we can erase all those terms \$b^x\$

And we are left with
$$ (a+b)^n = {n \choose 0} a^n + {n \choose 1} a^{n-1} + \dots + {n \choose n} a^0 $$

Since a=10, we know \$a^n\$ is basically a 1 followed by n zeroes.

Simple add and carry of the coefficients should now show you when a digit is 1 and when it is anything else.


Shell function to convert .png to .svg file

You don’t need eval. For example,

eval "rm \"$pnm_filepath\""

is the same as

rm "$pnm_filepath"

but the latter is more readable.

The same is true for the other two cases where you use eval.

I’m not sure what the purpose is of looping over the dots in the file path. Note that directory names can have dots too. The best way to get a file name with a different extension is to use ${x%.*} (see here):

pnm_filepath=${1%.*}.pnm

(I’m assuming you use Bash).


Recursive function refactoring help: occurrences of char in string starting at ith char

A simple recursive function would be:

let rec occFromIth s i ch =
  if i >= String.length s then 0
  else (if s.[i] = ch then 1 else 0) + occFromIth s (i + 1) ch


[fizz x | x <- xs] is the same as map fizz xs, so fizzBuzz = map fizz.

You can use putStrLn instead of print to print strings without quotes.

Using the fact that map (g . f) = map g . map f,  you can merge mapM_ putStrLn and map fizz into:

mapM_ (putStrLn . fizz) [1..15]

Another solution with everything in single function and without mod x 15:

import Control.Monad (forM_, when)

fizzBuzz :: IO ()
fizzBuzz = forM_ [1..15] $ \x -> do
  let [m3, m5] = map ((==0) . mod x) [3,5]
  when m3 $ putStr "Fizz"
  when m5 $ putStr "Buzz"
  when (not m3 && not m5) $ putStr $ show x
  putStrLn ""


Save on typing while using UTF8 encoding

You don't care about null references?

IMO you create an object in order just to do something, that is more suitable for the concept of extensions:

  public static class StringExtensions
  {
    public static byte[] ToUTF8Bytes(this string text)
    {
      return Encoding.UTF8.GetBytes(text);
    }

    public static string ToUTF8(this byte[] bytes)
    {
      return Encoding.UTF8.GetString(bytes);
    }
  }

  Assert.AreEqual(text, text.ToUTF8Bytes().ToUTF8());

The benefit of the extension methods is that you don't have to remember that you've created the UTF8 struct somewhere, because it will show up in the intellisence.


select_best: yet another partitioning algorithm

A couple of points on the style rather than the algorithm itself.

First, I find the #ifdef for the typename peculiar, it detracts from clarity, and is a pointless use of macros, it may be fine for a small snippet but in a large project or a library header such a thing can wreak havoc. Consider simply,

template <class BidirectionalIterator>

That said, note that C++11 relaxes std::partition to a ForwardIterator, so I would simply say,

template <class ForwardIterator>
void select_best(ForwardIterator first, ForwardIterator mid, ForwardIterator last);

The type T is also a bad choice to denote a value_type, it has too much baggage as a template parameter. Simply say,

using value_type = typename I::value_type;

Then consider avoiding the inadvertent copy of the value by changing the code to take a const reference of the pivot,

const T& pivot = *first;

The lambdas are arguably the preferred way to write the predicate (let's not venture into std::bind and std::min territory), but again I would capture the value by a reference to avoid a copy, and be less verbose,

[&](const T& elt) { return elt < pivot; }

Consider either using brackets with if-else clauses or at least put the conditional statement on a separate line.

if ( ... )
    statement;
else

note that using std::distance implies that complexity of your function can blow up to O(n) for that use only (where n is the pp, somewhere around N/2), and if you want O(1) for the distance calculation you have to make sure your iterators are random access.

and last, please get rid of the ghastly space in else first = pp;.

For your question on the return value, would it be useful to return pp itself?


Performance Issue on css and javascript styling

Yes! This looks like a maintenance head ache ( nightmare ).

CSS belongs to CSS files ( you can apply csslint to CSS files, CSS files also have syntax highlighting, plus most developers rightfully dislike maintaining CSS in JavaScript ).

If you must support different styles at run-time, you can create styles in your stylesheet for each theme and then assign the right class when themes get switched.

To your points:

I find this method to be easy to maintain and update to other themes because the underlying samples are there and its not hard coded in the script. I am not sure what you mean by "not hardcoded", but you are most likely wrong.

So I can just create another theme like aqua for example and just change the colors, etc. You can do the same with CSS files
Also I can dynamically change the theme easier without having to do a page refresh. You can do the same by changing the class dynamically

As for performance, you are using extra bandwidth by sending over all style-sheets, to be avoided on mobile.


Searching a maze using DFS and BFS in Python 3

Kill the noise

It's great that the solution works, but it's full of elements that seem to serve no purpose, which makes it confusing and hard to read.

visited_cells is modified but never used
BIT_SOLUTION is defined but never used
A comment like # add 1 to visited cells adds no value to a code like visited_cells += 1. Avoid writing such comments.

The same goes for the # Solve maze ... comments.

The doc comment """ ... """ in solve_bfs is inappropriate. Instead of useful documentation, it's pseudo-code of the implementation. It's unnecessary.
The return statement is unnecessary at the end of a function.
Why write 0b0000 instead of simply 0?

Confusion

I'm confused by the different terminating condition in the two implementations. In one of them, reaching the goal is expressed as cur_cell == len(m.maze_array) - 1, in the other it's current_cell == m.total_cells - 1.
It's best when there's one clear way to do something.
I suggest to change the maze implementation so that the terminating condition can be expressed as m.is_goal(cell_id).

Encapsulation

The posted code is a client of the maze library (I guess your own).
It knows too much about how the maze is implemented.
It's not good that it accesses implementation details such as m.maze_array and m.total_cells.
It's not good that the client knows that the last cell in the implementation is the exit of the maze.
It's not good that the client knows that the cells of the maze are stored in a list (maze_array).
This also limits the kind of mazes that can be modeled.

If you change the maze API so that clients can check if they have reached the exit by calling m.is_goal(cell_id),
then the maze library will be free to place the exit to wherever it likes in its storage,
it wouldn't need to be the last.
The client also wouldn't know what data structure was used to store the cells of the maze,
which again would give the maze library the freedom to use whatever it likes,
and the freedom to change the underlying storage as needed,
for example to something more efficient in a future release.

Style

You can replace len(v) > 0 and len(v) >= 1 with simply v,
because a non-empty collection is truthy in Python.

Instead of while 1:,
it's more natural to write while True:.


Apply one random deduction pattern onto different lists with same index in Python

The code is not bad, but is a little redundant and messy.

Some comments:

There is no need to shorten the included module random because it's already short and legible.
If you are going to use global variables (module level variables) at least they should be in uppercase. It makes more easy to understand the code when reading it because you don't have to look for the variable in the code. You know they're up there. Another option is reading those variables from, say, a file if you plan to apply the script to multiples instances of the problem.
indxLst = [] it's declared but not used.
xrange() it's good for looping because it generates the new value on demand, but there is no point in using it if you're going to exhaust it right away (i.e. L = [x for x in xrange(num)] that is equivalent to L = range(num)). On the other hand, in the only place you are using range(1, n) that's the place you should be using xrange() because you're on a loop and there is no need to generate the whole range right away, you have time until you reach the last element.
The initialization for L and index it's the same. In this case you could initialize them both to the same object using the syntax: x = y = obj. But it's a minor thing and can be troublesome since both variables are pointing to the same obj.
The code should contain "some kind of logic flow". In the revised code I order it like: "calculate index; show index", "calculate Lchg; show Lchg".
The name of lChng should be something that relates to L, so possible names could be LChng, L_chng, L_tmp, etc. But the l in upper case. Also maybe you could improve the name of the variables. num it's generic and it doesn't tell you much, also index. But if the names are specified that way then it's okay.
indexLst seems to be unuseful because you put list in there only to use the same list you put 2 lines afterwards. If you don't need to whole indexes lists stored there's no point in having it there.
Last. This two lines:

lChng = [ L[y]+e for y in xrange(num)]
lChng = [lChng[x] for y, x in enumerate(indexLst[e-1]) ]

Can be replaced by:

Lchg = [L[i]+e for i in index]

Since you are puting index in indexLst only to pick it up again by indexLst[e-1].

Revised code:

import random

NUM = 30
N = 7
SLP = 1

def main():
    L = index = range(NUM)
    for e in xrange(1, N):
        get = (NUM/e) * SLP
        index = random.sample(index, get)
        index.sort()
        print "Index %d =" % e, index
        Lchg = [L[i]+e for i in index]
        Lchg.sort()
        print "List %d =" % e, Lchg

main()


In general in F# we try to minimize the use of explicit type declaration on function arguments:

let left (node: Node<'a>) = node.Left

becomes

let left node = node.Left

etc.

The function insertNode violates the single responsibility principle in that if root =  None then it creates a new tree/root node instead of actual inserting the value.

Personal I wouldn't allow root to be Option/None

Instead I would provide a function called newTree taking a 'a value as argument and returning a Node<'a>

  let rec insertNode (root: Node<'a> option) (nextValue: 'a) : Node<'a> = ...

In general you should have object in question of the module as the last argument of a function in order to make use of the pipe operator:

let rec insertNode value root =...

root |> BinarySearchTree.insertNode value

sortedData seems overly complicated - maybe from the use of List.sort. In principle it's just a depth-first-search (dfs), where you for each node can concatenate the values in the left child node with the value of the node itself concatenated with the values in the right child node:

For a list it could be:

let toList root =
    let rec dfs optNode =
        match optNode with
        | Some node -> (dfs (left node))@(data node::dfs (right node))
        | None -> []

    dfs (Some root)

Or if you prefer a Sequence (which I do):

let toSeq root =
    let rec dfs optNode =
        match optNode with
        | Some node -> seq {
            yield! dfs (left node)
            yield data node
            yield! dfs (right node)
            }
        | None -> Seq.empty

    dfs (Some root)

I call the functions toList and toSeq. Maybe toOrderedList/Seq are better names.

You could consider to extend the List-module with a toBinaryTree items instead of the create items function. That way it is possible to write:

let data = [ 5; 8; 1; 5; 1; 2; 2; 4; 6; 3 ]
let root = data |> List.toBinaryTree

which may be more intuitive

In the create items function you should consider to sort the items and do a binary insertion in order to create a balanced tree, because if you provide a list of items that is sorted then your function will merely produce a singly linked list of nodes using only one of the child nodes instead of a tree.

You should consider to provide a function that can balance an existing tree.

As an alternative to the Node<'a> type as a record type, you could consider to define it as a discriminated union type with the following definition:

type Node<'a> =
    | Empty
    | Node of Data:'a * Left:Node<'a> * Right:Node<'a>

That is more in line with the functional style of F# and your functions become somewhat more simple and intuitive:

module BinaryTree =

let data = function Empty -> failwith "Empty Tree" | Node (d, _, _) -> d
let left = function Empty -> Empty | Node (_, l, _) -> l
let right = function Empty -> Empty | Node (_, _, r) -> r

let first root =
    let rec goLeft node =
        match node with
        | Empty -> None
        | Node (d, ln, _) ->
            match ln with
            | Empty -> Some d
            | Node _ -> goLeft ln

    goLeft root

let last root =
    let rec goRight node =
        match node with
        | Empty -> None
        | Node (d, _, rn) ->
            match rn with
            | Empty -> Some d
            | Node _ -> goRight rn

    goRight root

let rec insert data root =
    match root with
    | Empty -> Node(data, Empty, Empty)
    | Node (d, l, r) ->
        match data <= d with
        | true -> Node (d, l |> insert data, r)
        | false -> Node (d, l, r |> insert data)

let toOrderedSeq root =
    let rec dfs node =
        match node with
        | Empty -> Seq.empty
        | Node (d, ln, rn) -> seq {
                yield! dfs ln
                yield d
                yield! dfs rn
            }

    dfs root

module List =
    let toBinaryTree data = data |> List.fold (fun n x -> n |> BinaryTree.insert x) Empty

As seen, the use of option is unnecessary and the insert function is consistent, because an Empty node as root is also a Node<'a>/Tree - just without any elements.


Nice code, only a few comments to offer here:

.1.

var rgb = document.getElementById("rgb");
var rgb2 = document.getElementById("rgb2");
var rgb3 = document.getElementById("rgb3");

This way of keeping the r, g, and b is not the best. Consider having to keep six of them, or more. You would not do this that way. You cannot run a loop with this and this gets obvious in

    if (rgb.value.length >= this.maxLength) {
        rgb2.focus();
    }
    if (rgb2.value.length >= this.maxLength) {
        rgb3.focus();
    }

So what I would do is:

var getEl = document.getElementById;
var rgbElements = {
                   r:getEl("rgb"),
                   g:getEl("rgb2"),
                   b:getEl("rgb3")
                  }

This way you could run a loop for these.

.2.
This code

document.getElementById("hex").addEventListener("input", function() {
    // Sets colours for SVG, picker, converts HEX to RGB and prints out HEX
    svgPath.style.fill = '#' + this.value;
    colorInput.value = '#' + this.value;
    hexOutput.innerHTML = 'HEX: #' + this.value.toUpperCase();
    rgbOutput.innerHTML = 'RGB: rgb(' + hexToRGB(this.value) + ')';
}, false);

should be like this one

document.getElementById("hex").addEventListener("input", function() {
    // Sets colours for SVG, picker, converts HEX to RGB and prints out HEX
    var hexVal = this.value;
    svgPath.style.fill = '#' + hexVal;
    colorInput.value = '#' + hexVal;
    hexOutput.innerHTML = 'HEX: #' + hexVal.toUpperCase();
    rgbOutput.innerHTML = 'RGB: rgb(' + hexToRGB(hexVal) + ')';
}, false);

You should not 'ask' for values from 'this' or higher scope when you can have it closer.


Program to find the maximum number/factor in a list

You have two independent conditions that must be satisfied before updating cur_val.

The number must be divisible by factor
The number must be larger than cur_val

If the first test fails, you don't bother doing the second test.
How many instruction (or better cycles) does it take to do each test?
Given a long non-monotonic list, you may save considerable time simply by reversing these two tests.


Fastest way to find all neighbours of a vertex in a graph

As of Mathematica 9.0 we have the function AdjacencyList[g,v].
Since this is built into Mathematica, I would assume that it is the fastest implementation.

In[1]:= g = CompleteGraph[7];
In[2]:= AdjacencyList[g, 4]
Out[2]= {1, 2, 3, 5, 6, 7}
In[3]:= g = CompleteGraph[{3,4}];
In[4]:= EdgeList[g]
Out[4]= {1 <-> 4, 1 <-> 5, 1 <-> 6, 1 <-> 7, 2 <-> 4, 2 <-> 5, 2 <-> 6, 2 <-> 7, 3 <-> 4, 3 <-> 5, 3 <-> 6, 3 <-> 7}
In[5]:= AdjacencyList[g, 5]
Out[5]= {1, 2, 3}


Print all nodes at k distance from the root in a binary tree iteratively

I think it's a decent implementation. It is readable and understandable. Nonetheless, I have some tips:

Try to avoid single letter variable names, like d (unless in very specific cases like certain loop variables or mathematical constructs).
Personally not a fan of new lines after each opening brace, it breaks the flow for me.
Try to always use braces with if\while\... statements. It helps to prevent potential bugs.
You could instead of silently returning, throw an (IllegalArgument\Nullpointer)Exception when passed node is null. Fail fast! Same with negative depths passed.
Trivia: how would you print the root with your implementation?

I also do not think you need the marker. If you instead each loop execution only take all nodes present in the queue at the start of that loop, you will process all nodes level by level (but only use it if you have constant time size operations). As an example:

public static void print(Node root, int depth) {
    if (root == null) {
        return;
    }

    Deque<Node> queue = new ArrayDeque<>();
    queue.offer(root);

    while (!queue.isEmpty()) {
        boolean atRequiredDepth = --depth == 0;
        int nodeCount = queue.size();

        if (atRequiredDepth) {
            for (int i = 0; i < nodeCount; i++) {
                Node node = queue.poll();
                System.out.println(node.val);
            }
            return;
        } else {
            for (int i = 0; i < nodeCount; i++) {
                Node node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
    }
}


As written, $new will contain the return value of s///, which is 1 (true) or the empty string (false).  This will (almost) never match $content and you'll be rewriting every file unconditionally.

You can inject $1 directly without the pass-and-eval.  This will stop the Perl script altogether in the event of an error, which is probably desirable.

While my and lexical open etc. are good habits, they're at odds with the design constraints of a one-liner that needs to survive multiple levels of quoting.  For example, print FD prints $_ to handle FD, while print $fd needs an explicit $_ argument, else it prints the string representation of that handle to stdout.  Just switching to a bareword-open saves you five characters.

Perl has a mechanism to read whole files specified on command-line and you can shorten your script further by employing it.

Tying all this together, your one-liner can fit in one line with some whitespace to spare.  In 128 columns (plus four spaces of indent):

[alias]
    pie = "!f(){ git ls-files -z | xargs -0 perl -0777ne'$old=$_; '\"$1\"'; $_ ne $old and open FD, q|>|, $ARGV and print FD';} ;f"


Word frequencies from large body of scraped text

for i in range(1 ,num_batches +1):

Your inter-token spacing here is a little wonky. I suggest running this code through a linter to get it to be PEP8-compliant.

This string:

r'input_batch_' + str(i) + r'.txt'

can be:

f'input_batch_{i}.txt'

This code:

entries_raw = infile.readlines()
entries_single = [x.strip() for x in entries_raw]
entries = [x.split('\t') for x in entries_single]

can also be simplified, to:

entries = [line.rstrip().split('\t') for line in infile]

Note a few things. You don't need to call readlines(); you can treat the file object itself as an iterator. Also, avoid calling a variable x even if it's an intermediate variable; you need meaningful names.

This is an antipattern inherited from C:

for j in range(len(entries)):
    data.loc[j] = entries[j][1], entries[j][0]

You should instead do:

for j, entry in enumerate(entries):
    data.loc[j] = entry[1], entry[0]

That also applies to your for x in range(len(data)):.

This:

freq_dict = dict()

should be:

freq_dict = {}

This:

if key in freq_dict:
    prior_freq = freq_dict.get(key)
    freq_dict[key] = prior_freq + data['freq'][x]
else:
    freq_dict[key] = data['freq'][x]

can be simplified to:

prior_freq = freq_dict.get(key)
freq_dict[key] = data['freq'][x]
if prior_freq is not None:
    freq_dict[key] += prior_freq

or even (courtesy @AlexHall):

freq_dict[key] = data['freq'][x] + freq_dict.get(key, 0)

Note a few things. First of all, you were inappropriately using get - either check for key presence and then use [], or use get and then check the return value (which is preferred, as it requires fewer key lookups).

This loop:

for key in freq_dict.keys():
outfile.write("%s,%s\n" % (key, freq_dict[key]))

needs adjustment in a few ways. Firstly, it won't run at all because its indentation is wrong. Also, rather that only iterating over keys, you should be iterating over items:

for key, freq in freq_dict.items():
    outfile.write(f'{key},{freq}\n')


Trying to Store EditText Values in SharedPrefs using a Single addTextChangedListener

I'm not sure if what I write below is what you are looking for.  Also I don't know much about Android, so maybe that would not work for some reason.

preserveText(field1, "autoSave")
preserveText(field2, "autoSave2")

val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

fun preserveText(field: Type????, itemName: String) {
    field.setText(sharedPref.getString(itemName, ""))
    field.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { }

        override fun afterTextChanged(s: Editable) {
            sharedPref.edit().putString(itemName, s.toString()).apply()
        }
    })
}


Matching element of arrays on a condition

They key here is to to be able to abstract common functionality away. You're not expressing "node[i] is in the neighbor array" nicely. Simply write a function which does it for you:

int node_in_neighbors(int node, int neighbor[], int length) {
    int i;

    for(i = 0; i < length; i++) {
        if (neighbor[i] == node) {
            return 1;
        }
    }
    return 0;
}

In a more "high-level" language, you wouldn't have to write this function, and it would be in the library. You can now rewrite your forward/backward loops easily:

// to find in forward direction
for (i = 0; i < 4; i++) {
    // keep a node if his successor and him are in the neighbors array
    if (node_in_neighbors(node[i], neighbor, 4)
            && node_in_neighbors(node[i+1], neighbor, 4)) {
        found_indices[fwd_count ++] = node[i];
    }
}

// to find in backward direction
for (i = 4; i > 0; i--) {
    // keep a node if his predecessor and him are in the neighbors array
    if (node_in_neighbors(node[i], neighbor, 4)
            && node_in_neighbors(node[i-1], neighbor, 4)) {
        found_indices[count ++] = node[i];
    }
}

This makes the code clearer, since it's way easier to understand the logic now.

One issue is that you still have lots of 4 around. You should replace those in the loop with node_length - 1 and those in the node_in_neighbors call by neighbor_length, otherwise you could confuse them.

Define those lengths like this:

int node_length = sizeof(node) / sizeof(node[0])
int neighbor_length = sizeof(neighbor) / sizeof(neighbor[0])

This trick only works on static arrays, be careful.


The best argument for using an enum in this context is the ability to:

Early input validation
Allowing users to discover valid inputs

In order to take advantage of that, your first example needs a slight change to use the enum type as the parameter type:

class PxPath {
    PxPath ([string]$path, [pxPathType]$pathType) {
        # if user input a string that doesn't correspond
        # to a [pxPathType] name, we won't even get this far!
    }
}

Now, your user has the option to pass either a [pxPathType] value or a corresponding string value:

$pxPath = [PxPath]::new("some\path", [pxPathType]::FileSystem_Folder)
# or
$pxPath = [PxPath]::new("some\path", 'FileSystem_Folder')

But this would fail even before we reach inside the constructor:

$pxPath = [PxPath]::new("some\path", 'not_a_valid_enum_name')


Check whether given a pair of arrays are permutation of each other

Complexity

You suggest that the performance is \$O(n)\$, but it is not. It is \$O(n \log{n})\$ because the set constructor is a binary-tree building algorithm that has an additional log(n) operations for each value.

Style

While your code is all neat, and well laid out, the variable names are good, etc., there are two issues I see with unnecessary else-condiditions on if-statements, and un-braced 1-liners. Additionally, white-space around punctuation and operators is useful for readability. This code:

  if( size1  != size2)
       return false;
   else
   {
       std::set<int> first_set(array1, array1+size1);
       std::set<int> second_set(array2, array2+size2);

       std::pair<std::set<int>::iterator,std::set<int>::iterator> myPair=std::mismatch(first_set.begin(),first_set.end(),second_set.begin());

       if( *myPair.first != *myPair.second)

            return false;
        else
            return true;
   }

should be written:

if( size1 != size2)
{
    return false;
}
std::set<int> first_set(array1, array1 + size1);
std::set<int> second_set(array2, array2 + size2);

std::pair<std::set<int>::iterator, std::set<int>::iterator> myPair
   = std::mismatch(first_set.begin(), first_set.end(), second_set.begin());

return *myPair.first == *myPair.second;

Bugs

The set construct keeps just a single entry for all instances of a given value. Thus, for example, given the input [1,2,3,4,4,4,4] it will have just 4 entries.

This leads to bugs in your code when there are duplicates. For example, your code will identify the following two input arrays as being permutations of each other:

[1,2,3,4,5,5,5]
[1,1,1,2,3,4,5]


Wrapping SDL_Surface like this to get automatic cleanup in the destructor is a good idea. However, the current implementation makes a few assumptions that aren't necessarily correct.

Surface Creation

There are lots of ways to get hold of a surface. Getting it from a Window, loading from a file, manually creating it with SDL_CreateSurface, or using something like SDL_TTF to render a font.

The Surface class shouldn't care about how the surface is created. It only needs to accept a surface, and know whether that surface should be cleaned up on destruction, e.g.:

Surface(SDL_Surface* surface, bool freeOnDestruction);

should replace the current Window and string constructors. The LoadBMP function could be made a free function that takes a string and returns a Surface.

Window

The dependency of Surface on Window seems backwards. Since an SDL_Window owns an SDL_Surface of its own, it would make more sense for the dependency to be the other way around. Thus the Window class could have a GetSurface() function, returning a Surface, and the Update() function would make more sense as UpdateSurface() in the Window class (it doesn't make sense for non-window surfaces anyway).

Interface and Error Checking

BlitSurface is confusing because you have to remember whether to call source.BlitSurface or dest.BlitSurface. As member functions it might be better to have both a BlitFrom(source) and BlitTo(dest), that both call a single Blit function.

It might be better to use free functions instead:

void FillSurface(Surface& surface, Color const& color); // fill entire surface!
void FillSurface(Surface& surface, Rect const& rect, Color const& color); // fill a rect on the surface
void BlitSurface(Surface& source, Surface const& dest); // blit whole surfaces
// TODO: rect versions...

SDL_BlitSurface has some conditions you should check before and after (it doesn't work on locked / null surfaces, it returns an error code on failure). These should be handled and output a message / throw an error / terminate the program.

It would make sense to have a GetSDLSurface() function in the Surface class (similar to the GetSDLWindow() function). We can check (assert / throw / print message) that the surface pointer is non-null in this function before returning it. If the Blit and Fill functions are free functions, and not members, they can't access the private member directly and must use this function. This means they will automatically do the non-null error check when using the surface.

Using the Standard Library

The C++ Standard Library already contains a class to manage an object's lifetime like this: std::unique_ptr.

Instead of checking whether we have to free the surface in copy / move constructors, we can wrap it in a unique_ptr with a custom deleter. We can then use the default move constructor and move operators:

#include <iostream>
#include <functional>
#include <memory>
#include <cassert>

// placeholder for testing...
struct SDL_Surface
{
    SDL_Surface() { std::cout << "constructor" << std::endl; }
    ~SDL_Surface() { std::cout << "destructor" << std::endl; }
};

// placeholder for testing...
void SDL_FreeSurface(SDL_Surface* surface)
{
    delete surface;
}

class Surface
{
public:

    Surface(SDL_Surface* sdlSurface, bool freeOnDestruction);

    Surface(Surface&&) = default;
    Surface& operator=(Surface&&) = default;

    Surface(Surface const&) = delete;
    Surface& operator=(Surface const&) = delete;

    SDL_Surface* GetSDLSurface() const; // Blit / Fill etc. should use this to get the SDL_Surface.

private:

    using SDLSurfacePtrDeleterT = std::function<void(SDL_Surface*)>;
    using SDLSurfacePtrT = std::unique_ptr<SDL_Surface, SDLSurfacePtrDeleterT>;
    SDLSurfacePtrT m_sdlSurfacePtr;
};

Surface::Surface(SDL_Surface* sdlSurface, bool freeOnDestruction)
{
    assert(sdlSurface != nullptr); // no null surfaces!
    // (means we don't have to check the inner pointer every time we e.g. blit).

    auto deleter = freeOnDestruction ?
        SDLSurfacePtrDeleterT([] (SDL_Surface* surface) { SDL_FreeSurface(surface); }) :
        SDLSurfacePtrDeleterT([] (SDL_Surface*) { });

    m_sdlSurfacePtr = SDLSurfacePtrT(sdlSurface, deleter);
}

SDL_Surface* Surface::GetSDLSurface() const
{
    assert(m_sdlSurfacePtr != nullptr); // check this surface hasn't been moved from
    // (if the m_sdlSurfacePtr is valid, the inner surface should be valid (or at least non-null) due to the assert in the constructor).

    return m_sdlSurfacePtr.get();
}

int main()
{
    std::cout << "Construct + Destruct:" << std::endl;

    {
        auto sdlSurface = new SDL_Surface();
        auto surface = Surface(sdlSurface, true);
        // should get destructor call...
    }

    std::cout << "Construct + Leak:" << std::endl;

    {
        auto sdlSurface = new SDL_Surface();
        auto surface = Surface(sdlSurface, false);
        // will not get destructor call...
    }

    std::cout << "Construct + Move + Destruct:" << std::endl;

    {
        auto sdlSurface = new SDL_Surface();
        auto surface = Surface(sdlSurface, true);
        auto surface2 = std::move(surface);
        // should get destructor call...
    }
}


Finding all root-to-leaf paths in a binary tree

Names

What is the purpose of this class? My first thought when I see a class named LeafNode is that it's a model of a leaf node in a tree. But this class is not about modeling trees. The purpose of this class seems to be to contain the method binaryTreePaths, which returns a list of paths to all leaf nodes of the Tree parameter it receives.

A better (but still not great) name for this class would have been the name of the exercise: BinaryTreePaths.

The term "print" comes up several times, but there's nothing in the exercise about printing. The task is to return a list of strings. No printing. The overuse of this term throughout the implementation is misleading, confusing, noise.

Choice of storage

If you don't know the required size of a collection in advance, prefer a List, which can dynamically resize itself, such as an ArrayList, instead of a fixed size array. ArrayList exists exactly for this purpose.

Fragile state tracking

This class has a state, represented by the fields list, count, printArray. It's difficult to follow the state changes, as all methods may (and do) change these variables.

I recommend using so-called accumulator parameters. You pass an accumulator variable to recursive method calls, which append values appropriately. Consider this alternative implementation, using paths as an accumulator variable:

public List<String> binaryTreePaths(TreeNode root) {
    if (root == null) {
        return Collections.emptyList();
    }

    List<String> paths = new ArrayList<>();
    binaryTreePaths(root, "" + root.val, paths);
    return paths;
}

public void binaryTreePaths(TreeNode root, String prefix, List<String> paths) {
    if (root.left == null && root.right == null) {
        paths.add(prefix);
        return;
    }
    if (root.left != null) {
        binaryTreePaths(root.left, prefix + "->" + root.left.val, paths);
    }
    if (root.right != null) {
        binaryTreePaths(root.right, prefix + "->" + root.right.val, paths);
    }
}

This improves in the original in simplicity.

Alternative implementation

Another variation on the previous solution, but using a StringBuilder instead of string concatenation:

public List<String> binaryTreePaths(TreeNode root) {
    if (root == null) {
        return Collections.emptyList();
    }

    List<String> paths = new ArrayList<>();
    binaryTreePaths(root, new StringBuilder("" + root.val), paths);
    return paths;
}

public void binaryTreePaths(TreeNode root, StringBuilder builder, List<String> paths) {
    if (root.left == null && root.right == null) {
        paths.add(builder.toString());
        return;
    }
    if (root.left != null) {
        int len = builder.length();
        binaryTreePaths(root.left, builder.append("->").append(root.left.val), paths);
        builder.setLength(len);
    }
    if (root.right != null) {
        binaryTreePaths(root.right, builder.append("->").append(root.right.val), paths);
    }
}


LeetCode: Intersection of two arrays ii C#

if (!nums1Count.ContainsKey(num))
            {
                nums1Count.Add(num,1);
            }
            else
            {
                nums1Count[num]++;
            }

I think it can be written as:

nums1Count.TryGetValue(num, out int count);
nums1Count[num] = count + 1;

You don't have to test the return value of TryGetValue() in this case, because TryGetValue() sets count to default (0) if it returns false.

The loop could also be written as a LINQ sequence as:

var nums1Count = data.GroupBy(i => i).ToDictionary(gr => gr.Key, gr => gr.Count());

Likewise:

            if (nums1Count.ContainsKey(num) && nums1Count[num] > 0)
            {
                res.Add(num);
                nums1Count[num]--;
            }

can be changed to:

if (nums1Count.TryGetValue(num, out int count) && count > 0)
{
  res.Add(num);
  nums1Count[num]--;
}


For input "abccba" Balanced substring are "cc" , "bccb" , "abccba" ie
  count=3 (Provided as per problem statement discussion) But I guess
  "aa", "bb", "cc", "abba", "acca", "cbbc" are also balanced sub string
  for the same input which makes count=6. Any wrong in my interpretation
  ?

A substring is a string that appears unbroken within another string. So for example, the provided answers are substrings

cc       ab|cc|ba
bccb     a|bccb|a
abccba   |abccba|

The other balanced substrings "aa", "bb", "cc", "abba", "acca", and "cbbc" are not substrings but a subset (w/ duplicates) of the characters in the original string.

The main thing to note is that order of the characters as well as the count of each characters matters.

EDIT: Formal Definition of Substring

@OP: Beware not to confuse substring with Subsequence


ActiveAdmin: Hide a whole panel in a smart way

I don't know ActiveAdmin, so I can only offer a local improvement.  That said, a little metaprogramming could work here.  The idea is to have the list of resource items in one place:

RESOURCES_ITEMS = [
  :phone,
  :fax,
  :email,
  :resource,
]

and then use that list with Object#public_send and Enumerable#any?:

if RESOURCE_ITEMS.any? { |item| resource.public_send(item).present? }
  panel I18n.t('contact_details') do
    attributes_table_for resource do
      RESOURCE_ITEMS.each do |item|
        if resource.public_send(item).present?
          row.public_send(item)
        end
      end
    end
  end
end

While not a huge improvement, this does DRY the list of resource items.


First of all, I think you misspelled refresh as refreash.
Second, your usage can probably be simplified
CacheGet(AlotOfWork);

Finally, you might want to check if refreshFunction returns null and maybe log a warning then as that function returning null would cause a cache miss every time.
Now to answer your specific questions.

I'll say it, the generic implementation is better. dynamic is a great trapdoor when you get really bogged down with generics or anonymous types and there's neat things you can do with it (see Dapper) but it still has some gotchas. For example, I do not think your function with dynamic will work in most cases.
HttpRuntime.Cache expects and returns object types meaning all types are being downcast or boxed. Therefore, if your function returns a User object, what is stored is still an object and what is returned from the cache is downcast likewise. Therefore your user.Username property will not be available until you cast, even though it's dynamic.

Yes. The generic version - with some subtle yet real differences - will run as if it was written for the type you're filling <T> with. The dynamic version will just be a "value" and let the DLR figure out how to invoke members (which again, unless you're calling ToString() or GetHashCode(), will fail). dynamic will also be slower as the runtime binding has to be done every time, though admittedly this is unlikely to be any sort of bottleneck.

Obviously I'm going to say always use the generic version in this case.


Find Pythagorean Triple with Perimeter == 24

There is no need for Lists a,b, and c, only one of them is needed.

So the flatmap could just use a three times:

a.flatMap(x =>
  a.flatMap(y =>
    a.flatMap(z => sumsEqualsTo24(x, y, z))))

For comprehensions can use extractors as you would in pattern matching or declaring a val.
You may find this more readable:

  ...
  c <- List.range(1, 11)
  (x,y,z) <- sumsEqualsTo24(a,b,c)
  _ <- pythagTriplebar(x,y,z)
} yield (a,b,c)

Likewise you can have

val ys = xs.flatMap{case (x,y,z) => pythagTriple(x,y,z)}


Presenting long string literals (URLs) in Python

You could use continuation lines with \, but it messes the indentation:

URL = 'https://www.targetwebsite.co.foo/\
bar-app/abc/hello/world/AndThen\
?whatever=123&this=456&theother=789&youget=the_idea'

Or you could use the fact that string literals next to each other are automatically concatenated, in either of these two forms:

URL = ('https://www.targetwebsite.co.foo/'
       'bar-app/abc/hello/world/AndThen'
       '?whatever=123&this=456&theother=789&youget=the_idea')

URL = 'https://www.targetwebsite.co.foo/' \
      'bar-app/abc/hello/world/AndThen' \
      '?whatever=123&this=456&theother=789&youget=the_idea'

I often use the parenthesized version, but the backslashed one probably looks cleaner.


Web-service for wiki-like movie database

A general comment: Extract logic to small private methods. Note that your methods are long which makes it hard to understand what they do. Every independent piece of code should be extracted into a private method. Like

private void RemoveMovie(id)

If you use the Add method on a List object it will insert the first item into the first place the second to the second and so on. No need in retchanges.Insert(0, new RMovieGenresChange()

GetMovieGenresChanges is a good method since it does only one thing unlike PostMovieGenre method which handles both the addition and the removal of the geners. This is a violation of the Single Responsibility Principle and hence you should split it to two methods: one for the addition AddGenereToMovie and another for the removal - RemoveGenereFromMovie.
This way yo keep your methods short, clean, readable and maintainable.


I can't speak to the specifics of the problem, since I don't understand exactly what you're trying to do, but the general idea seems to be:

Filter citizen_list based on some critiera
Apply some transformation to each citizen in citizen_list

To make that clearer, we can rewrite the code this way:

def _transform_citizen(citizen):
    # ???

def _is_valid_citizen(citizen):
    return citizen['handle'] and citizen['citizen_number']

def citizens(citizen_list):
    return [
        _transform_citizen(citizen)
        for citizen in citizen_list
        if _is_valid_citizen(citizen)
    ]

This has several benefits. It will reduce multiple layers of indentation. It will give you two functions with focused criteria. And it will make it clear that citizens() is doing just a filter and a transformation on the input list.


Trust the math. If exp<0 and cf<0, their product will be positive, so abs is redundant. BTW, in case of elif exp < 0, call to abs leads to an incorrect answer.
In any case, \$(ax^n)'\$ always equals to \$anx^{n-1}\$. Mathematically speaking there are no special cases. There are special cases when it comes to printing:

\$n = 0\$: you (correctly) print 0
\$n = 1\$: you print x^0, but it is better to omit it altogether
\$n = 2\$: you print x^1, but it is better to print just x.
\$n < 0\$: consider printing parenthesis around the exponent.

Separate concerns. The derivative shall only compute the derivative. Input shall be handled separately.
The call to derivative should be conditionalized:

if __name__ == `__main__`:
    derivative()

This enables you to import your code in another project.


There are two suggestions I have for situations like this:

double-negatives are bad
use abstract methods for extensions

Let me explain. A method isInvalid(...) is really is not valid, and that can then be used in an expression !isInvalid(...) which is not is not valid... which is complicated. You should reverse the logic in your code, and call the method isValid(...)

That way, your code keeps a better 'read' to it.

The second issue is about how it is best to manage having some base functionality, and extending it for particular purposes. The way I prefer (and I am not sure if there is a formal 'pattern' for this process), is to have the base class do the actual work, and delegate to the specific class for the more fine-grained validation. Your base class would be (note the final on the isValid method....:

abstract public class AbstractPersonValidator {

    public final boolean isValid( Person person ) {
        if ( person.getName() == null || person.getName().length() < 3 ) {
            return false;
        }

        if ( person.getSurname() == null || person.getSurname().length() < 3 ) {
            return false;
        }

        return detailIsValid(person);
    }

    protected abstract boolean detailIsValid();

}

So, that class declares an abstract method that the child classes will need to implement, and the abstract method will do the child-specific checks:

public class SourcingPersonValidator extends AbstractPersonValidator {
    @Override
    protected boolean detailIsValid( Person person ) {
        if ( person.getTechnology() == null ) {
            return false;
        }

        if ( person.getSource() == null ) {
            return false;
        }

        return true;
    }
}

The advantage of doing things this way is that you don't run the risk of a bug where you forget to call super.

Note also that I added braces to your 1-liners. My experience suggests this makes for more reliable code when your code enters a maintenance cycle.


Iterating through one map and one multimap and printing the vlaue of common keys

You can merge both maps to a "list". That should give you O(n) complexity solution where n is a total number of elements in both maps.
map elements are sorted from lower to higher, so simple iteration would yield an ordered list.
To merge maps, you need to iterate both of the maps, instead of insertion to a list, you can just output values to the screen.


- Use the strict and warnings pragmas

This helps catch many errors at an early stage.

- Declare lexical variables with my instead of using package variables

If you define variables without having declared them they will be defined as package variables (which are seen by all code in your package). Note that if you use the strict pragma you need to declare package variables with our.

- use say instead of print

Since perl version 5.10 you can use say to print a line and add the line terminator (newline character) automatically. Just remember to enable the the feature with use feature qw(say).

- Unpack arguments to a function/method from the @_ array for clarity

Prefer my ($str, $delim) = @_ over my $str = $_[0]; my $delim = $_[1]

- Use $array[$N] to refer to the ($N+1)th element of @array.

In you code you used @_[1] to refer to the second element of the @_ array. The correct syntax is to use $_[1].

- Do not use parenthesis around argument for builtin functions if not necessary.

In Perl parenthesis around function arguments is optional. A common style is to avoid parenthesis around builtin function calls. This reduces visual clutter and disambiguates built-in functions from user functions, see also What is the reason to use parenthesis-less subroutine calls in Perl?

- Don't declare empty arrays with empty parenthesis. Simply use my @arr;

- Return a reference to an array and not an array value.

By returning a reference you avoid copying, but see also In perl, when assigning a subroutine's return value to a variable, is the data duplicated in memory?

- Don't reinvent the wheel, use the Perl builtin function split

You tagged your question with [reinventing-the-wheel] so I assume this is for learning purposes only.

Here is a revised version of your code that implements the above comments:

use feature qw(say);
use strict;
use warnings;

{ # <-- create a scope so lexical variable does not "leak" into the subs below

    my $test = split_string("This is a test to ensure this works correctly.");
    foreach my $element (@$test) {
        say $element;
    }
}

sub split_string {
    my ( $string, $delimiter ) = @_;

    $delimiter //= " ";
    my @result;
    my $temp = "";

    for my $i (0..(length $string)) {
        my $char = substr $string, $i, 1;
        if (($char eq $delimiter) or $i == (length $string)) {
            push @result, $temp;
            $temp = "";
        } else {
            $temp .= $char;
        }
    }
    return \@result;
}


The Palindromic Odometer Puzzler: A Programmatic Solution

The documentation

   string: str

   returns: bool

is pretty obvious. I would skip it. The rest of the documentation can be more idiomatically written as

"""Return whether input sequence is a palindrome."""

(note palindrome, not plaindrome). I removed the term string because many sequence types can be palindromic, like [1, 2, 3, 2, 1].

find_puzzle_number should yield, not print, its values.

I would change the documentation to specify the rules the output satisfy.

def find_puzzle_number():
    """Generates 6-digit integers, x, where all of

    * the last 4 digits of x,
    * the last 5 digits of x+1,
    * the middle 4 digits of x+2, and
    * all 6 digits of x+3

    are palindromes.
    """
    guess = 100000
    # the odometer shows only 6 numbers,
    # therefore 999999 is the last number to test.
    while guess < 1000000:
        if is_palindrome(str(guess)[2:]):  # last 4 numbers.
            if is_palindrome(str(guess + 1)[1:]):  # last 5 numbers.
                if is_palindrome(str(guess + 2)[1:5]):  # middle 4 numbers.
                    if is_palindrome(str(guess + 3)):
                        yield guess

        guess = guess + 1

The while should become a for

# 6 digit numbers
for guess in range(10**5, 10**6):

Then the if chain of is_palindromes can be simplified:

valid = (
    is_palindrome(str(guess + 0)[2:]) and
    is_palindrome(str(guess + 1)[1:]) and
    is_palindrome(str(guess + 2)[1:5]) and
    is_palindrome(str(guess + 3))
)

if valid:
    yield guess

Now note something bad: guess + 3, can overflow. Either you want to clamp the code so that guess + 3 < 10**6, or you want to perform modular arithmetic.

Further, you don't know that 10**5 is a valid lower bound: 000000 is a valid reading. You can use format(guess, "06") to pad like this.

If you care about speed, PyPy makes the code run in about a tenth the time.

def is_palindrome(seq):
    """Return whether input sequence is a palindrome."""
    return seq == seq[::-1]

def find_puzzle_number():
    """Generates 6-digit integers, x, where all of

    * the last 4 digits of x,
    * the last 5 digits of x+1,
    * the middle 4 digits of x+2, and
    * all 6 digits of x+3

    are palindromes.
    """
    def as_reading(x):
        return format(x % 10**6, "06")

    # 6 digit numbers
    for guess in range(10**6):
        valid = (
            is_palindrome(as_reading(guess + 0)[2:]) and
            is_palindrome(as_reading(guess + 1)[1:]) and
            is_palindrome(as_reading(guess + 2)[1:5]) and
            is_palindrome(as_reading(guess + 3))
        )

        if valid:
            yield guess

print('These are the possible odometer readings: ')
for solution in find_puzzle_number():
    print(solution)

Note that there are simple optimizations you can apply. For instance, you can easily iterate over only those values for which guess + 3 is a palindrome by construction - this reduces the values to iterate over from \$10^6\$ to \$10^3\$.

for guess_digits in range(10**3):
    # guess + 3 is a palindrome
    # NOTE: relies on correct handling of wrapping
    guess = guess_digits + int(format(guess_digits, "06")[::-1]) - 3

This makes the code basically instantaneous, so if optimizations were pointless to apply before they're most certainly pointless to apply now.


Making a property virtual to cause EF to load the property

EF will not create a wrapper around the Restaurant class! Instead it will derive from your Restaurant class and it will override that property (public ICollection<RestaurantReview> Reviews) because it needs to create a proxy or navigation property instead of an everyday property. If you don't specify that property as a virtual one, the EF can not create a navigation property over it and your relations will not work.

I recommend you to check out this behavior through the debugger you will see classes with this kind of name: Restaurant_HFUEOHUEOHHRRHRHRHHRHIFEFNSES355KL4KLH4KH3KLNEN3L3


This is a nice answer to a fun challenge.  There are a couple ways I can see to improve it.

This solution only works for arrays of up to 10 values due to the for loop terminating after 10 iterations.  We can make it work for an arbitrary number of values by closeing the channel when Walk has complete, and testing for each channel's state to match.
Testing the value earlier in the walk will lead to earlier fails.  Reordering the send on the channel to be first will allow this.

Here is a refactored version of your code:

func Walk(t *tree.Tree, vals chan int) {
    if t != nil {
        vals <- t.Value
        Walk(t.Left, vals)
        Walk(t.Right, vals)
    }
}

func Same(a, b *tree.Tree) bool {
    avals := make(chan int, 8)
    bvals := make(chan int, 8)
    go func() {
        Walk(a, avals)
        close(avals)
    }()
    go func() {
        Walk(b, bvals)
        close(bvals)
    }()
    for {
        av, aopen := <-avals
        bv, bopen := <-bvals
        if aopen != bopen || av != bv {
            return false
        }
        if !aopen {
            return true
        }
    }
}

Buffering the channels is still useful since synchronization is not a requirement for evaulation, so I've left them buffered.


Finding a word ladder using Breadth First Search

If you worry about the performance, the first thing to try is to hook up the profiler. Besides that, constructing another Ladder at each level seems wasteful.

is_changeable is named misleadingly; my first impression was that you are testing a mutability of something. It turned out that the method test for a Hamming distance to be 1. I recommend to name it hamming_distance, make it return int (or size_t or whatever you find appropriate) ant let the client test the result for 1.
Use of lambdas borders to abuse. If you feel a need to comment what lambda is doing, it is a strong indication that the lambda wants to have a name, i.e. be a normal function.


Javascript - varargs constructors, method chaining, and static methods

Answer: Yes, yes, and yes.

Honestly, I'm wondering how else you'd achieve it. The arguments object exists to let you access whatever was passed; return this is really the only way to allow chaining; and the "static" method is technically just an object property, and that's the way you define those.

Only things I'd add is that you can easily convert the arguments object - which is "array-like" but not actually an array - to a real array by saying [].slice.call(arguments, 0);. Useful for looping, slicing, etc.. And you should always use braces/curly brackets - even if the "block" is just 1 line - just good code hygiene. Oh, and when in doubt, use hasOwnProperty() in a for...in loops.


Count groups of open cells around a cell on a grid

You could try using ramdajs. I solved it as follows but it could be way better

// indexes of the order to iterate in array square
const cord = [6, 7, 8, 5, 2, 1, 0, 3, 6];
const binaryRand = ()=>  Number(Math.random() < 0.5);

//const square = [1, 1, 1, 1, 0, 1, 0, 1, 0];
const square = R.times(binaryRand,9)

const zeroToOne = (acc,curr,index)=>{
  if(index === 0) return 0;
  return acc+= Number(!square[index-1] && square[curr])
}

const countGroups = (square)=>
  ((R.sum(square) - cord[4]) < 8)?
     cord.reduce(zeroToOne,0) : 1;

countGroups(square);

here is the Ramdajs repel of the code.


The following code works fine and faster than the previous one to obtain all of k-permutations provided there's no duplicate data in the input. I use an array as the output in the loop instead of the range of cells. It's usually considered to be faster than working on the range of cells. This code also gives two different choices of output. See the comment for the clarity.

Dim k As Long, Permutation_Table
Sub Permutation()
Dim Data_Input, Permutation_Output
Dim Output_Row As Long, Last_Column As Long, Array_Row As Long

Rows("2:" & Rows.Count).Clear
Last_Column = Cells(1, Columns.Count).End(xlToLeft).Column
Data_Input = Application.Transpose(Application.Transpose(Range("A1", Cells(1, Last_Column))))

k = InputBox("Input the value of k for P(" _
    & UBound(Data_Input) & " , k) where k is an integer between 2 and " _
    & UBound(Data_Input) & " inclusive.", "Permutation", 1)

Array_Row = WorksheetFunction.Fact(k) * WorksheetFunction.Combin(UBound(Data_Input), k)

ReDim Permutation_Table(1 To Array_Row, 1 To k)

If k >= 2 And k <= UBound(Data_Input) Then
    ReDim Permutation_Output(1 To k)
    Call Permutation_Generator(Data_Input, Permutation_Output, Output_Row, 1)
Else
    MsgBox "The input [" & k & "] is invalid. The input must be an integer between 2 and " _
    & UBound(Data_Input) & " inclusive."
End If
Range("A3").Resize(Array_Row, k) = Permutation_Table    'Use this line if UBound(Data_Input) < 10
End Sub

Function Permutation_Generator(Data_Input As Variant, Permutation_Output As Variant, _
                               Output_Row As Long, Output_Index As Integer)
Dim i As Long, j As Long, P As Boolean

For i = 1 To UBound(Data_Input)
    P = True
    For j = 1 To Output_Index - 1
        If Permutation_Output(j) = Data_Input(i) Then
            P = False
            Exit For
        End If
    Next j
    If P Then
        Permutation_Output(Output_Index) = Data_Input(i)
        If Output_Index = k Then
            Output_Row = Output_Row + 1
            For n = 1 To k
                Permutation_Table(Output_Row, n) = Permutation_Output(n)
            Next n
            Debug.Print Join(Permutation_Output, ",")    'Optional, use this line as the output if UBound(Data_Input) > 9
        Else
            Call Permutation_Generator(Data_Input, Permutation_Output, Output_Row, Output_Index + 1)
        End If
    End If
Next i
End Function


Command line tool for Italian language studies

Maybe this could provide of a more neat way of relating verbs with veb_forms:

verb_binder = dict(are=AreVerb, ire=IreVerb, ere=EreVerb)

def build_regular_verbs(verbs, verb_forms):
    def make(verb):
        try:
            return verb_binder[verb[-3:]](verb, verb_forms)
        except KeyError:
            raise Exception("not a regular verb")

    return [make(v) for v in verbs]

not sure if verb_binder dictionary should be a module global or local to the function or maybe it should be located elsewhere, but this is the idea.


You have conceived a theoretical model that works. And avoids sorting.

Tiers by frequency
Every tier contains letters of that frequency

It will come at no surprise, that moving a char from on frequency's bin to the next frequency's bin will cost at least as much as sorting. But it is a nice mechanism
one sees too rare, and might have its application in vector operations, GPUs or whatever.

Improved could be the names. "Tier" one inclines to love, and might be apt, but does the term help in understanding the code?
Use if possible more general interfaces implemented by specific classes, like List<T> list = new ArrayList<>();. This is more flexible, when passing to methods, reimplementing with another class.
The comment to remain is for adding null for the frequency 0.
For characters in a tier use a Set. As implementation I used a TreeSet which is sorted to give nicer output.
Use as index not i but rather freq.
Moving from one frequency to the next higher can be done in two separate steps old+new. That makes the code more readable.

so:

public static String frequencySort(String s) {
    if (s.length() <= 1) return s;

    List<Set<Character>> charsByFrequency = new ArrayList<>(); // stores characters at their proper frequency "tier"
    Map<Character, Integer> frequencyMap = new HashMap<>(); // maps the characters to their current frequency tier
    charsByFrequency.add(null); // entry for frequency 0 is not used

    for (char c : s.toCharArray()) {
        Character ch = c; // Does ch = Character.valueOf(c);
        int oldFreq = frequencyMap.getOrDefault(c, 0);
        if (oldFreq != 0) {
            charsByFrequency.get(oldFreq).remove(ch);
        }
        int freq = oldFreq + 1;
        if (freq >= charsByFrequency.size()) {
            charsByFrequency.add(new TreeSet());
        }
        charsByFrequency.get(freq).add(ch);
        frequencyMap.put(ch, freq);
    }

    StringBuilder result = new StringBuilder();
    for (int i = 1; i < charsByFrequency.size(); i++) { // iterate through tiers
        Set<Character> tier = charsByFrequency.get(i); // get tier
        for (Character c : tier) { // for each char in tier, append to string a number of times equal to the tier
            for (int j = 0; j < i; j++) result.append(c);
        }
    }

    result.reverse(); // reverse, since result is currently in ascending order
    return result.toString();
}


Attaching both mouseenter and mouseleave event handlers using jQuery

First of all you can use jQuery hover and passing 2 functions (mouseenter, mouseleave)
and u can shorten it also with jQuery end

$('.foo').hover(
    function () {
        $(this).find('h1').addClass("hover").end().find('input').focus();
    },
    function () {
        $(this).find('h1').removeClass("hover").end().find('input').val('');
    }
);


converting object of arrays to an array of objects in a desired format

Your code is not bad. You use functional style to loop through the data, which is good. But inside the loop you do not have to check with if-elseif-elseif, as this is not solid when it comes to many many cases.
Maybe it would be better to use a map object to guide the process of matching data.

getSelectedItemsIds = selectedItemsList => {
    const keyNamesMap = {
        projectIds: "PROJECT",
        subjectGroupIds: "SUBJECT_GROUP",
        subjectIds: "SUBJECT"
    };
    let selectedItems = [];

    Object.keys(keyNamesMap).map( k => {
        selectedItemsList[k].map ( id => {
            selectedItems.push (
                {
                    type: keyNamesMap[k],
                    id: id
                }
            );
        });
    });
    return selectedItems;
}

This way it is more clear and more easy to add another type.


Element selectors for a RepeatButtonView

Using data-* attributes is actually part of the HTML5 standard.

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
These attributes are not intended for use by software that is independent of the site that uses the attributes.

(emphasis mine)
In my opinion, I like to keep behavior separate from style, so I lean towards using data-* attributes. A problem arises when you attach CSS styles to those custom attributes, though I must admit that some styling is OK (for instance, showing or hiding elements). If you want a data-ui=child element styled a certain way, add a class attribute to it to maintain your separation of style and behavior.
My only piece of advice when using data attributes is to "namespace" them such that you have data-ui and more specific or related attributes are data-ui-something where each data attribute your view framework uses is prefixed with data-ui. This helps prevent naming collisions with other people's code.


3. Monadic notation

Let's start with your last question, as it has a clichéd answer: Do whatever you prefer.  I often find the bind operator >>= nicer to read, but switch to do-notation as soon as the code gets complicated.  Another rule of thumb is to use do-notation if the code is easier to express imperatively.  Both notations are equivalent, there is no performance impact.

1. Idiomatic Haskell

Haskell has a few conventions about variable naming.  Lists are commonly referred to as xs or ys (think plural of x), while function parameters are named f or g.  Type parameters are almost always taken from the first letters of the alphabet.

perms3 :: (a -> a -> b) -> [a] -> [b]
perms3  f xs               = perms3' f xs xs
perms3' _ []         _     = []
perms3' c (x:xs)    [y]    = f y z : perms3' f xs  xs
perms3' c xs'@(x:_) (y:ys) = f x y : perms3' f xs' ys

Since perms3' is only used within perms3, it would make sense to define it as a local function.  This has the additional benefit that we can drop f from its parameter list, since it's already in scope and won't change.

perms3 :: (a -> a -> b) -> [a] -> [b]
perms3  f xs = perms3' xs xs
  where
    perms3' []         _     = []
    perms3' (x:xs)    [y]    = f y z:perms3' f xs  xs
    perms3' xs'@(x:_) (y:ys) = f x y:perms3' f xs' ys

2. Performance improvement

Pattern matching on lists usually takes two cases: empty and non-empty lists.  This can reduce code (DRY etc) and actually improve performance, as tests for empty lists are faster than tests for singleton lists.

perms4 :: (a -> a -> b) -> [a] -> [b]
perms4  f xs = perms4' xs xs
  where
    perms4' []        _      = []
    perms4' (_:ys)    []     = perms4' ys ys
    perms4' ys'@(y:_) (z:zs) = f y z : perms4' ys' zs

A quick test gave me a 20% improvement compared to perms3.

Notes on perms2

The fold in perms2 is just a map.  Using partial application, it could be written as

perms5 _ [] = []
perms5 f xs'@(x:xs) = map (f x) xs' ++ perms5 f xs
-- faster:
-- perms5 f xs'@(x:xs) = foldr ((:) . f x) [] xs' ++ perms5 f xs

However, this is (somewhat surprisingly) slower than the fold.  AFAICT, this is due to the fact that ghc won't inline map, but will do so with foldr.

Finally, here is how I (naïvely) would have written the code.  Looks nice,  performs terribly.

import Data.List (concatMap, tails)
perms6 f = concatMap pairs . tails
  where
    pairs [] = []
    pairs (ys'@(y:_)) = map (f y) ys'

or

perms7 f xs = concat $ zipWith (map . f) xs (tails xs)


Check if a linked list is a palindrome in O(n) time and O(1) space

I agree that your code runs in \$O(n)\$ time and \$O(1)\$ space complexity, but the issue I have is that you do in-place modification of the list..... and thus a "processed" list is no longer the same list as it started as.

This makes the function useless for most practical purposes. A list that returns "true" on one call, will likely not return "true" on the second call.

A compromise solution would be to restore the list linking after reversing the second half, but your method will still not be reentrant - even though it would be more convenient to use.

In other words, you are using the list itself as a place to store temporary "state", and that list is not entirely contained in your function. This is as bad, or worse, than using global variables.

In a real interview I would challenge the requirement to have the \$O(1)\$ space, and suggest that \$O(n)\$ space is an acceptable compromise - or that a double-linked list is a better data structure to contain this problem.


Count the number of duplicated chars in a string

A more straight forward solution would be to count each character and then to count the characters that have a count larger than 1. This can easily be done using the functional methods available in Kotlin's standard library:

fun duplicateCount(text: String): Int =
  text.toLowerCase()
    .groupingBy { it }.eachCount()
    .count { it.value > 1 }

.groupingBy { it }.eachCount() creates a map (Map<Char, Int>) that assigns each character in the string to its count.

.count { it.value > 1 } then counts all entries in the map where the count is more than one.

EDIT: Inspired by @SimonForsberg here in comparision a procedural implementation of the same algorithm. I also modified the version above to use the better count(predicate) method, which I originally forgot about.

fun duplicateCount(text: String): Int {
    val lcText = text.toLowerCase()
    val characterCount = mutableMapOf<Char, Int>()

    for (i in 0 until lcText.length) {
        val char = lcText[i]
        characterCount.put(char, 1 + characterCount.getOrDefault(char, 0))
    }

    var count = 0

    for (entry in characterCount) {
        if (entry.value > 1) {
            count++
        }
    }

    return count
}


Bash script to open or close gnome-terminal with a single keybinding

Instead of this:

function terminal_process {
  # Is gnome-terminal already running
  echo $( ps aux | grep $TERMINAL_EMULATOR | grep -v grep)
}

You don't need the echo, you can let the standard output simply go through:

terminal_process() {
  # Is gnome-terminal already running
  ps aux | grep $TERMINAL_EMULATOR | grep -v grep
}

The same goes for get_terminal_window too.

Notice that I also changed the wording style of the function definition. This is the recommended style in bash,
I suggest to apply this to all your functions.

You can actually go even further. [[ -z $(terminal_process) ]] is actually a text comparison, checking if the output of the command as a string is empty. Instead of that, it would be better to use the exit code of the function, like this:

if ! terminal_process; then
    # ...

This works, because the exit of grep will be success (= 0) if it matched something (process exists), and failure (non-zero) if it didn't match.

However, when using the function like this, since the output of grep is not captured within a $(...), it will be printed on stdout, which you probably want to avoid. You can easily suppress that by adding the -q flag:

terminal_process() {
  # Is gnome-terminal already running
  ps aux | grep $TERMINAL_EMULATOR | grep -qv grep
}

This can also be simplified:

echo $(($width_percent*$1/100)) $(($height_percent*$2/100))

Like this:

echo $((width_percent * $1 / 100)) $((height_percent * $2 / 100))


Could you have avoided get-diagonal-sums-reducer?

You probably could have used partial if you wanted, though I'm not sure it ends up that much better:

(defn diagnoal-sums-reducer [n sums [line-number line]]
  ...)

(reduce (partial diagonal-sums-reducer n) ...)

Is there a much less verbose way to do this.

I think there is.  I can see why you've tried to use reduce, but your reducer is doing way more than it should be.  Essentially, there's 3 things it's doing:

Calculating the coordinates of the  diagonals for the line.
Getting the values of those coordinates.
Summing the values together with the previous values.

There might be some situations where you'd need to do all of those things in a single reduce, but I don't think this is one of those cases.  It's also complicated by having to do this for both the primary and the secondary cases.

It ends up much simpler if you split the whole process out into the individual steps:

(defn sum [x] (apply + x))

(let [n 3
      matrix [[11 2 4]
              [4 5 6]
              [10 8 -12]]

      ;; Build up a list of coordinates for the diagonals.
      primary-coords (for [i (range n)] [i i])
      secondary-coords (for [i (range n)] [(- n i 1) i])

      ;; Extract the values of those coordinates
      primaries (map #(get-in matrix %) primary-coords)
      secondaries (map #(get-in matrix %) secondary-coords)]

    ;; Sum them, take the absolute difference
    (Math/abs (- (sum primaries) (sum secondaries))))


I'd maybe try something like the following. What I've done is remove the string manipulation and concentrate on rounding the numbers.

function formatGPA(originalGPA) {

    var originalGPAVal = originalGPA.value;
    var gPAVal = parseFloat(originalGPAVal);

    if (gPAVal < 0) {
        gPAVal = 0;
    } else if (gPAVal > 4) {
        gPAVal = 4;
    }

    if (isNaN(gPAVal)) {
        // Some kind of error handling
    } else {
        originalGPA.value = gPAVal.toFixed(2);
    }

}

//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->

document.getElementById('collegeGPA').onblur = function () {
    formatGPA(this);
};

The only problem with this is it's difficult to manipulate it as one types. Therefore I've actioned the manipulation only on blur.


I can't see that I'm gaining much by making it private either.

The clients of the GrowOnlySet might use this object in a inappropriate way. For example they can remove an element.

So I can do this, the compiler lets me do it.

var gset = new GrowOnlySet<string>();
gset.payload.Remove("element");

Now there is no grow only set anymore. The encapsulation is important.

Also as a client I really don't need to know the internal representation, which is the way how it was chose to represent the grow only set.

And because the payload property is public now the GrowOnlySet interface has a lot of other methods that I can use (via .payload... ), thus there is no abstraction. But I needed an interface made of only Lookup, Compare, Merge and Add methods.

There is not check for null newstore.

 public GrowOnlySet(HashSet<T> newstore)
    {
        payload = newstore;
    }

Thus the methods that are using the payload will throw a NullReferenceException which is not good. I prefer to throw a ArgumentNullException so I can create a consistent GrowOnlySet and to let the clients to be aware that they need to provide a new store.

 public bool Compare(GrowOnlySet<T> R)
    {
        return R.payload.IsSubsetOf(this.payload);
    }

Naming convention here. Suggested name is r. Or maybe find a better name like other (inspired from the HashSet itself)

this. is redundant, so it can be removed to make the code cleaner.

Compare and Merge accept null arguments but again this will throw NullReferenceException. Better is to inform the clients of this class that it really needs an object to be compared or to be merged with.

So the class is refactored to something like this

 public class GrowOnlySet<T>
    {
        private readonly HashSet<T> _payload;

        public GrowOnlySet()
        {
            _payload = new HashSet<T>();
        }

        public GrowOnlySet(HashSet<T> newstore)
        {
            _payload = newstore ?? throw new ArgumentNullException(nameof(newstore));
        }

        public void Add(T element)
        {
            _payload.Add(element);
        }

        public bool Lookup(T element)
        {
            return _payload.Contains(element);
        }

        public bool Compare(GrowOnlySet<T> other)
        {
            if (other == null) throw new ArgumentNullException(nameof(other));

            return other._payload.IsSubsetOf(_payload);
        }

        public void Merge(GrowOnlySet<T> other)
        {
            if (other == null) throw new ArgumentNullException(nameof(other));

            _payload.UnionWith(other._payload);
        }
    }


Disclaimer: I do eventually answer your question, there are just some other things I wished to point out.

GET vs REQUEST

First of all, I would consider using $_GET instead of $_REQUEST. I'm assuming its get your using judging by the data you are passing. It is generally a better idea to use the specific array you need if you know it rather than one that could potentially contain data from another source. For example, should you ever create a form with a path input, it will supersede any get path. But this isn't even necessary, the remote user can change that value should they wish. However, if you were to call them separately $_GET[ 'path' ] and $_POST[ 'path' ] you will be able to use them both together without losing any information and they are less likely to be hijacked (minus get, its pretty easy to hijack that).

Filter Input

Take a look at PHP's filter_input(). It will mean you only have to type that $url variable once and has the added benefit of sanitizing your input.

$url = filter_input( INPUT_GET, 'path', FILTER_SANITIZE_STRING );
//returns false if not set so
if( $url ) {
    //etc...
}

Array Shift

PHP's array_shift() returns the value shifted, so there is no reason to specifically call that value, simply set the variable as you shift it.

$resource = array_shift( $urlSegments );

Order of Logic

Instead of checking if the value of $urlSegments is empty, I would set it first then check it. A couple of reasons for this. What if "path" starts with a forward slash "/"? I believe explode will produce an empty element at the very beginning. Unless this is the desired result, it could cause errors. Also, it removes the need for those magic numbers, i.e.($urlSegments[0]) Yes its obvious where it came from and why you are using it, but it is a bad habit and is not extendable.

$resource = array_shift( $urlSegments );
if( ! empty( $urlSegments ) ) {
    if( ! empty( $resource ) ) {
        $action = array_shift( $urlSegments );
        if( ! empty( $action ) ) { $parameters = $urlSegments; }
    } else {
        //handle $url starting with a forward slash
        //this is where having this set up in functions would help
    }
}

Here's the Better Solution: Only one parameter

However, the cleanest way of all is to guarantee the length of $urlSegments, then use PHP's list(). So, you can use array_pad() to fill out the rest of $urlSegments should it be too short, otherwise list() will produce errors. If it is already of the proper size it will not do anything so you don't need to test it first. Now, to ensure that it doesn't already contain empty elements, that it didn't start with a forward slash, or have any double slashes, you should run it through array_filter(). Note: This will remove any element that could be considered "false" (0, '', null, -1, etc) so be careful here. This also means that if you were using empty or false parameters before, then it may not work the same way. Edit: This is if you use array_filter() without a callback, you could always make your own callback function to ignore certain values.

$urlSegments = array_filter( $urlSegments );
$urlSegments = array_pad( $urlSegments, 3, '' );
list( $resource, $action, $parameters ) = $urlSegments;

Here's the Better Solution: Multiple parameters

I just realized that $urlSegments could very likely be longer than 3 elements. In this case, I would filter and pad it like I did above, shift the first two elements into their respective variables then set $parameters to whatever remains of $urlSegments. Padding it first ensures that each variable has a default value of an empty string.

$urlSegments = array_filter( $urlSegments );
$urlSegments = array_pad( $urlSegments, 3, '' );
$resource = array_shift( $urlSegments );//default = '';
$action = array_shift( $urlSegments );//default = '';
$parameters = $urlSegments;//default = array( '' );

Shorthand

Finally, it is rarely a good idea to use shorthand in PHP. If I did not know what you were trying to accomplish, or had a slightly older version of PHP, I would think that $urlSegments = []; was syntactically wrong. Yes it works, but you could run across problems in the future. Not to mention its just easier to read $urlSegments = array();

Regex

That should clean up your code considerably. I would hesitate to suggest any regex, mainly because I find it extremely difficult to read.

Edits

Edited a few times to clean up post and add the second "Better Solution".


Here, while it may look nice, the method clean_hash is not general enough to be valid across all Hashes. So adding a method such as clean_hash to all Hashes would only serve to increase the coupling which is bad. A second problem is that you are mutating your method argument which is almost never advisable.

The  solution is to define the clean method outside, perhaps as a part of your internal API object and call HHTParty.get(path, :query => clean(options)).parsed_response.

I would also define the clean method this way

def clean(opt)
  Hash[opt.collect{|k,v| [k,v.is_a? Date : v.strftime('%Y-%m-%d %H:%m:%S'):v.to_s ]}]
end


PHP class architecture and dependency injection

Alright, let's start with your concerns, and then move on to the actual review:

A prepared statement costs about 50 times a normal statement. However, that cost is on the database server's side (i.e. on MySQL's side), preparing a statement A, then clearing the statement object on PHP, then preparing the same statement A (with different parameters) will not incur a penalty, because the query is cached by mysql.
A dependency injection container has advantages and disadvantages. It simplifies the dependency wiring process at the cost of magic. A dependency injection container is completely optional, don't sweat about it (especially in small projects).
What are you abstracting? That's a question that you should ask yourself every time you create a class or a layer (which is a bunch of classes that have the same purpose). You seem to trying to abstract the PDO object, hiding it from the user. But why? PDO is an abstraction on its own, you don't really need to abstract it. What you should abstract is either

Storage itself. Make a mapper that takes an object and stores/fetches it from storage. Note that I didn't say MySQL because mappers are storage agnostic, then you can work seamlessly across different storage types.
The SQL language. Make a criteria based API (also commonly known as DSL). Something like this: $db->select()->from('table')->where(Database::EQUALS("column", "value"))->limit(10); It's up to you.

Your current abstractions don't really add value to an application. Why would I use your class over plain 'ol PDO?
Yes, it should, and I'll explain. When you create an object, it should do one thing and one thing only. Your user object should be responsible for keeping track of data about the user. It's an object that represents a single user in your data model.

Your user should not be aware of its own means of storage. A user specifically can come from many places. It can come from a register form, it can come from a database, it can come from a migration CSV file containing hundreds of users to be inserted at bulk.

As a result, your user should be storage agnostic, it should not care where the data came from, it should just accept it in the constructor, and  work with what it's got.

A few more points:

Always keep your code properly and consistently indented.
Don't catch the database exception and kill the script every time when there's an error. Let the caller decide! What if I can live without a database and will rely on alternative storage methods until I can get the database back online?
Don't rely on constants for the database credentials! Pass the to the constructor!

public function openConnection(string $host, string $dbname, string $username, string $password) {

By default, refrain from having public fields. Everything should be as private as possible, and only what you want to expose to the outside world is public.
Assuming your user object is bound to the database, a database object would be part of the object's state, it's bound to that database instance. Why not pass it in the constructor and keep it as a property?
PHP7 added the ability to type-hint scalars (such as string), use that in your advantage.
Your instance methods seem to return a new user object, rather than changing the current one, that seems counter intuitive, make changes to the current object. If the consumer wants a different user, they should create a new User.


jQueryTools plugin custom effect for caching ctabs

From a once over :

Whether the content is loaded or not, you call panes_cont.children().hide();, you might as well centralize that 1 call
There is too much going on in the creation of new_pane, it ought to be split up.
lowerCamelCasing is good for you, also write out things. cont keeps reminding me of continue whereas you probably mean content
I prefer the line of comment on top of the function
There is no need to check length > 0, you can simply check for length
As Bill Barry pointed out, caching the loader image is more efficient
Most recent js standards suggest to put strings in single quotes, whichever way you go, you should be consistent for easy reading.

All the above together gives this:

//check if pane already loaded, if so, display it, otherwise send ajax
$.tools.tabs.addEffect("ajax_cache", function(tabIndex, done)
{
  var allPanes    = this.getPanes().eq(0).hide(),
      targetPane  = allPanes.find("#tabindex_"+tabIndex);

  if(targetPane.length)
  {
    targetPane.show();
  }
  else
  {
    var loaderImage = allPanes.append('<img id="tab_loading" src="/graphics/loading.gif"/>'),
        newPane = $('<div>').attr('id', 'tabindex_'+tabIndex),
        URL = this.getTabs().eq(tabIndex).attr('href');

    newPane.load(URL, function(){
      loaderImage.remove();
      allPanes.append(newPane.show());
    });
  }
  done.call();
});


The comments are misleading:

#Read second integer
li  $v0, 5      # Read 1st integer
la  $t1, B      # $t0 = A

umm... are we reading second or 1st? Bottomline is, do not overcomment the code.
syscall 5 leaves a value in $v0. The contents of $t0 (or $t1) is irrelevant during the syscall. Set them up when you need them:

li $v0, 5
syscall
la $t0, A
move    $t0, $v0

You store data to memory just to load them back. This is very anti-assembly. Generally you want to use registers as much as possible, and avoid memory as much as possible:

li $v0, 5
syscall
move $t0, $v0
...
li $v0, 5
syscall
# At this moment you have first integer in $t0, and the second in $v0.
# Just add them together. No memory access is necessary.

Consult your documentation on which registers are guaranteed to survive a syscall (I suspect, all of them besides $v0).
Nothing to simplify reading and printing.


Picking a random point along the edge of an area

Easy-peasy.  Just imagine walking around the rectangle starting at the origin in a counter-clockwise direction, and keeping track of the length traversed:

(defn random-edge-coord
  [width height]
  (let [len-1 width
        len-2 (+ width height)
        len-3 (+ (* 2 width) height)
        len-4 (* 2 (+ width height))
        pos   (rand len-4)]
    (cond
      (< pos len-1) [pos 0]
      (< pos len-2) [width (- pos len-1)]
      (< pos len-3) [(- len-3 pos) height]
      :else [0 (- len-4 pos)])))

(defn print-1 [[x y]]
  (printf "[%3.1f %3.1f] \n" (double x) (double y)) )

(dotest
  (nl)
  (dotimes [i 10]
    (print-1 (random-edge-coord 2 3))))

with result:

[1.4 3.0]
[0.0 0.2]
[2.0 2.1]
[1.2 0.0]
[2.0 1.4]
[1.7 0.0]
[1.5 3.0]
[1.5 3.0]
[2.0 0.7]
[1.0 3.0]

and

[1.0 0.0]
[1.4 0.0]
[1.4 3.0]
[0.5 0.0]
[0.0 2.6]
[2.0 2.7]
[0.0 1.5]
[2.0 2.8]
[0.9 3.0]
[1.1 3.0]

For a more general shape, you could calculate the length breakpoints in a loop and use a loop to search them in order instead of a cond.  You could also use generalized line-segments, then interpolate so you don't depend on simply vertical/horizontal coordinates.


Listing people with their phone numbers (if any)

What you are describing is known asLEFT OUTER JOIN

SELECT
   id,
   name,
   group_concat(
      concat(
         number,
         ' (',
         description,
         ')'
      ) ORDER BY description SEPARATOR ','
   ) AS phones
FROM people LEFT OUTER JOIN phones
ON person_id = id
GROUP BY id;

inner join => give me only rows with records in both tables
left outer join => give me all rows of from the left table along with any matching rows in the right..


Extracting specific rows and columns from a CSV file

Use round parenthesis for generators

Also x for x in was unnecessary:

return (filter(lambda a: a != '', row[span_start:span_end]) \
    for row in itertools.islice(file_, start_line, lenght))

If you use Python 2 you should use itertools.ifilter because it returns a generator while filter returns a list.

The functions is pretty clear overall, I suggest you space your argument list as according to PEP8 conventions. Also investigate in easier to remember argument formats like f(file, line_range, inline_range) where two tuples replace 4 arguments.


Print out all possible sizes of subsequences of string in C

Here's a way that (at least IMO) at least marginally cleaner:

#include <stdio.h>

int main(int argc, char const *argv[])
{

    char s[] = "abcdefghijk";
    int n = sizeof(s);

    for (int k = 1; k < n; k++)
    {
        for (int i = 0; i < n - k; i++)
        {
            printf("%*.*s, ", k, k, s + i);
        }
        printf("\n");
    }

    return 0;
}

As to things about the code that can be improved, the most obvious would be using sizeof (or strlen, if necessary) to find the length of the input array, instead of hard-coding it.

Realistically, there's probably not a lot you can do to improve speed/performance--it's virtually guaranteed to be heavily I/O bound (though Tom Ernack's suggestion of using fwrite instead of printf might help--then again, depending on the standard library you're using, it might not).


You write this is a

  Javascript function to convert SQL resultset to a string

however that is not true. It's a function that

executes an SQL query
converts its result set to a string
(sometimes) closes its DB connection

Generally its bad idea to have a function to do more than one thing. Especially the closing of a DB connection that (I presume) is passed in open is very out of place and unexpected to the user of this function, more so because it only happens when the result set of the query is empty. (The last dbConn.close() is never executed).

Conversely the result set is only closed if it isn't empty. I don't know which DB library you are using, so it may be ok, but I doubt it.

Generally you should be using try ... finally blocks to make sure you are closing your resources.

Next you have pointless assignments such as col_delim = col_delim; when handling default argument values. All current JavaScript implementations support default
parameters:

 function get_sql_string(dbConn, query_string, col_delim = ",", row_delim = "\n") {

Also look into using const/let instead of var.

Another potential bug is the use of .slice(0, -1). Besides being inefficient, it assumes that the delimiters are exactly one character long, which may not be the case. At the very least you should be using .slice(0, -col_delim.length), better would be not to add this final delimiter in the first place. This could be done by collecting the results/lines in arrays and using .join(col_delim).

String concatenation (especially in a loop) is anyway very inefficient and using join would help here, too.

Other than that: Code formatting is very inconsistent. For example:

if( vs if (
if (...){ if (...) {

etc. Choose one style and stay with it (preferably the latter version). Consider using an editor/IDE that can format the code for you.

Example reimplentation (untested):

function executeQueryAndFormatResult(dbConn, queryString, colDelim = ",", rowDelim = "\n") {
  try {
    const result = dbConn.executeCachedQuery(queryString);
    return formatResult(result, colDelim, rowDelim);
  } finally {
    if (result) {
       result.close();
    }
  }
}

function formatSqlResult(result, colDelim = ",", rowDelim = "\n") {
   const columnCount = result.getMetaData().getColumnCount();
   const lines = [];
   while (result.next()) {
      const row = [];
      row.length = columnCount; // Allows JS engine to reserve the needed number of entries ahead of time
      for (let i = 1; i <= columnCount; i++) {
         row[i-1] = result.getString(i);
      }
      lines.push(row.join(colDelim));
   }
   return lines.join(rowDelim);
}

EDIT: Do the columns actually start with index 1? It seems unusual, but I've adjusted my code.


#include <cstring>
#include <cstdio>

You're not using either of those, so remove them, and include <string> instead to get std::string.

std::string rot47(std::string s) { /* ... */ }

Why copy the caller's string? You're only reading from it, so take it by const&.

std::string s1 = "!\"#$%&\...";
std::string s2 = "PQRSTUVW...";

These two are constant, don't allocate them for every call, make them static (and const):

static std::string const s1 = "...";

std::string ret = "";

That initialization is not necessary, a default-constructed string is empty. You might want to reserve the appropriate size since you know it though, for optimal performance.

for (unsigned int i = 0; i < s.size(); i++) { /* ... */ }

You can use range-based for loop with strings:

for (auto c: s) { /* ... */ }

And you should probably check that s1.find actually found something, otherwise the line after that is undefined behavior.

And s, s1 and s2 are rather poor choices for those variable names. Something like "source", "original", "plaintext" for the input would be better. map_from / map_to could work for the other two.


Ruby function to fetch, filter, and generate data

Matthew, it appears to me that you are only making use of the two elements of data whose keys are the top two in the sort.  Please correct me if I am wrong.  If that is the case, I believe your code (after "edit") can be simplified to this:

  def self.fetch_data(company)
    data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data
    data = data.sort {|(k1,_),(k2,_)| -(k1<=>k2)}.first(2)
    loop do
      break if :done == choose {|menu| timesheet_menu data, data.map(&:first), menu}
    end
    Hash[data]
  end

Note that after the sort, data is an array of two 2-tuples, each corresponding to a key-value pair from the original hash.  If I misunderstood what you are doing, and you do need to pull out the 10 elements of the hash corresponding to the 10 highest-ranking keys, just change the parameter for first from 2 to 10, then extract the first two elements when you need them (i.e., data.first(2)).  You can then retrieve the key values from these 2-tuples or convert data.first(2) to a hash for the return value, as I have done with data.

Edit: Ah, valid_keys is modified by choose. Consider this as a further possibility:

 data = Hash[data.sort{|(a, _), (b, _)| -(a <=> b)}.first(10)]

 loop do
   break if (keys_chosen = choose {|menu| timesheet_menu data, data.keys.first(2), menu})
 end

 data.select {|k, _| keys_chosen.include? k}


Loading data from a web API to be displayed in a tableview

1) i would not use inner classes.

2) i would extract the data extraction part from the init to a other class / helper - a class should only have the data structure and not how to convert it

3) typo resposne => response