Simple text-to-binary converter written in C++

As already mentioned, your code is looking okay.  Here are my additions:

It's best not to use using namespace std.
Variables should be declared/initialized on their own line:

char letter = ' ';
char playAgain = 'y';

You don't need a newline between every line of code.  This will just make your program appear longer and harder to read.  Just separate lines into groups based on purpose.
Variable declarations/initializations should be placed as close in scope as possible to where they will be first used:

std::cout << "Please enter a character, word, or phrase: ";
std::string word; // declaration is first used here
getline(std::cin, word, '\n');

Your main loop could use for (;;).  This is essentially an infinite loop, but it should do a break at the end if the user inputs a value other than 'Y':

for (;;)
{
    // do stuff

    std::cout << "\n\nWould you like to try again? Y/N)";
    char playAgain;
    playAgain = std::toupper(playAgain);
    std::cin >> playAgain;
    std::cin.ignore();

    if (playAgain != 'Y')
    {
        break;
    }

    // playAgain is 'y', so do stuff again
}

Prefer to use std::string::size_type for the inner for-loop as it's the type returned from std::string::size().

Or if you have C++11, use a range-based for loop instead:

for (auto iter& : word)
{
    letter = iter;

    // ...
}


As @200_success mentions in a comment, this isn't a kosher use of Ord. I believe though that it is the property of antisymmetry that is broken, not transitivity. \$Rock \leq Paper \leq Scissors \leq Rock\$ means that by transitivity \$Paper \leq Rock\$, which violates antisymmetry since \$Rock \neq Paper\$. This may seem academic, but many library functions will break or produce incoherent results given your instance. Try to guess what sort [Rock, Scissors, Paper] will return. Don't get in the habit of writing bad instances just because you like their namespace.

What you should do instead is just write a grab bag of pure functions and domain-specific datatypes. This would look something like—

data Winner = PlayerOne | PlayerTwo | Tie

shoot :: RPS -> RPS -> Winner
shoot Rock Rock     = Tie
shoot Rock Paper    = PlayerTwo
shoot Rock Scissors = PlayerOne
-- ...

All top-level definitions should have a type signature always, full stop. main is always main :: IO ().

Since you're not doing anything fancy with your StdGen, just use the *IO functions.

main = do
          humanchoice <- prompt "Rock, Paper, or Scissors: "

          compchoice <- randomRIO (0,2)
          -- ...

One typeclass it would be appropriate to instance is Random, so that you can have a more semantic computer-player interface. I'll toss in Enum and Bounded instances because they make the Random instance more future-proof.

data RPS = Rock | Paper | Scissors
    deriving (Eq, Show, Read, Enum, Bounded)

instance Random RPS where
    random g = randomR (minBound, maxBound) g

    randomR (lo, hi) g = first toEnum $ randomR (fromEnum lo, fromEnum hi) g
        where first f (a, b) = (f a, b)

The last thing I would do would be to factor out the result message code from main, it's a little repetitive having putStrLn there three times, and you can conceive of various scenarios like making this two player where you'd want to be able to easily swap around result message generators.

humanTwo :: Winner -> String
humanTwo PlayerOne = "You lose :("
humanTwo PlayerTwo = "You win! :)"
humanTwo Tie       = "Tie."

And with all of those changes you end up with a main function like—

main :: IO ()
main = do
          humanchoice <- fmap read $ prompt "Rock, Paper or Scissors: "
          compchoice <- randomIO
          let winner = shoot compchoice humanchoice
          putStrLn $ humanTwo winner


Apply function to every subset combination and return square matrix

I'm afraid that I'm not familiar with pandas, so there are definitely some things that I'm missing. However, I've done a bit of poking this code with a profiler, and I have a two suggestions that I expect would be helpful.

In my timings, over half of the runtime (3.5s out of 6.5s for 100 repetitions) in your example was spent on these two lines:

x = dat[(dat['hour'] == i) & (dat['day'] == k)].distance
y = dat[(dat['hour'] == j) & (dat['day'] == l)].distance

If I understand the code correctly, (dat['hour'] == i) is passing over the whole dataset searching for indexes with the specified hour. Especially given that this is in the middle of a very hot loop, that seems like prime work to avoid doing! Consider changing the data structure to allow for quicker look ups: perhaps have a dictionary that maps your chosen hour to a list or set of indexes.

Second, let's take a look at this custom_fn

def custom_fn(x, y):
    x = pd.Series(x)
    y = pd.Series(y)
    x = x**2
    y = np.sqrt(y)
    return x.sum() - y.sum()

Now, I would normally not pay much attention to this function, because according to the profiler it just used up 8% of the total runtime. However, I did notice that it is almost completely seperable. The last line uses data derived from both x and y but until that you just use x for x things and y for y things. That suggests that there is considerable opportunity to cache the relevant x.sum() and y.sum() components, with the relevant calculations done outside of so deeply nested a loop.

For reference, the following code is my initial go at using some of this caching approach. There is still plenty of opportunity to improve, including changing data structure as mentioned, but it is already significantly faster. It has come down from 6.5 seconds to 3.5 seconds in total, of which 2 seconds is packing the dmat table.

import pandas as pd
import numpy as np

dat = pd.DataFrame({'day': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'hour': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'distance': {0: 1.2898851269657656, 1: 0.0, 2: 0.8371526423804061, 3: 0.8703856587273138, 4: 0.6257425922449789, 5: 0.0, 6: 0.0, 7: 0.0, 8: 1.2895328696587023, 9: 0.0, 10: 0.6875527848294374, 11: 0.0, 12: 0.0, 13: 0.9009031833559706, 14: 0.0, 15: 1.1040652963428623, 16: 0.0, 17: 0.0, 18: 0.0, 19: 0.0}})

def x_sum(x):
    x = pd.Series(x)
    x = x**2
    return x.sum()

def y_sum(y):
    y = pd.Series(y)
    y = np.sqrt(y)
    return y.sum()

def custom_fn(x_s, y_s):
    return x_s - y_s

def get_hour(i):
    return (dat['hour'] == i)

def get_day(k):
    return (dat['day'] == k)

def get_day_hour(hour, day):
    x = dat[hour & day].distance
    return x

# Empty data.frame to append to
dmat = pd.DataFrame()

day_indices = {k : get_day(k) for k in range(1, 3)}
hour_indices = {i : get_hour(i) for i in range(1, 3)}

x_sum_indices = { (i, j): x_sum(get_day_hour(hour_indices[i], day_indices[j])) for i in range(1, 3) for j in range(1, 3)}
y_sum_indices = { (i, j): y_sum(get_day_hour(hour_indices[i], day_indices[j])) for i in range(1, 3) for j in range(1, 3)}

# For i, j = hour; k, l = day
for i in range(1, 3):
    for j in range(1, 3):
        for k in range(1, 3):
            for l in range(1, 3):
                x_s = x_sum_indices[(i, k)]
                y_s = y_sum_indices[(j, l)]

                # Calculate difference
                jds = custom_fn(x_s, y_s)

                # Build data frame and append
                outdat = pd.DataFrame({'day_hour_a': f"{k}_{i}", 'day_hour_b': f"{l}_{j}", 'jds': [round(jds, 4)]})
                dmat = dmat.append(outdat, ignore_index=True)
return dmat

# Pivot data to get matrix
distMatrix = dmat.pivot(index='day_hour_a', columns='day_hour_b', values='jds')

print(distMatrix)

If you had a different custom_fn function that was not so easily separable, you could still benefit from caching the inputs to the function. E.g.

x_indices = { (i, j): get_day_hour(hour_indices[i], day_indices[j]) for i in range(1, 3) for j in range(1, 3)}
y_indices = x_indices

...
    jds = custom_fn(x_indices[(i, k)], y_indices[(j, l)])


Algorithm

You will benefit greatly from using OpenCV's built-in functionality rather than performing this operation yourself. OpenCV supports masked operations, which will only apply to pixels where the mask is nonzero.

cv::Mat global_average(const cv::Mat& input, const cv::Mat& levels)
{
    assert(levels.channels() == 1);
    cv::Mat output(input.size(), input.type());
    for (int level = 0; level < nlevels; ++level)
    {
        const cv::Mat mask = levels == level;
        const cv::Scalar avg = cv::mean(input, mask);
        output.setTo(avg, mask);
    }
    return output;
}

Using functionality already present in OpenCV is not only clearer and shorter (by a factor of 3), but also allows the code to be more flexible. You will notice:

There is no explicit type conversion or array indexing occurring, which is safer.
This code is also more flexible: you do not need to convert your images to floating-point or integers.
It can operate on 8-bit images as well, which can give a significant speedup, since most of the time in the algorithm will be spent on memory access. Simply using the raw 8-bit images gives a ~15% speedup in my tests.
It is also possible that OpenCV functions may benefit from hardware and parallelism optimizations, which could make them faster than raw loops.

Code Style

Whitespace

Put spaces around your assignments and comparisons: int i=0; i<m; is harder to read than int i = 0; i < M;. Also, be consistent. Sometimes you do this already, but most of the time you do not.

Braces

You have nested for loops, but only the inner loop has braces. Both loops should have braces surrounding the body for consistency.

Precondition Checking

Although it is good that you leave comments indicating the data types you expect from in and lev, it is better to verify this in code. Adding assertions about these conditions makes it easier to debug if a wrong parameter is passed:

assert(in.depth() == CV_32F);
assert(lev.depth() == CV_32S);

Use const when you can

Both M and N do not change during the function evaluation. They can be declared as const int to allow the compiler to perform checks that they are never accidentally modified. Additionally, you can reduce the scope of pixlev by declaring it inside each of the loops. Then it too can be made const:

const int pixlev = lev.at<int>(i,j); // or use auto to reduce type duplication


Error checking in function that returns reference to static variable

The only things I would change are:

    // Move this boolean to the top.
    // So if you throw an exception that is not caught
    // you then stil know that you have tried.
    hasTriedLoadingPath = true;

    try {
         // No change.
         muiPath = Internal::zGetSpecialFolder(zCsidlSystem)
                 + L"\\" + Internal::zGetSystemLocale()
                 + L"\\" + L"wbadmin.exe.mui";
    }
    catch (AutoWinError const& e) {
        error = e.m_error;

        // Curious why you did not re-do the throw here?
        throw;  // Note. Not  `throw e;`
                // Rethrows the current exception.
    }


Two thoughts:

If there is other code and you need all the features of a TreeSet great, otherwise delegate to a TreeSet member variable.
Your code if (capacity <= 0) is somewhat superfluous because of the next test if (size() < capacity)


Sierpiński's carpet fractal animation for teaching Python 3

Algorithm

You can simplify the code and make it run faster if you construct the next-level carpet by continuing to work on the previous image (punching more holes in it), rather than starting with a blank slate every time.  The code can look prettier and more Pythonic too, since the technique lets you get rid of the recursion.

Coding practices

It's a good habit to write docstrings, especially if you are using this code to teach a student!

Avoid free-floating code; all code should be in a function.  Follow the standard practice of writing if __name__ == '__main__': main() at the end of the code.

You can combine the two import statements into one, since Image and ImageDraw are both being imported from the same module.

It should be easier to tell that the color triples represent dark green and light green.  A comment would work.  In my solution below, I've opted to use explanatory variables.  Furthermore, the colors should be specified in a more obvious place, rather than buried in some obscure place in the code.

In Python, it is usually possible to find a more elegant way to building a list than by repeatedly .append()ing.  Below, I construct carpets using a generator, and durations using the * operator.

You know that all of the coordinates should be integers.  Use integer division (//) rather than floating-point division (/) wherever possible.

You can use itertools.product() to avoid nested for loops for x and y.

To split a list into the first element and subsequent elements, you can write first_image, *other_images = images.

Suggested solution

from itertools import product
from PIL import Image, ImageDraw

def save_animated_gif(filename, images, durations):
    """
    Save images as frames of an animated GIF.  Durations should specify the
    milliseconds to display each frame, and should be of the same length as
    images.
    """
    # https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#saving
    first_image, *other_images = images
    first_image.save(filename, save_all=True, append_images=other_images, duration=durations, loop=0)

def punch_hole(draw, x, y, section_size, hole_color):
    """
    For a square with a corner at (x, y) and sides of length section_size,
    divide it into 9 tiles, and fill the center tile with hole_color.
    """
    corner = (x + section_size // 3, y + section_size // 3)
    # -1 necessary due to https://github.com/python-pillow/Pillow/issues/3597
    opposite_corner = (x + section_size * 2//3 - 1, y + section_size * 2//3 - 1)
    draw.rectangle((corner, opposite_corner), fill=hole_color)

def make_carpets(n, carpet_color, hole_color):
    """
    Generate n PIL Images, each of Sierpiński's carpet with increasing levels
    of detail.
    """
    image_size = 3**n
    carpet = Image.new("RGBA", (image_size, image_size), carpet_color)
    yield carpet
    for section_size in (3**i for i in range(n, 1, -1)):
        carpet = carpet.copy()
        draw = ImageDraw.Draw(carpet)
        for x, y in product(range(0, image_size, section_size), repeat=2):
            punch_hole(draw, x, y, section_size, hole_color)
        yield carpet

def main():
    N = 7
    DARK_GREEN = (5, 60, 20)
    LIGHT_GREEN = (5, 205, 65)

    carpets = make_carpets(N, carpet_color=DARK_GREEN, hole_color=LIGHT_GREEN)
    durations = [1200] * N              # 1200ms per frame, except...
    durations[0] //= 2                  # first frame is shorter
    durations[-1] *= 4                  # final frame is longer

    save_animated_gif("Sierpiński's carpet.gif", carpets, durations)

if __name__ == '__main__':
    main()

Alternative calculations

In the suggested solution above, I've written punch_hole() to be similar to your make_pattern(), in that they are both responsible for rendering a square of size section_size.  However, the arithmetic can be simplified by specifying the size of the center hole instead, so that no division is necessary.

def draw_square(draw, x, y, size, color):
    """
    Fill a square with one corner at (x, y) with the specified color.
    """
    # -1 necessary due to https://github.com/python-pillow/Pillow/issues/3597
    draw.rectangle((x, y), (x + size - 1, y + size - 1)), fill=color)

def make_carpets(n, carpet_color, hole_color):
    """
    Generate n PIL Images, each of Sierpiński's carpet with increasing levels
    of detail.
    """
    image_size = 3**n
    carpet = Image.new("RGBA", (image_size, image_size), carpet_color)
    for hole_size in (3**i for i in range(n, 0, -1)):
        draw = ImageDraw.Draw(carpet)
        for x, y in product(range(hole_size, image_size, 3 * hole_size), repeat=2):
            draw_square(draw, x, y, hole_size, hole_color)
        yield carpet
        carpet = carpet.copy()


The quest for a succint, readable expression of Next in a sequence

It sounds like what you want is a foreach over the Dictionary, combined with a break for the bytesToWrite condition.

foreach (var pin in dictionary)
{
    if (bytesToWrite <= 0)
        break;

    Debug.Print(pin.Key + ", " + pin.Value);

    // Write the bytes using Key and Value for location information.

    bytesToWrite -= bytesWritten;
}


PHP recreate array if it contains certain values

Only thing you can use besides the foreach loop, it is array_filter:

$selected_fruits = array_filter($fruits_arr, function($fruit) use($ids_arr) {
    return in_array( $fruit['id'], $ids_arr );
});

looks shorter and uses native functions


There's no documentation. What is this code supposed to do? How am I supposed to call it?
There's no functional decomposition. Code is easier to understand and test if it's organized into functions with well-defined inputs and outputs.
There's no inherent order to the neighbours of a point, so the natural representation of the neighbours is a set, not a list. Also, if you used a set, then you'd have a more efficient membership test, and you could update it with new points without having to check whether they are already present.

So I would write:

from collections import defaultdict

def find_neighbours(triangles):
    """Given an array of triangles (triples of points), return a graph in
    adjacency representation: that is, a map from point to the set of
    its neighbours.

    """
    graph = defaultdict(set)
    for x, y, z in triangles:
        graph[x].update((y, z))
        graph[y].update((x, z))
        graph[z].update((x, y))
    return graph


Project Euler #4 Largest Palindrome Product

Your method isPalindrome produces wrong results for negative numbers. (which is not important for Project Euler #4, but still)
It is also inefficient to convert all numbers to String. I would only do that when using BigInteger. With int, you can just use a little math:

public static boolean isPalindrome(int number) {
    return number == reverse(number);
}

public static int reverse(int number) {
     //negative numbers: reverse the positive and negate it again.
    if (number < 0) return -reverse(-number);
    //a 1-digit number is its own reverse
    if (number < 10) return number;
    int reversed = 0;
    while (number > 0) {
        //take the last digit of number and paste it to reversed.
        reversed = reversed * 10 + number % 10;
        //cut off the last digit
        number /= 10;
    }
    return reversed;
}

You are not using the method getPalindromeProducts(int multiplicand, int multiplier) correctly. You run both loops all the way down to zero.
The meaning of the names multiplicant and multiplier isn't clear imo. In a multiplication, both numbers are just factors. One of them is the minimum (100) and the other is the maximum (999). You're looking for numbers between 100 and 999, not between 100 and 0 or between 999 and 0.
You also do a lot of the work twice by running both loops all the way. For example, you will get a * b AND b * a. You can skip a lot of iterations by breaking out of the loop early.

Another thing to think about is the HashSet. The problem with Java Collections is that you cannot use them with primitive types. It will convert all numbers to Object, which will hurt performance. (You cannot have a HashSet<int> for example)
However, in this case, you don't need a HashSet at all. You don't care about duplicates, you just want to find the largest product. It is also not necessary to store all the palindromes you found; you only need the largest one.

public static int getLargestPalindromeProduct(int minFactor, int maxFactor) {
    int largest = 0;
    for (int a = maxFactor; a >= minFactor; --a) {
        for (int b = maxFactor; b >= a; --b) {//Note the b >= a, not b >= minFactor
            int product = a * b;
            if (product <= largest) break; //We can stop this iteration, because factors will only get smaller.
            if (isPalindrome(product)) {
                largest = product;
                break;
            }
        }
    }
    return largest;
}

Then call getLargestPalindromeProduct(100, 999);


Update column based on input variable in stored procedure

I think your stored procedure looks great!
The only line that had me scratching my head is this one:
Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')

I'm guessing those apostrophes are escape characters for asp.net but if that's not the case I would discard them.
Nice work!


Changing images when hovering over links

Refactor the function from the data. Then you can just bind the same function to all of the links.

html

Link 1

js

$('#navigation li a').hover(
    function(){
        $(this).addClass('hover');
        $('.box img').attr('src', $(this).data('img');
    },
    function(){
        $(this).removeClass('hover');
        $('.box img').attr('src', 'default.jpg');
    }
);


Your code looks quite reasonable, though there are a few tweaks you could consider.
Function or Callback? Rather than names like FoldlFunction and MMapFunction, since what those types contain are the types for the callback run for each element of the array, consider calling them FoldlCallback etc instead. It's a bit more precise and will make more intuitive sense at a glance. (One might think at a glance that FoldlFunction might refer to the type of the whole Foldl function, which is incorrect.)
camelCase is the near-universal convention for plain non-class functions and variables in JavaScript. PascalCase is generally used for class constructors and namespaces, which aren't being used here, so camelCase is probably more appropriate. Eg Foldl -> foldl (or to foldL).
DRYer types You only need to specify the type of a parameter when TypeScript can't infer it automatically. For example, with foldl, since the base value is T, and the array is T[], the callback - the f: FoldlFunction<T> - will be known to be of the form (a: T, b: T) => T. There's no need to additionally specify the arguments' types when calling foldl. That is, this:
foldl((a: number, b: number) => (a + b), 0, [1,2,3,4,12,14,15,16])

can be
foldl((a, b) => (a + b), 0, [1,2,3,4,12,14,15,16])

It's a good idea to let TypeScript automatically infer the types of variables and parameters whenever possible - less code to read makes comprehension easier. You can do the same thing for MMap and Filter.
Outside definition? I'm not entirely convinced of defining the type of the function/callback outside - it's one more type parameter that needs to be cognitively pieced together. Consider defining the callback type in the parameter list:
function foldl<T>(
    f: (a: T, b: T) => T,
    base: T,
    arr: T[]
): T {
    const [head, ...rest] = arr;
    return !head ? base : foldl(f, f(base, head), rest);
}

console.log(foldl((a, b) => (a + b), 0, [1,2,3,4,12,14,15,16]));

I consider that significantly more readable. You can do the same thing for MMap and Filter.
Falsey bug You use return !head ? base : foldl.... This will not run if head is falsey. For example, foldl((a, b) => (a + b), 0, [1,2,3,4,12,14,15,16]) results in 67, but foldl((a, b) => (a + b), 0, [0, 1,2,3,4,12,14,15,16]) results in 0, which probably isn't desirable. Check the array's length instead:
function foldl<T>(
    f: (a: T, b: T) => T,
    base: T,
    arr: T[]
): T {
    if (!arr.length) {
        return base;
    }
    const [head, ...rest] = arr;
    return foldl(f, f(base, head), rest);
}

This applies to MMap and Filter as well.
DRYer filter To fix the falsey bug and make Filter a bit cleaner, you can replace:
const [head, ...rest] = arr;
return !head ? [] :
    (f(head) ? [head, ...Filter(f, rest)] : [...Filter(f, rest)])

with
if (!arr.length) {
  return [];
}
const includeThis = f(head); // call this here to preserve callback execution order
const restFiltered = Filter(f, rest);
return includeThis ? [head, ...restFiltered] : restFiltered;


Broken API

The class name BST suggests that it's a binary search tree,
but it's not.
It's a node (in a binary tree), with private references to other nodes.

If it's intended to be a node in a binary search tree,
its API is broken.
The insert method takes two parameters,
both of them BST instances.
It works fine when the first parameter is a BST instance without children (left and right nodes both null),
but if you pass to it two nodes with children,
the result will be no longer a binary search tree,
for example:

BST root = new BST(5, null, null);
root.insert(new BST(3, null, null), root);

BST root2 = new BST(7, null, null);
root2.insert(new BST(3, null, null), root2);

root2.insert(root2, root);
root.inOrder(root);

System.out.println(root);

This will output:

3
5
3
7
BST [left=BST [left=null,right=null,data=3],right=BST [left=BST [left=null,right=null,data=3],right=null,data=7],data=5]

The result corresponds to this tree, which is not a binary search tree:

  5
 / \
3   7
   /
  3

You could avoid this by allowing to pass as parameter only data, not another BST instance.

Note that the constructor suffers from the same problem,
because the left and right parameters to insert arbitrary BST instances with children,
breaking the binary search tree property.

Strange API

The insert method doesn't use any fields or methods of the instance.
It could have been a static method.
It would have made more sense to use this method signature:

public void insert(int data) {

This method could use this.data, this.left, and this.right to perform inserting a new value,
and it could successfully protect the binary search tree property.

The inOrder method has the same issue.
I suggest to drop the BST argument.

After you rewrite the insert method this way,
and also drop the dangerous left and right constructor parameters,
the example code in your question will become simpler and more natural too:

BST root = new BST(5);
root.insert(3);
root.insert(8);
root.insert(2);
root.insert(4);
root.inOrder();
System.out.println(root);

Extension ideas

Instead of int as the data,
you could make this class generic,
by declaring as public class BST<T extends Comparable<T>>,
and using type T everywhere instead of int,
and rewriting x < y comparisons with x.compareTo(y) < 0.

Instead of inOrder printing data,
you could allow a Consumer<T> argument,
to let users decide what they want to do with the visited nodes.
For example, if you rewrite inOrder like this:

public void inOrder(Consumer<T> consumer) {
    left.inOrder(consumer);
    consumer.accept(data);
    right.inOrder(consumer);
}

Then users could print the node values in in-order with:

root.inOrder(System.out::println);

toString value hard to read

The toString method returns this for the tree in your example:

BST [left=BST [left=BST [left=null,right=null,data=2],right=BST [left=null,right=null,data=4],data=3],right=BST [left=null,right=null,data=8],data=5]

This is hard to read, because the data is printed after the children.
I suggest to print data before the children,
and also the implementation maybe slightly easier to read using String.format:

return String.format("BST [data=%s,left=%s,right=%s]", data, left, right);


Ping-pong game with JavaScript and Canvas

From a once-over,

Short 1 letter variables are terrible ( except for x and y ), b, p and W are just terrible
Also please spellcheck your variables: padles -> paddles
You should only detect collision when the ball is going to the left and gets in the danger-zone or when it is going to the right and getting in the danger-zone. So instead of doing 8 accesses, 1 AND and 4 sums (if(b.x + ball.r >= p.x + p.w && b.x - ball.r <= p.x + p.w) {) you should rather do something like

if( deltaX < 0 && ball.x < someLimit ){
  testCollision( ball , leftPaddle );
} else if( ball.x > someOtherLimit  ) {
  testCollision( ball , rightPaddle );
}

Where deltaX is the amount of pixels the ball is moving over the X axis, this should make paddle collision a lot more efficient
Please don't use magical constants, in this case I see 25 all over the place
Same for the keycodes, you should use constants for those


I'd definitely map the tuples to objects, to avoid all the index stuff later on. In this case, the question specifically says it's all about readability, so don't worry about memory usage (also because it's next to nothing).

const orders = data.map(order => {
  const [orderId, companyName, companyAddress, orderedItem] = order;
  return { orderId, companyName, companyAddress, orderedItem };
});

As for the rest of the code:

Your removeOrder could be implemented using filter, just like the all* functions; no need to manually push to a new array. And your showMostFrequent and itemsCount functions could both be implemented using map - again instead of manually pushing to a new array/object.

Overall though, I'd wrap everything in an Orders object/class, instead of passing the orders array on every call. Maybe something like this:

class Orders {
  constructor(data) {
    this.orders = data.map(order => {
      const [orderId, companyName, companyAddress, orderedItem] = order;
      return { orderId, companyName, companyAddress, orderedItem };
    });
  }

  // note: Assumes orderIds are unique
  remove(orderId) {
    const index = this.orders.findIndex(order => order.orderId === orderId);
    if (index === -1) {
      return null;
    } else {
      const order = this.orders[index];
      this.orders.splice(index, 1);
      return order;
    }
  }

  findBy(property, value) {
    return this.orders.filter(order => order[property] === value);
  }

  findByCompanyName(name) {
    return this.findBy('companyName', name);
  }

  findByCompanyAddress(address) {
    this.findBy('companyAddress', address);
  }

  itemCounts() {
    const grouped = this.orders.reduce((memo, order) => {
      memo[order.orderedItem] = memo[order.orderedItem] || 0;
      memo[order.orderedItem] += 1;
      return memo;
    }, {})

    return Object
      .keys(grouped)
      .map(key => { return { orderedItem: key, count: grouped[key] } })
      .sort((a, b) => a.count - b.count)
      .reverse();
  }
};

I've added a generic findBy method that's used by other two findBy* methods. But more importantly, the remove method now modifies the list of orders, and returns the removed order object (or null), rather than return a new array.


Type for each value and naming, anonymous structs inside struct

typedef unsigned long tick_t;

  we are arguing with friend about that - he thinks that we should [...] make tick_t just 64bits [...] but I want to make this code run fast on 16bit microcontrollers too

Personally, I would never use the long or unsigned long types in production code, because they vary in size even between different 32-bit platforms. On some platforms, int is 32 and long is 32 and long long is 64; on other platforms, int is 32 and long is 64 and long long is 64. Rather than play a guessing game with my program's future portability requirements, I would write explicitly

#if OMFW_USE_32_BIT_TIMES
typedef uint32_t tick_t;
#else
typedef uint64_t tick_t;
#endif // OMFW_USE_32_BIT_TIMES

This is much more typing, but it conveys the intended semantics unambiguously: that is, by default I want 64-bit tick_t, but I also want to give the builder the option of using 32-bit tick_t in case it's helpful to him. In fact, this lets the builder pass -DOMFW_USE_32_BIT_TIMES on his 32-bit platform, or -DOMFW_USE_32_BIT_TIMES=0 on his 16-bit platform if he really wants to.

  Do they have correct naming? I added _t prefix as uintx_t have.

FYI, that's a _t suffix (appended), not a prefix (prepended).

This is fine; but you are courting collisions with the standard library. For example, the standard library already defines time_t and off_t; if you get in the habit of using the exact same naming conventions as the standard library, then you might one day run into trouble when you need a name for an entity representing a "time" type or an "offset" type.

Therefore I would recommend at least namespacing the identifiers as omfw_time_t, omfw_offset_t, etc. (Also notice that I wrote out "offset" instead of "off", because it's clearer and the compiler certainly won't care that we're being a little more verbose.)

int pinSignal;
int pinDirection;

Surely pinDirection should be a bool. Also, in all cases where you're using int, I suggest being explicit about the expected range of the value: is an int16_t good enough? Could we get away with int8_t? I would definitely use unadorned int for computations, but here you're defining a storage format, which means it would be nice to clarify exactly how many bytes each field is expected to have.

  Is it OK to have multiple anonymous structs inside main struct?

Yes. But I do think it's confusing to sometimes have a multi-level access path and sometimes not. For example, you access one field as

myMotor.cur.speed

but another as

myMotor.pos.curDirection

Why is it not myMotor.cur.direction?  And why is myMotor.rt.currentStep not myMotor.cur.step or at least myMotor.rt.curStep, given that you're abbreviating current to cur on every other line of the program?

(Again, personally I would write out current and especially target; abbreviating them as cur and tar is more confusing than helpful IMHO. With current you have to worry about whether the proper abbreviation is cur or curr (I've seen both, particularly since curr is the same number of characters as prev and next and last). I've never seen target abbreviated as tar (although I have seen targ and tgt).

/**
 * num_t: Floating point number used to calculate
 * Please note, if you want [to] use fixed point or any custom
 * number, you should use operator over[l]oading feature of C++
 * and also implement following functions for it in omfw/math.h
 */
typedef double num_t;

You don't explain which functions are "the following functions." Also, it might be more appropriate to write this as

#ifndef OMFW_NUM_T
#define OMFW_NUM_T double
#endif // OMFW_NUM_T

typedef OMFW_NUM_T num_t;

so that it can be specified by the user at build time as e.g. -DOMFW_NUM_T=float.

/**
 * step_t: Hold current step value
 * Only increased / decreased by one
 * May be signed, unsigned, floating point
 */
#ifdef OMFW_PRECOMPUTE_TABLE
typedef uint32_t step_t;
#else
typedef num_t step_t;
#endif

I'm suspicious of this code. Why is it okay for the step number to be a double (which is what num_t is)? At the very least, you should replace the word num_t with double here for clarity. But also, maintaining this code is going to be a nightmare without a very thorough test suite. For example, you'll have to be very careful never to use ++ or % with a step number, because those don't work with double.

Why not just let the step number be int and be done with it?

Incidentally, I don't know what the initialism omfw_ stands for, but you should be aware that to a native English speaker it bears an amusing resemblance to "omfg". :)


Same Guy, Same Language, same criticism?
Let me start by (again) critzising your variable casing choice of SHOUTCASE
It's so darn hard to tell what's a variable and what's not :(
But your names got better since the last time. Cheez and Burgr aren't the best, but given their content is arbitrarily set and accordingly somewhat meaningless they really stand their ground.
One thing though: your Cheezburgers are not needed.
It's a waste of computation power to check divisors by the biggest one first if you return early. (I recall rolfl having some nice stats on that in one fizz-buzz review I can't find right now). We can completely elimimate that O RLY? YA RLY from your code.
Oh and while we're at cheeseburgers... There's one thing I really dislike on cheeseburgers... Pickles.
The temporary TROOF variable to remove that three YA RLY doing the same thing is completely overkill. Instead of PICKLES R WIN it would be sufficient to add the current Number to the total.
Code until now:
IM IN YR Mind UPPIN YR Number TIL BOTH SAEM Number AN Limit
    BOTH SAEM 0 AN MOD OF Number AN Cheez
    O RLY?, YA RLY
          Total R I IZ AddToTotal YR Number MKAY
    NO WAI
          BOTH SAEM 0 AN MOD OF Number AN Burger
          O RLY?, YA RLY
                Total R I IZ AddToTotal YR Number MKAY
          OIC
    OIC
IM OUTTA YR Mind

Now what have we got here? this looks like it should be either an ElseIf or just a simple combination of conditions into an Or.
The latter is the easier one, but for reference: There is an else if. It's MEBBE
Final Code:
HAI 1.2
    VISIBLE "HAI, PROJEK LOLLER ONE!!"

    I HAS A Limit ITZ 1000
    I HAS A Total ITZ 0
    I HAS A Cheez ITZ 3
    I HAS A Burger ITZ 5

    HOW IZ I AddToTotal YR Value
        I HAS A Result ITZ SUM OF Value AN Total
        FOUND YR Result
    IF U SAY SO

    BTW Iterates from 0 to 999
    IM IN YR Mind UPPIN YR Number TIL BOTH SAEM Number AN Limit
        EITHER OF BOTH SAEM 0 MOD OF Number AN Cheez AN BOTH SAEM 0 MOD OF Number AN Burger
        O RLY?, YA RLY
             Total R I IZ AddToTotal YR Number MKAY
        OIC
    IM OUTTA YR Mind

    VISIBLE SMOOSH "TEH ANSWER IZ " AN Total MKAY
    VISIBLE "DOWN WITH PROJEK LOLLER ONE!"

KTHXBYE


Use joined tables to make more performant database calculations and avoid unnecessary models instantiations.

def liked_by
  return [] unless object.likes.present?
  User.distinct.joins(:likes).where(likes: { bonus_id: bonus.id }).pluck(:email)
end


First: you leak memory. Terribly. Never use new unless you know what you are doing. Use smart pointers, or in this case just objects on the stack.

The visitor pattern is meant for separating algorithms from an object structure. There is no object structure / composition / hierarchy in your code, so there is no use for the visitor pattern.

Following your example, there should be a Cart class with an accept method, that iteratively calls accept for all elements in the cart.

Also the visitor pattern is supposed to prepare for unknown algorithms operating on data structures that should not know about the algorithms. So it does not make sense to use a return value here. If you want to accumulate a prize here, you would have to do it in the state of the visitor.

Also: Use consistent spacing between type& variable etc. Use consistent capitalization of methods (visit). Avoid redundant newlines.


I'd prefer to rewrite this

 if (!noViews && hasEditPermissions) {
     shareNavigate();
 } else if (noViews) {
     if (hasEditPermissions) {
         sharePublishNavigate();
     } else if (!isLoggeedIn) {
         loginSharePublishNavigate();
     } else {
         shareNavigate();
     }
 }

To this:

 if (hasEditPermissions) {
     if (noViews) {
         sharePublishNavigate();
     } else {
         shareNavigate();
     }
 } else {
     if(loggeedIn) {
         shareNavigate();
     } else {
         loginSharePublishNavigate();
     }
 }

The !noViews is redundant and it is usually confusing if you start an if-else expression with a negation. Besides that, try avoiding else if in favor of nested expressions. You should also try to make the boolean expressions functionally independent - if you have checked noViews somewhere, don't check it again.

I am not sure if the truth table for the two blocks are identical. I'll leave that up to you to verify.


Structure

I'm not quite sure why you chose to write your program the way you did. It seems to add complexity to the naive approach of using a normal function, without adding any benefits:

function fizzBuzzer(number) {
    var isBuzz = (number % 5) === 0;
    var isFizz = (number % 3) === 0;

    if (isFizz && isBuzz) { return "FizzBuzz"; }
    if (isBuzz) { return "Buzz"; }
    if (isFizz) { return "Fizz"; }

    return number;
}

Misc

parentheses: sometimes you have too many (for example ((isFizz) && (isBuzz)) would be more readable as (isFizz && isBuzz)), and sometimes you could use a bit more (for example, to understand var isBuzz = number % 5 === 0;, you need to remember the precedent of 3 things; I would probably change it to var isBuzz = (number % 5) === 0;).
spaces: I wouldn't put a space before ). But I would put one after { and before } to make the code more readable. So if (isBuzz ) {return "Buzz";} for example would become if (isBuzz) { return "Buzz"; }.
I like that you wrote unit tests for JavaScript code. You could also include a test for 0, and maybe negative numbers (as they are allowed as input to your function).


How to apply Python generators to finding min and max values?

eval(...)

What is the purpose of:

compilt = "r'(?=(" + genes[i] + "))'"
... eval(compilt), ...

It takes a string like "aa", and forms a new string "r'(?=(aa))'", which is source code for the raw string r'(?=(aa))', which when evaluated yields the string "(?=(aa))".

There is no escaping being done, no obvious reason to do the raw string formation and subsequent evaluation, and no prevention of a syntax error due to a stray ' character in the genes[i] array.  So ... why not simply:

regex = "(?=(" + gene[i] + "))"

and no call to eval(...) at all?

Regex Capturing

The regex subexpression (...) is a "capturing group", which copies the matching characters into an internal buffer, for returning in the match group.

>>> re.findall('(?=(aa))', "caaab")
['aa', 'aa']

Without the capturing group, the matching characters do not have to be copied to the internal buffer, to be returned.

>>> re.findall('(?=aa)', "caaab")
['', '']

Given that you are only interested in the len(...) of the list returned from re.findall(), the capturing group seems like unnecessary overhead, which can be eliminated for faster execution.

Compiled Regex

As Python uses regular expressions, it maintains a cache of the most recently used regular expressions.  This cache has a limited size, to prevent an excessive memory load.

In this exercise, you are repeatedly using the same gene regular expressions for each "healthy string" test.  If the number of genes exceeds the cache size, Python will be tossing out compiled regular expressions, only to compile them again moments later.

You can preempt this by compiling and storing all the gene regular expressions ahead of time.  Leveraging Python 3.6's f-strings, and list comprehension:

    genes = input().rstrip().split()
    genes_rx = [re.compile(f"(?={gene})") for gene in genes]

Used as:

               matches = len(re.findall(genes_rx[i], gn))

Now the gene to regular expression string, to compiled regular expression is done once per gene, instead of once per "healthy string" test.

Computing min/max weight without creating a list

How about:

    min_weight = math.inf
    max_weight = -math.inf

    for ...:

        weight = ...

        if weight < min_weight:
            min_weight = weight
        if weight > max_weight:
            max_weight = weight

    print(min_weight, max_weight)


common lisp: nested loop beautification (checkboard texture generator)

Not much better:

(defun init-texture (tex &aux (tex-w 16) (tex-h 16) (pixel-size 4))
  (gl:bind-texture :texture-2d tex)
  (gl:tex-parameter :texture-2d :texture-min-filter :nearest)
  (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
  (print *test-texture*)
  (let ((pixel-data (make-array (* tex-w tex-h pixel-size)
                                :element-type '(unsiged-byte 8)
                                :adjustable nil
                                :initial-element 0)))
    (loop for y below tex-h
          for line-offset = (* tex-w pixel-size y)
          do (loop for x below tex-w
                   for x-offset = (+ line-offset (* x pixel-size))
                   for c = (if (oddp (+ x y)) 255 0)
                   do  (setf (aref pixel-data (+ x-offset 0)) 255
                             (aref pixel-data (+ x-offset 1)) c
                             (aref pixel-data (+ x-offset 2)) c
                             (aref pixel-data (+ x-offset 3)) 255)))
    (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))

To get rid of the arefs is not really possible. One way would be to use the function REPLACE:

(replace pixel-data (vector 255 c c 255) :start1 x-offset)

But now it allocates a vector for that. Then one might want to wish that the vector would be allocated on the stack:

(let ((new-data (vector 255 c c 255)))
  (declare (dynamic-extent new-data))
  (replace pixel-data (vector 255 c c 255) :start1 x-offset))

Another way is not to write the arefs, but to hide it behind a macro:

(defmacro vector-put-at ((vector start) &rest data)
  `(progn
     ,@(loop for d in data and i from 0
             collect `(setf (aref ,vector (+ ,start ,i)) ,d))))

The you can write above as:

(defun init-texture (tex &aux (tex-w 16) (tex-h 16) (pixel-size 4))
  (gl:bind-texture :texture-2d tex)
  (gl:tex-parameter :texture-2d :texture-min-filter :nearest)
  (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
  (print *test-texture*)
  (let ((pixel-data (make-array (* tex-w tex-h pixel-size)
                                :element-type '(unsiged-byte 8)
                                :adjustable nil
                                :initial-element 0)))
    (loop for y below tex-h
          for line-offset = (* tex-w pixel-size y)
          do (loop for x below tex-w
                   for x-offset = (+ line-offset (* x pixel-size))
                   for c = (if (oddp (+ x y)) 255 0)
                   do (vector-put-at (pixel-data x-offset)
                        255 c c 255)
    (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))


Checking whether any item in an array has a desired value for a key

Easy to clean up your second suggestion, at which point, I would prefer it.

has(key) {
    for (let i = 0, len = this._items.length; i < len; i++) {
        if (key in this._items[i]) return true;
    }
    return false;
}

Note I determinethis._items.length only once with this approach vs. on every iteration.

You may consider returning index position of found item (or found item itself) here to make this more useful, because presumably you are checking for this key because you want to access it somehow. The caller would need to be aware of potential falsey behavior of 0 vs. false or similar.  You also would probably want to rename the function at this point to something more meaningful like getIndexHavingKey() or getItemHavingKey()

Of course, this is essentially what Array.find() and Array.findIndex() do.  You would just need to implement your key check check in callback.  That might look something like this:

var search = { key: 'someKey' };
// define filter callback
var keyExistsFilter = function (element) {
    // here 'this' is search object passed via find or findIndex
    return (this.key in element);
}

// get item from array based on filter
var itemWithKey = this._items.find(keyExistsFilter, search);

// get item index from array based on filter
var itemIndexWithKey = this._items.findIndex(keyExistsFilter, search);


Bugs

You return 'No Police!' instead of returning 0, but you don't check the return value. You might consider printing the string and returning 0 instead. Likewise for the no-thieves case.

Style

You are nominally compliant with pep-8, but your style is very much a beginner style. Why do you have variables named t_list and p_list? Do you really think that the _list part of the name is the most important, and likely to be overlooked by readers?

When choosing a name, you should almost always avoid using the type of the data in the name (1). After all, the type might change! (For example, you might switch from a list to a dict for storage.)

(1): Except when the type is the important part, like if you're writing a type conversion function (str2int or wav2mp3 or something).

Iteration

You are missing some tricks of Python iteration. First, let's look at your tp_build function:

def tp_build(n):
    thief_police = []
    for i in range(n):
        thief_police.append(random.choice(['T', 'P']))
    return thief_police

This code is a one-off "helper" that does a job that is described in the problem statement: generate a random array of police & thieves. Because it's simple and the requirements are clearly explained by the problem statement, you don't need to worry about documenting this, or leaving the code spelled out for comprehensibility. So just use a list comprehension and shorten that code a lot (also, strings are iterable):

def tp_build(n):
    return [random.choice("TP") for _ in range(n)]

In your ``catch` function, you have a lot of iteration. Again, you're writing too-simple loops when you could get clarity and performance from Python features.

p_indexes = []
t_indexes = []
for i in range(n):
    if tp_list[i] == 'P':
        p_indexes.append(i)
    elif tp_list[i] == 'T':
        t_indexes.append(i)

In this paragraph, you construct lists of the indexes of the different characters. If you're going to look up the value of tp_list[i], you should just use enumerate:

p_indexes = []
t_indexes = []
for i, ch in enumerate(tp_list):
    if ch == 'P':
        p_indexes.append(i)
    else:
        t_indexes.append(i)

Of course, this is another case where you could use comprehensions. In theory, this is twice as slow. In practice, the comprehension might be faster because Python knows how to speed it up. You'll have to check it:

p_indexes = [i for i in range(n) if tp_list[i] == 'P']
t_indexes = [i for i in range(n) if tp_list[i] == 'T']

Clarity

You don't provide a function level comment explaining your algorithm, and frankly it's not obvious to me. Obviously you are pairing some police with some thieves. But it would be helpful if you explained what/how your pairing mechanic was, and why you felt it produced a best-possible result. In cases where there are potential conflicts between pairings, how do you decide which to choose, and why?

Also, note that at the end you are doing a lot of unnecessary work.

new_p = []
new_t = []
for i in p_list:
    if i not in new_p:
        new_p.append(i)
for j in t_list:
    if j not in new_t:
        new_t.append(j)
final_combinations = list(zip(new_p, new_t))
print('Number of thieves caught: %s'%(len(final_combinations)))
return len(final_combinations)

First, you make new_p and new_t. (Which aren't new: bad names.) You make them contain unique members of a previous list. Then you zip them together. The effect of zip is to stop when the shortest source iterable is exhausted. Then you compute the len of the result.

Effectively, you're asking for the length of the shortest unique group of indexes. Since order really doesn't matter here (you're using the len of the result) you can use a set. And since you just care about the length, you don't need to zip them, just compare their lengths:

catches = min(len(set(p_list)), len(set(t_list)))
print('Number of thieves caught: %d' % catches)
return catches


Creating a generic filter system to pass into an API request

Am I on the right track here?

I think you are. Here's how you can use a few tricks to make it even shorter.

Instead of the interface you can implement what is common in an abstract class.

public abstract class Filter
{
    public virtual string Name => Regex.Replace(GetType().Name, $"{nameof(Filter)}$", string.Empty);
    public static implicit operator string(Filter filter) => filter.ToString();
}

This means the base class will get the name of the filter from its type and it'll be able to implicitly cast it into a string by calling ToString. Now everything the derived class needs to do is to implement its own ToString:

public class CreatedAfterFilter : Filter
{
    private DateTime _value;

    public CreatedAfterFilter(DateTime value)
    {
        _value = value;
    }

    public override string ToString()
    {
        return _value.ToString("yyyy-MM-ddTHH:mm:ss+00:00");
    }
}

So later in the loop you can just do this:

foreach (var filter in filters)
{
   getParams.Add(new KeyValuePair<string, string>(filter.Name, filter));
}

If you make the Name property virtual you can override it in a derived class if the name of the filter cannot be derived from its type name:

public class OrdersFilter : Filter
{
    public override string Name => "OrderIdList";

    public override string ToString()
    {
        ...
    }
}


For starters, you should replace your Vector with an ArrayBlockingQueue .  Then you can drop the wait and the null check.  Can also then remove synchronization on the add method since its handled by the data structure.

private final BlockingQueue<String> pendingURLs = new ArrayBlockingQueue<String>(64);
protected void doInBackground(Void... params) {
    this.backgroundThread = Thread.currentThread();
    while (!backgroundThread.isInterrupted()) {
        String url = pendingURLs.take();
        // fetch image...
        publishProgress(url, fetchedBitmap); // in onProgressUpdate I call a listener that can be implemented by any Fragment or other component
    }

public void addUrl(String url) {
    pendingURLs.put(url);
}

You should probably replace it with just a new thread instead of using asynctask at all.

public class ImageLoader implements Runnable {
  private final BlockingQueue<String> pendingURLs = new ArrayBlockingQueue<String>();

  public void run() {
    while (true) {
        String url = pendingURLs.take();
        // fetch image...
        publishProgress(url, fetchedBitmap); // in onProgressUpdate I call a listener that can be implemented by any Fragment or other component
    }
  }

  public void addUrl(String url) {
    pendingURLs.put(url);
  }
}

Then you can create it in your initialization somewhere, ie

 ImageLoader loader = new ImageLoader();
 new Thread(loader, "BackgroundLoader").start();


Yes, you are using this patter correctly here. Its use in PHP (especially as a generic implementation) is greatly reduced though. As the answers in your programmers.stackexchange.com point out: basically it is a hashmap. Now, PHP implements arrays as some form of hash map already. I see this pattern as an anti-pattern too. There are some use-cases of this pattern when you register validators along each property this property has to fullfil when setting.

The php class stdClass basically does what you want to achieve it a more direct way:

$object = new stdClass();
$object->key = $value;

Though I'd recommend not to use this code in production, it is a good way to learn of course.

So my review for your code:

$PropertyContainer: It is uncommon in PHP to have variables start in upper case. Most code I do read either starts in lower-case and follow Camel-Case or is snake casing.
public function __construct() { } just fills up space. Not required, therefore remove it.
You should have a closer look at how to work with arrays in PHP. Your current approach is highly inefficient. Many of the array functions do not relay on the array iterator's state. Currently you force PHP to iterate over the array. If you use dedicated methods instead, PHP doesn't have to iterate (which is much faster of course :))

To add an entry to your array there is no need to iterate over it without doing it first. You can either array_push it at the end or just set it by $this->PropertyContainer[$k] = $v.
Same goes for checking of existence. Use isset instead.
And for accessing you can use $this->PropertyContainer[$k] instead of iterating

$k and $v are bad parameter names. While they usually are recognized as key and value, there is no harm to call them this way. But this can be improved: you are talking about properties and not keys. So better name them $propertyName and $value. Shorthands should be used in local scope only (if at all).
While I suppose they are just there for debugging: echo'ing on error is a bad idea. Either return a error code or even better, throw an exception. Of course this requires a method to check if a property exists (e.g. hasProperty).
return; without any value is the default anyway at the end of a method. You can remove this, shorting the code. Elsish after some time another developer might wonder why it was written once: was it located at some other line? was there some return value previously?


There's no reason to make a reversed copy. Just index from the back.
Nor to delay comparing the differences. It just means you have to save them.
Following the above two points ensures the function never throws. So, in C++ mark it noexcept.
Next, there's no need to go over the string from beginning to end and from end to beginning. Just stop in the middle.
In line with that, you should use C++17's std::string_view so even the caller need not make a copy.
Also, return a boolean. Leave it to the caller to Interpret it as he likes, not necessarily by choosing some English words.
I have no idea why you are bringing floating-point into it with fabs(), instead of staying with integers using std::abs(). At least I'm reasonably sure the compiler will fix that inefficiency. Or will it?

Modified C++ code:

constexpr bool isFunnyString(std::string_view s) noexcept {
    std::size_t a = 0, b = size(s);
    if (b > 2)
        for (b -= 2; a < b; ++a, --b)
            if (std::abs(s[a] - s[a + 1]) != std::abs(s[b] - s[b + 1]))
                return false;
    return true;
}


Excel 2016 VBA - Show/Hide multiple shape groups

The simple answer is to use pass an array of names to the Shapes.Range, hide all 4 Groups, and then make the one Group visible.

ActiveSheet.Shapes.Range(Array("Group 19", "Group 20", "Group 23", "Group 71")).Visible = msoTrue
ActiveSheet.Shapes("Group 20").Visible = msoFalse

Reference: MSDN - Shapes.Range Property(Excel)

Considering that all Group default names start with "Group ", you could further simplify it by creating a function that will return the ShapeRange based of the Group number.

Public Function getGroupRange(ws As Worksheet, ParamArray GroupNames() As Variant) As ShapeRange
    Dim n As Long
    For n = 0 To UBound(GroupNames)
        If IsNumeric(GroupNames(n)) Then GroupNames(n) = "Group " & GroupNames(n)
    Next
    Set getGroupRange = ws.Shapes.Range(GroupNames)

End Function

Sub Pic_1_SA_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 23).Visible = msoTrue
End Sub

Sub Pic_1_SB_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 71).Visible = msoTrue
End Sub

Sub Pic_2_SA_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 19).Visible = msoTrue
End Sub

Sub Pic_2_SB_click()
    getGroupRange(ActiveSheet, 19, 20, 23, 71).Visible = msoFalse
    getGroupRange(ActiveSheet, 20).Visible = msoTrue
End Sub


Your solution:

copies the whole string twice (1. string.ToCharArray() 2. new string())
needs n bytes of extra storage (apart from the input and output; n is the size of the output)
potentially moves the characters in the string a lot (O(n2))
requires the input to already have free space for the expansion

Solution using StringBuilder:

copies the whole string twice (1. calls to Append() 2. StringBuilder.ToString())
needs about n bytes of extra storage
doesn't need to move characters at all
doesn't require the input to be in any special format

Based on this, StringBuilder is clearly the better solution.

But there is even better solution: just use string.Replace(). That's likely going to be quite efficient and it's much shorter than any other of the proposed alternatives.


I'll refer you to this excellent blog post on Coding Horror in regard to the name of your class. XyzManager in general is never going to be a good name for a class.

You should sort your usings alphabetically and get rid of any that aren't used. Visual Studio (or resharper) can both do that automatically for you (using 'organise usings' or 'clean up code' respectively).

What is your base class? SingletonEternal<FacebookManager>. I could argue that singletons are always 'eternal' - at least for the lifetime of the application... so the name is a bit off too.

As already mentioned - you shouldn't normally use public fields. Properties are better for encapsulation as you can control who sets the value as well as who can read it. At the moment you're letting any consuming code update the values. Auto properties aren't even much more code:

public string AccessCode { get; set;}

This might sound a bit mean, but your code looks ugly to me... Let me explain.

Which is easier to read?

thisfirstone

or

the second one

Hopefully you'd agree that the second one is easier to read, the same is true for your code. Separate parameters with a space, do the same for operators:

FB.API ("me?fields=id,name,picture",Facebook.HttpMethod.GET,GotMyInformationCallback);

Becomes:

FB.API("me?fields=id,name,picture", Facebook.HttpMethod.GET, GotMyInformationCallback);

and result.Error!=null should be result.Error != null. The same applies here a=>a.name change it to a => a.name. It would be even nicer if you changed a to something meaningful.

I know it all seems really trivial but code will be read far more often than it's written/edited so you should be optimizing for read time not saving the odd space characters when you're typing it.


So you're saying that you have a bunch of classes representing db rows, and need a WhateverHandler for each class?

Use generics.

https://msdn.microsoft.com/en-us/library/ms172192(v=vs.110).aspx
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

The type is replaced whenever you need to use it, like so:

internal class Handler<T> where T : new()
{
    private readonly Dictionary<int, T> _rows;
    private readonly string _tableName;
    private Handler() {}
    public Handler(string tableName)
    {
        _rows = new Dictionary<int, T>();
        _tableName = tableName;
    }

    public void Load()
    {
        using (var dbConnection = Program.Server.DatabaseHandler.Connection)
        {
            dbConnection.SetQuery("SELECT * FROM `{0}`;".Format(tablename));

            using (var reader = dbConnection.ExecuteReader())
            {
                while (reader.Read())
                {
                    var rowId = reader.GetInt32("id");
                    _rows[rowId] = new T();
                }
            }
        }
    }

    public bool TryGetById(int rowId, out T row)
    {
        return _rows.TryGetValue(rowId, out row);
    }
}

edit: thanks @kuskmen for reminding me about the new() constraint


What are you thoughts on this implementation?

It is simply awful. Besides code bloat, just look how you declare such objects, and how you call methods on such objects.

  Do you have suggestions for improvements or perhaps an entirely different system?

So, to fix your implementation :

add an interface for your Shader class. Like that, you can have different shader classes for vertex, geometric and pixel shaders
remove all templates
pass the shader's program id to constructor, and remove it from the Parameter class
move 'class Parameter' out of the 'class Shader', and make it a structure. It's member variables do not need to be static. By the way, name should be std::string - not const char*


Returning "" is reasonable, since that is what you want to use as the default value.

Returning the special value "!invalid property!" to indicate an error might be allowable only in the following limited circumstance:

This is view-layer code, not your model, not middleware, not an API, and
You actually want that special string to appear in the UI as a placeholder, and
The placeholder text is to be presented in the normal font and color.

If any of those conditions is not applicable, then the special string is absolutely inappropriate. That is precisely what exceptions are for — exceptional cases. If you present exceptional cases as if they were legitimate data, then you end up with bugs like this one, where a person whose name is Null causes grief.


Improve scala functional string transformation

If I might chime in briefly, it all looks fine, any modifications here are mostly a matter of taste and personal preference; for example, I'd make it a curried function with varargs:

def transformString(s : String)(functions : String => String*) =
    functions.foldLeft(s) { (str, fun) => fun(str) }

And you don't need to define functions as literals, for example:

scala> def toUpper(s : String) = s.toUpperCase
toUpper: (s: String)String

scala> def reverse(s : String) = s.reverse
reverse: (s: String)String

And then, using the slightly modified version above:

scala> transformString("blah")(toUpper, reverse)
res3: String = HALB

Of course, you can always use the literal, too:

scala> val reverse2 = (s : String) => s.reverse
reverse2: String => String = <function1>

scala> transformString("blah")(reverse2)
res4: String = halb

Or even provide the lambda in-place:

scala> transformString("blah")(_ + "1", _.reverse)
res9: String = 1halb

IMO, varargs here work nicely, and you can transform any sequence/collection into varargs by :_*; there are a few differences, though:

def methods have to be partially applied in the list (e.g. : toUpper_ below)
Underscore shorthand syntax won't work

so:

scala> transformString("blah ")(List(reverse2, (s : String) => s + "12", toUpper_):_*)
res21: String = " HALB12"

[EDIT for the comments]

1 & 2. Oh, there is a difference. You can easily make a function partially applied if it's curried, not so much if it just takes in arguments. Also, you can make shorthand underscore syntax work after applying the function partially:

scala> def blahArg = transformString("blah")_
blahArg: Seq[String => String] => String

Note the trailing underscore and the return type: a function (with lower arity). Now you can pass that function somewhere else where the second argument can be supplied. You can't do that when taking in both arguments at once. That also means that your second parameter changed from varargs to Seq, which - in turn - means you explicitly have to pass a Seq, List or something similar:

scala> blahArg(List(_.reverse))
res10: String = halb

3.Removing vowels looks fine :) If that's contained inside an object, you can move the Set initialization to the object level, so it's only initialized once instead of on every function call, but that's nitpicking.


How can I make my Merge Sort Code In C more secure, effective and efficient

make the code more compact and secure

Separate sort code from test code

To well address security issues, OP needs to present a clear distinction between what is the sort code and what is not.  Put all sort code in a separate .c file.

int vs. size_t

C employs size_t as the type that is neither to narrow nor too wide for array indexing and sizing.

Although int is commonly sufficient, to make more secure and work with large data, use size_t.

Aside from changing int --> size_t and "%d" --> "%zu", a singular challenge is to remember size_t is some unsigned type and code needs to consider that.  (size_t)x < 0 is never true.

Beware large VLAs

Security risk: int left[n1]; is subject to stack overflow.  Consider *alloc() instead.  Insufficient memory can be detected that way.

Avoid exposing helper functions

mergeSequence() is not meant to be used outside of mergesort().  To prevent other code from using this functions, make it static.  Further, put it and mergesort() in their own .c file.

This increases security as mergeSequence()  then not need to handle all sorts of arguments, just the ones mergesort() generates.

All warnings enabled?

Save time, enable all warnings.

I'd expect mergeSort(num,0,(n-1)); (upper case S) to warn about function usage before declaration.

void mergesort(int*,int,int); (lower case S) is declared but not used.

Avoid generic names when a specific type is required

mergeSort() sorts int.  With a name like mergeSort, I expected something like qsort() with its size-of-element parameter and compare function.

Of re-architect your merge sort code to take a generic object type.

void SS_mergeSort(void *base, size_t nmemb, size_t size,
    int (*compar)(const void *, const void *));`

Compact by eliminating print out

It is unexpected that a sort routine would do any printing.  Remove printf() and displaySequence() from merge...() functions.

Compact left,right code

int left[n1]; int right[n2]; can be int left_right[n1+n2]; and then the copying facilitated with the fast lib function memcpy().

memcpy(left_right, num, sizeof left_right);
int *left = left_right;
int *right = left_right + n1;
...


Evaluate the best common type to fit both of types

Your code does not take in account interface covariance and contravariance issues.

Here is the sample code that demonstrates it:

class ObservableOfString : IObservable<string> { /*...*/ }
class ObservableOfObject : IObservable<object> { /*...*/ }
class ObserverOfObject : IObserver<object> { /*...*/ }
class ObserverOfString : IObserver<string> { /*...*/ }
class Program
{

    static void Main(string[] args)
    {
        IObservable<object> observableIsCovariant = new ObservableOfString();
        IObserver<string> observerIsContravariant = new ObserverOfObject();
        Console.WriteLine(typeof(ObservableOfString).FindEqualTypeWith(typeof(ObservableOfObject)) ?? (object)"<NULL>"); // Would it not be more useful to return IObservable<object>?
        Console.WriteLine(typeof(ObserverOfString).FindEqualTypeWith(typeof(ObserverOfObject)) ?? (object)"<NULL>"); // Would it not be more useful to return IObserver<string>?
        Console.ReadLine();
    }
}

The fundamental issue is, as soon as you want to find the "best common interface", you are going to run in an issue, as "best" and "common" are at best dependent on the context. You should clearly identify which use cases you are going to support, in the context of why that method was needed, and write a specific implementation that solves your need.


Creating the design matrices for a canonical correlation analysis

Here you want to move away from for loops for two reasons:

your number of for loops depends on your number of datasets, so using for loops prevents you from generalizing your code to any number of datasets.
many for loops will likely slow down your code execution when working with a larger number of datasets.

I think the key to vectorizing your for loops is to use the expand.grid function. If you have

n <- 4

datasets, then you have

p <- n * (n - 1) / 2    # 6

degrees of freedom (the number of for loops in your code, or the number of items on the lower triangle of each matrix). If for each of these you can pick among

w <- seq(from = 0, to = 1, length.out = n)

then you can build the matrix of all possible combinations by doing:

W <- as.matrix(expand.grid(rep(list(w), p)))

Here W is a big matrix with 4096 rows, each row representing a different combination of your (i1, i2, i3, i4, i5, i6) variables:

> head(W)
          Var1      Var2 Var3 Var4 Var5 Var6
[1,] 0.0000000 0.0000000    0    0    0    0
[2,] 0.3333333 0.0000000    0    0    0    0
[3,] 0.6666667 0.0000000    0    0    0    0
[4,] 1.0000000 0.0000000    0    0    0    0
[5,] 0.0000000 0.3333333    0    0    0    0
[6,] 0.3333333 0.3333333    0    0    0    0

These 6 columns are only part of the n * n = 16 values needed in each matrix. We can expand using the following:

X <- matrix(1:(n*n), n, n) # pattern matrix of indices
A <- matrix(0, nrow(W), n * n)
A[,    X[lower.tri(X)]] <- W
A[, t(X)[lower.tri(X)]] <- W

A is similar to W in that it is a matrix with 4096 rows, but each row now has the n * n = 16 values of a symmetric matrix.

From there, you can reshape A into a 3D array:

dim(A) <- c(nrow(W), n, n)

and your 4096 matrices can be accessed as follows:

A[1, , ]
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    0    0    0    0
# [3,]    0    0    0    0
# [4,]    0    0    0    0

A[10, , ]
#           [,1]      [,2]      [,3] [,4]
# [1,] 0.0000000 0.3333333 0.6666667    0
# [2,] 0.3333333 0.0000000 0.0000000    0
# [3,] 0.6666667 0.0000000 0.0000000    0
# [4,] 0.0000000 0.0000000 0.0000000    0

A[4096, , ]
#      [,1] [,2] [,3] [,4]
# [1,]    0    1    1    1
# [2,]    1    0    1    1
# [3,]    1    1    0    1
# [4,]    1    1    1    0

If I were you I would probably stop here, i.e., keep the data in this form. A 3d array might allow you to continue writing vectorized code if the rest of your analysis allows for it. However if you absolutely want a list of matrices, you can do:

C_list2 <- lapply(seq(nrow(A)), function(i) A[i, , ])

(note that the order of the matrices in my data and yours do not match. Let me know if this is a concern, it's probably a matter of reorganizing the rows and/or columns of the W matrix.)


How do I make my Rock-Paper-Scissor program more JavaScript-like?

Well, there might be a few things.

The most important thing that can be changed is removing all those magic numbers: What happens when we want to play “Rock, Paper, Scissors, Lizard, Spock” instead? You'd think you would only have to update the choiceArray – but unfortunately the length of that array is encoded in various places.

This means that if (userChoiceIndex >= 0 && userChoiceIndex <= 2) should be

if (userChoiceIndex >= 0 && userChoiceIndex <= choiceArray.length - 1)

and var computerChoiceIndex = Math.floor(Math.random() * 3) should be

var computerChoiceIndex = Math.floor(Math.random() * choiceArray.length);

Your decideWinner function isn't really extensible, because you encode the winning relationships as code, not as the data it actually is. I'd use an object literal that only encodes what choice wins over another, like:

var winningData = {
  paper:     { rock:     true },
  rock:      { scissors: true },
  scissors:  { paper:    true }
};

Also, I'd implement decideWinner as a comparator that returns one of -1, 0, 1 depending on whether the first or the second argument won. This decouples the decision logic from UI like text.

function(choiceA, choiceB) {
  if (choiceA === choiceB)           return  0;
  if (winningData[choiceA][choiceB]) return -1;
  if (winningData[choiceB][choiceA]) return  1;
  console.warn("No ordering between " + choiceA + " and " + choiceB + " was found");
  return 0;
}

The game result is then determined as:

var ordering = decideWinner(userChoice, computerChoice);
var winningMessage = ordering < 0 ? "You win!" :
                     ordering > 0 ? "The computer wins!" :
                                    "It's a tie!";
var gameResult = "You chose: "          + userChoice     + ".\n" +
                 "The computer chose: " + computerChoice + ".\n" +
                 winningMessage;

Now when we extend the game, we just have to update the winningData. Notice that I display who wins, not what choice wins, as I don't think that would be tremendously interesting to a player. Also, he would have to make an association from the choice to the player, which is unnecessary mental effort.


vumeter % 50 < vumeter doesn't make much sense to me. For non-negative numbers, this is equivalent to vumeter > 50, so you can just use that instead. For negative numbers, this will always return false, although it seems like this would be an illegal argument to your function.

@mleyfman provided a great solution. In practice, the code provided achieves something called clamping, where you restrict a value to a specified range. You can roll your own clamp function like so:

clamp = (value, min, max) -> Math.min(Math.max(min, value), max)

levels = (vumeter) ->
  'green'  : clamp(vumeter,  0,  50)
  'yellow' : clamp(vumeter, 50,  85) - 50
  'red'    : clamp(vumeter, 85, 100) - 85
  // or, if you find it more meaningful to provide maxima as parameters rather than ranges:
  'green': clamp(vumeter, 0, 50)
  'yellow': clamp(vumeter - 50, 0, 35)
  'red': clamp(vumeter - 85, 0, 15)


Which option is better for readability when dealing with blank strings?

Instead of returning a "        " or string.Empty.PadRight(8, ' ') you should extract the values to some meaningful constants.

The easiest way would be for your example to just use the overloaded constructor of the String class like

private const string eightSpaces = new string(' ', 8);

this makes it clear for Mr./Mrs.Maintainer what it stands for. But because this seems to produce CS0133: The expression being assigned to <constant> must be constant. you should just use a readonly string like

private readonly string eightSpaces = new string(' ', 8);

Using your first version will lead for each bug which needs to be solved to count the spaces which are returned.

The name of this property is also poorly named. It doesn't represent an ImmediateDestinationRoutingNumber but instead ImmediateDestinationRoutingNumberSpaces.


Find all the factors of a given natural number, N

You don't need to keep an intermediate list here, just add all the divisors to a set:

from math import sqrt

def get_all_factors(n):
    divisors = set()
    for i in xrange(1, int(sqrt(n)) + 1):
        if n % i == 0:
            divisors.add(i)
            divisors.add(n / i)
    return divisors

if __name__ == "__main__":
    print get_all_factors(60)

I also added a if __name__ == "__main__": guard to allow importing this function from another script.

Note that there is no requirement for the output to be a sorted list in the problem statement you posted. If there is, you can just call sorted on the output of this.

As @kyrill mentioned in the comments, you could also make this a generator:

from math import sqrt, ceil

def get_all_factors(n):
    sqrt_n = sqrt(n)
    for i in xrange(1, int(ceil(sqrt_n))):
        if n % i == 0:
            yield i
            yield n / i
    if sqrt_n % 1 == 0:
        yield int(sqrt_n)


Doing it with folds pretty much begs you to create a custom accumulator and recursive function or fold within a fold like that.

A couple notes. I don't think foldr is tail-recursive. Also (λ (x acc) (cons* x acc)) is redundant. You can just use cons*

You're also using (reverse lst) in a few different places. You could create a separate definition here, or refactor.

(define (unzip lst)
  (define (template lst) ;;a list of null lists
    (if (null? lst)      ;;of the proper length
        '()
        (foldl (λ (x acc) (cons '() acc)) '() (car lst))))
  (define (cons* heads tails)
    (reverse (foldl (λ (hd tl acc)
                       (cons (cons hd tl) acc))
                    '() heads tails)))
  (reverse
      (foldl cons* template lst)))

Not much chage, but perhaps a bit easier to see what's going on. If your wanting to do it with a single fold, thats a bit tricker.

(define (unzip L)
 (define (mangle glob)
   (let loop ((news '()) (acc glob))
      (if (or (null? (car acc)) (pair? (car acc)))
          (cons (reverse news) (car acc))
          (loop (cons (car acc) news) (cdr acc)))))
  (reverse (apply foldl (lambda z (mangle z))'() L)))

Notice the lambda is just grabbing a list off all arguments, and we are applying foldl to the lists of lists, as if we are folding multiple lists. However arity is unknown so I've got to take all the arguments as a list, and figure out what is new and what was the accumulator on each round. As is this will choke on a list of lists of lists, but maybe an interesting approach.


I guess I was able to figure it out, not sure how I missed it but by simply adjusting the bg_DoWork the application loads twice as fast, as it only creates an Image once instead of twice.

    private void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        int i = 0;
        Image tempImage;
        foreach (FileInfo fileinfo in IconFiles)
        {
            tempImage = Image.FromFile(fileinfo.FullName);
            imageListLarge.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), tempImage);
            imageListSmall.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), tempImage);
            IconLoaderBGWorker.ReportProgress(++i);
            Application.DoEvents();
        }
    }


Install, configure, and maintain content for Ubuntu webserver

So, this might not be quite in line with your 100% automation approach, but the best way to provide a shell script access to a git repository is to use ssh keys to allow access to your git repository. Of course, this means you either need to log on and set up that key and grant access it to Git  (goodbye 100% automation) or securely copy a private key that already has access to the repository to your server. You'll probably want to keep that key someplace that requires a password to access it, so... chicken and the egg scenario. Unless your cloud provider gives you the ability to create a template that already has that key on it's file system when it's created. If you can do that, then you definitely want to go the ssh route.

Your clone would look something like this.

git clone ssh://username@bitbucket.org/username/repository.git

Okay, let's review your code now.

You're using sudo very liberally. It would be better to set file permissions appropriately. You can run into weirdness when using sudo along with git. You can end up with a repository on the file system owned by root and.. it can get messy.
There's no error handling what so ever. If any given step of your script fails, it will continue on trying to execute the next line.
If you needed to change the location of the repository, you'd need to change the /var/www/html string in 3 different places. If your repository changes locations, it would change in 2. Use variables appropriately.


Use the C standard library

Your code could be greatly simplified if you used the C standard library functions fopen, fclose, fread, fwrite and fprintf instead of the low-level POSIX system calls. The standard libraray also provides strlen which obsoletes your ft_len function but if you use the functions mentioned earlier, you won't have to count the length of a string any more anyway. If these standard library functions are verboten in your assignment, please state this in your question.

Be prepared for read and write to return early

read and write are not guaranteed to read or write all bytes they were asked to. The proper way to use them is therefore to call them in a loop until either all bytes are read / written or an error is encountered.

Be prepared for read and write to fail

read and write may fail in which case they return a negative value and set errno. You should check this and act upon the error appropriately.

Be prepared for files larger than 4095 bytes

You only call read a single time per file. The concerns about read returning early aside, what if the file is larger than your buffer?

Get rid of useless NUL termination

You stick a '\0' byte at the end of your buffer but nothing expects this. You're already passing around an explicit length (which is good, because the buffer may contain embedded NUL bytes). And if you do it anyway, it should be buf[size] = '\0';.

Don't guess the reason for an error

If you cannot open a file, you always report “No such file or directory”. But that isn't the only reason a call to open can fail. You should inspect the value of errno to find out why the operation failed. If you cannot find out the reason, reporting a generic error like “Cannot open file … for reading” is still better than guessing a potentially wrong reason. Reporting a wrong reason is worse than reporting no reason at all because it will mislead your users.

#include all required headers

I don't see any #includes of system headers in your code. Your code depends on the following headers.

<unistd.h> for open, read, write and close
<sys/stat.h> and <fcntl.h> for the respective flags

In case you have #included them in the header file you didn't show: Don't do that. What functions are needed in the implementation is an implementation detail. You headers should only expose the public API of your module.

Use proper types

The length of an array should be measured in size_t (defined in <stddef.h>) instead of int. The return type of read and write is ssize_t.

Avoid uninitialized variables

It's not the 1980's any more where we had to write code like this.

int i;
// …
i = 1;
// …
while (i < files)
  {
    // …
    ++i;
  }

Instead, we can write this.

for (int i = 1; i < files; ++i)
  {
    // …
  }

The more you limit the scope of a variable, the lesser the risk for accidentally misusing it.

The variables size and fd could be declared only inside the body of the loop. fd could be declared const then.

const int fd = open( … );

It would avoid certain mistakes and you wouldn't be tempted to initialize it with a meaningless value.

Avoid magic numbers

Your choice for a buffer size of 4096 is reasonable but still arbitrary. One day, you might decide to chose a different size. Yet, the constant – or, even worse, constants derived from it, which you cannot search for – is repeated several times in the code. Instead of hard-coding such magic numbers, use a named constant.

#define BUFFER_SIZE 4096

char buffer[BUFFER_SIZE];

const ssize_t count = read(fd, buffer, BUFFER_SIZE - 1);

You could also use sizeof(buffer).

Since C now supports variable-length arrays, you could also use a const variable instead of a macro #define.

Subtracting 1 isn't really needed because NUL termination isn't needed as mentioned above. But when you do need to derive a size, using an expression like this automatically updates the dependent value if the value it depends on changes.

The line

ft_writeln(1, " No such file or directory", 26);

is another example that is waiting for somebody to alter the text and forgetting to update the number. It's not even clear what the 26 means immediately.

In order to further reduce the amount of magic constants, consider using the macros STDOUT_FILENO, STDERR_FILENO and STDIN_FILENO, which are #defined in <unistd.h> to 1, 2 and 0 respectively. The benefit is not so much that these constants would change any time soon or people don't know what file descriptor 1 refers to but that in a function call

print(1, "hello, world\n");

the 1 could mean almost anything whereas in

print(STDOUT_FILENO, "hello, world\n");

the meaning of the first argument is much clearer.

Print error messages to standard error output

Programs should output their results to standard output and any logging, warnings or error messages to standard error output. One reason for this is that standard output is often redirected. If I execute

$ cat bar.c baz.c > foo.c

all standard output will go to foo.c but I still want to see the error messages. (And even if I don't want to see them, I certainly don't want them to end up in foo.c.)

Separate concerns

The arguments passed to main include the program name as argv[0]. This is fine but your ft_read function really shouldn't care where its arguments came from. Instead, the call in main should only pass it the relevant arguments

ft_read(argc - 1, argv + 1);

and ft_read should consider all elements (starting with index 0) of the array as file names to operate on.

Report errors all the way back

If your program fails at any point, it should report this back via its exit status. Therefore, if you encounter an error you cannot recover from, main should return EXIT_FAILURE (which is #defined in <stdlib.h>) or a small positive integer.

Structure the code in the way that minimizes surprises

You have separated the implementation logic from the file that contains the main function. This is good because it allows unit testing and code re-use. But there isn't really a good reason to put the ft_writeln function into a separate file. Actually, why do you have this function at all?

Declare functions static when they need not be externally visible

If a function is only used in the translation unit (the *.c file) that defines it, declare it static. This will make it inaccessible from other translation units and therefore improve encapsulation and avoid name-space pollution. It might also help increase performance.

Use names that properly reflect what a function is doing

ft_writeln sounds as if the function would write a line. But it actually doesn't care about lines. It simply writes out bytes.

Don't confuse return with a function

The return statement is not a function call. You don't need parenthesis around the value that is to be returned.

Use proper indentation

Your code is formatted correctly most of the time. But at some points, you forgot to indent the body of a loop or misplaced braces. There is no point in engaging in a flame war about how many spaces are the correct choice but there can be no dispute that you should use some indentation and use the same style consistently. A good editor will take care of this for you automatically.

Read the documentation for cat

If your goal is to be compatible to POSIX cat, read its documentation to find out what it does exactly. Implementing all of its options might be too much work for now but an interesting aspect of its behavior is currently not reflected by your version. If cat is given zero arguments, it reads from standard input instead. Your program simply does nothing in this case.


Welcome back! There are a lot of good things to say about your program, and a few not-so-good. First, the good:

The code is clean, well laid-out, and generally written in a Pythonic style.
You have used functions to break things down.
You have structured your program as a module, which should make it easier to test.

Here are some things that I think could be improved:

Your function names need a little work. Consider this code:

player_choice = ask_player()
comp_choice = comp_play()

The object is to get two choices, one made by the player and the other made by the computer. Why are the two names so different? ask_player doesn't sound like getting a player's choice. It sounds like a generalized function that asks the player something and gets a response (i.e., input()). On the other hand, if player is spelled out why do you abbreviate the opponent in comp_play?

Using get is not always a good thing. It's one of the times when a function or method name doesn't need a verb in it - because it is frequently implicit when you are doing is_... or has_... or get_... or set_.... I don't think you need to spell out get_player_choice and get_computer_choice, but certainly player_choice and computer_choice would be appropriate.

This same logic applies to results. Instead of calling a function named results, why not call play_once? Or one_game? It's obvious from the code in main what is going on, but the function name doesn't really match the nature of the "step" being executed.

Your code breakdown is uneven. Consider this code:

def main():
    wins = 0
    losses = 0
    draws = 0
    while True:
        os.system('cls' if os.name == 'nt' else 'clear')
        print(f"Wins: {wins}\nLosses: {losses}\nDraws: {draws}")
        wins, losses, draws = results(wins, losses, draws)
        if play_again() == '2':
            break

Let's break those lines down. The key point I want to make is to keep neighboring statements at a similar level of abstraction.

First, you initialize your variables:

wins = 0
losses = 0
draws = 0

Because you are not using a class, and are not using globals (which would be appropriate in this scenario, IMO), you are stuck with doing variable initialization here. I suggest that you make this consistent with how you update the variables after each game:

wins, losses, draws = starting_scores()

Now, starting_scores could just return 0,0,0 or it could load from a saved-game file. But it makes the initialization sufficiently abstract, and it also spells out what you are doing.

Next, you loop:

while True:
    ...
    if play_again() == '2':
        break

The while True ... break could be rewritten to use a boolean variable. That's not super-critical, since the value of that variable is determined at only a single location. I consider the break to be equivalent in this case.

However, the comparison == '2' is not acceptable! Why? Because that's a detail, and your function name play_again should take care of that detail for you! Don't ask a question and then interpret the answer. Make your question-asking code handle the interpretation for you. Obviously play_again is short for "do you want to play again?" and '2' is not a valid answer. True or False are valid answers, so the code should look like:

while True:
    ...
    if not play_again():
        break

Finally, the inside of your loop has the same problem:

os.system('cls' if os.name == 'nt' else 'clear')
print(f"Wins: {wins}\nLosses: {losses}\nDraws: {draws}")
wins, losses, draws = results(wins, losses, draws)

What are you doing here? Well, you are clearing the screen, showing a summary of the games played, and playing one more round of the game. So say that!

clear_screen()
show_statistics(wins, losses, draws)
wins, losses, draws = play_one_round(wins, losses, draws)

Use appropriate data structures.

Your main code passes three variables to your play-game code. That code then returns three data items in a tuple, which you unpack into three variables.

In fact, you never use one of those variables without also having the others at hand. This should tell you that you are dealing with one aggregate data item, instead of three independent pieces of data. If that's true, just treat the scores as a single item:

def main():
    scores = starting_scores()

    while True:
        clear_screen()
        show_statistics(scores)
        scores = rock_paper_scissors(scores)

        if not play_again():
            break

Similarly, you can treat the scores as an aggregate until you have to update them:

# NB: was `results(wins, losses, draws):`
def rock_paper_scissors(scores):
    player = player_choice()
    computer = computer_choice()
    outcome = game_outcome(player, computer)
    show_results(outcome, player, computer)
    new_scores = update_scores(scores, outcome)
    return new_scores

At this point, the "play one game" has also become a collection of abstract statements. But notice that I'm treating scores as an opaque blob that I don't need to deal with: I just pass it along to the lower levels, with another data item describing the update to make.
Be consistent!

I notice that when asking the player to choose rock, paper, or scissors, you allow them to type in an answer. But given a Yes/No question, you require a selection of either 1 or 2. That's consistently surprising. When I ran your code, I wanted to keep typing my answers. (I kept hitting 'y' to play again.)

I suggest you either present the Rock/Paper/Scissors options as a menu, or present the Yes/No options as a string input and look for 'y' or 'n'. Making the interface that much more consistent will be an improvement.
Use data, or code. Not both.

This one is a little subtle, but take a look:

if comp_choice == 'Paper':
    print(results_msg(comp_choice, player_choice, 'lost'))
    losses += 1
else:
    print(results_msg(player_choice, comp_choice, 'won'))
    wins += 1

What's significant here is that you have an if/then statement that decides whether you won or lost. And then you pass that into your results_msg function as a string parameter. The result of this is that you have a string parameter to be substituted that gives information you already knew: whether the player won or lost.

Let's look at results_msg:

def results_msg(x, y, result):
    message = f"{x} beats {y}. You {result}!"
    return message

You have to consider that Python f-strings are code. And they're a pretty compact form of code, compared to the horror of str.format(). So writing:

print(results_msg(player_choice, comp_choice, 'won'))

is not really an improvement on writing:

print(f"{player} beats {computer}. You won!")

It's not clearer. It's not shorter. It does avoid problems with changing the text of the message, although there isn't much text in the message to change.

I don't think you need to hoist the f-string up into the calling function. I do think you should not pass 'won' or 'lost' as a parameter: you already decided you won or lost. Call a separate function instead.

if ...
    win_message(player_choice, comp_choice)
else:
    lose_message(player_choice, comp_choice)

Note that this will appear to conflict with the code structure I showed above- because in that code structure, I chose to treat the result as data, not code. I'm not saying you have to use data, or that you have to use code. I'm saying that you should pick one and stick with it. If you determine your outcome as code, go ahead and hard-code the outcome. If you determine your outcome as data, go ahead and treat it as data.

And as a side note, strings with substitutions in them make it hard to do i18n. So there's nothing wrong with having an array of totally spelled out messages at the bottom. It also gives a bit more "flavor" if you customize the verbs:

"Rock breaks scissors. You won!",
"Scissors cuts paper. You won!",
"Paper covers rock. You won!",
...


Spelling "Celsius" (3 places)

printf("Type 2 if you would like to convert to Celcius\n");

Better to get return value of input functions (4 places).  Even in learner code, it saves time during debug

// scanf("%i", &w)
int ret = scanf("%i", &w);
assert(ret == 1);

Infinite loop should user enter non-numeric input as the offending input is not consumed.

while(w != 1 && w !=2) {
  fprintf(stderr, "You didn't input a valid number. Please Try Again\n");
  // scanf("%i", &w);
  ret = scanf("%i", &w);
  assert(ret == 1);
}

Style: Suggest .0.  Also since the input and output are float, code could use float constants.  In general, unless floating point math is intensive or has larges array of data, recommend using double as that is C's default FP type.

// f = c * (9./5.) + 32.;
f = c * (9.0/5.0) + 32.0;
f = c * (9.0f/5.0f) + 32.0f;

Functional simplification: Rather than enter a number to indicate the desired temperature scale, enter 'C' or 'F'.

char scale;
char scale_new;
ret = scanf("%f %c", &temperature, &scale);
assert(ret == 2);

switch (scale) {
  case 'C':
  case 'c':
    temperature_new = temperature*9/5 + 32;  // math is all FP
    scale_new = 'F';
    break;
  case 'F':
  case 'f':
    temperature_new = (temperature - 32)*5/9;  // math is all FP
    scale_new = 'C';
    break;
  default:
    // Handle bad scale
}
printf("... converts to %f %c\n", temperature_new, scale_new);


Style

Dead code should be removed. maxSize is never used.
Be consistent in your style. You should decide wether you use this. If a decision is made you should stick to it.

Here i would suggest refactor the constructor to

public MinHeap(int maxSize){
    heap = new int[maxSize+1];
    heap[0] = Integer.MIN_VALUE;
    size = 0;
}

Simplification

In the isLeaf() method you basically say if the condition is true, return true otherwise return false

private boolean isLeaf(int position){

    if(position > size/2){
        return true;
    }
    return false;
}

This can be simplified to return if the condition is true.

private boolean isLeaf(int position){
    return (position > size/2);
}