Compute the height of a tower made of buckets

You don't need to remember every single bucket you've seen.

Once a bucket is added to the top of the pile, any wider bucket that has its rim lower than the rim of the new bucket becomes irrelevant, as do all the narrower buckets it sits on.

So a better data structure would just store the altitudes of all rims currently in play; this can be initialised to (0,0).  When you add a bucket, find the widest rim not greater than the new bucket's width; we now set height[0] to that height and height[bucket_width] to height[0]+bucket_height.  Remove all narrower buckets, and all other buckets up to a the new height - they can no longer affect the result.

I've added a working demonstration, with tests, below.

Other items for review:

using namespace std;

Bringing all names in from a namespace is problematic; namespace std particularly so. See Why is “using namespace std” considered bad practice?.
Spellings: highestPoint, maximum.
Naming: temp and temporary - these are declared far from their use, so it's hard to appreciate the difference.
You can omit return 0; in main().

Working solution

#include <algorithm>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <sstream>

// Assume that unsigned int is large enough to represent the tallest
// tower
unsigned tower_height(std::istream& input)
{
    unsigned count;
    input >> count;
    if (!input) { std::cerr << "reading count" << std::endl; return 0; }

    // start with a point at 0,0 on which everything balances
    std::map<unsigned,unsigned> m{ {0,0} }; // radius -> altitude

    while (count-->0) {
        unsigned radius, height;
        input >> radius >> height;
        if (!input) { std::cerr << "reading size" << std::endl; return 0; }
        // find the widest bucket this sits on top of
        auto smaller = std::prev(m.upper_bound(radius));
        // floor height is now smaller's height
        m[0] = smaller->second;
        // floor extends out over smaller
        if (smaller != m.begin()) {
            m.erase(std::next(m.begin()), std::next(smaller));
        }
        // put this bucket in place (it will always be second)
        auto current = m.insert({radius, m[0]+height}).first;
        // find the first wider bucket that's taller
        auto height_test = [current](auto const& e){ return e.second > current->second; };
        auto wider = std::find_if(current, m.end(), height_test);
        // and remove values up to it
        m.erase(std::next(current), wider);
    }

    return m.rbegin()->second;
}

static bool test(unsigned expected, const std::string& input)
{
    std::istringstream is{input};
    auto actual = tower_height(is);
    if (actual != expected) {
        std::cerr << "Got " << actual
                  << " instead of " << expected
                  << " for input " << input
                  << std::endl;
        return false;
    }
    return true;
}

int main()
{
    int errors = 0;
    errors += !test(0, "0");
    errors += !test(10, "1  20 10");
    errors += !test(20, "2  20 10  20 10");
    errors += !test(15, "2  20 10  10 15");
    errors += !test(25, "2  10 15  20 10");
    errors += !test(25, "3  10 15  20 10   5 10");
    errors += !test(20, "3  20 10   5  5  10 15");
    return errors;
}

A note on complexity

At first glance, we might think that the code here is O(n²), because we used std::find_if() each time we add a bucket.  But find_if() returns at the first match, and we then remove all the elements we've seen, thus reducing work for subsequent iterations.  Therefore on average, we scale as O(n), and that's demonstrable:

std::mt19937 gen{std::random_device()()};
std::uniform_int_distribution dist{1, 1000};
for (unsigned n: {10000, 100000, 1000000}) {
    std::stringstream s;
    s << n;
    for (unsigned i = 0;  i < n;  ++i) {
        s << ' ' << dist(gen) << ' ' << dist(gen);
    }
    auto start_time = std::chrono::high_resolution_clock::now();
    auto height = tower_height(s);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    std::clog << "Measured " << n << "-bucket tower as "
              << height << " in " << millis.count() << "ms"
              << std::endl;
}

Measured 10000-bucket tower as 2897237 in 1ms
Measured 100000-bucket tower as 28587991 in 13ms
Measured 1000000-bucket tower as 285125976 in 136ms

The very worst case is where each bucket is narrower and shorter than the previous, meaning that the map continuously grows in size.  This introduces an O(log n) term, since that's how map operations scale.  So we have worst-case performance that scales as O(n log n):

for (unsigned n: {10000, 100000, 1000000}) {
    std::stringstream s;
    s << n;
    for (unsigned i = n;  i > 0;  --i) {
        s << ' ' << i << ' ' << i;
    }
    auto start_time = std::chrono::high_resolution_clock::now();
    auto height = tower_height(s);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    std::clog << "Measured " << n << "-bucket tower as "
              << height << " in " << millis.count() << "ms"
              << std::endl;
}

Measured 10000-bucket tower as 10000 in 2ms
Measured 100000-bucket tower as 100000 in 36ms
Measured 1000000-bucket tower as 1000000 in 539ms


What you are looking for is add_mutually_exclusive_group. It allows you to define options that are mutually exclusive as well as specifying if selecting one of these options is a required action or not. And looking at your else: block, yours is; meaning if we call the program without arguments, it should fail with an error along the following:

usage: [-h] (-t TEXT | -f FILE)
program_name.py: error: one of the arguments -t/--text -f/--file is required

You are also handling files in your input and should avoid doing so manually. argparse provides a FileType object meant to be used as the type keyword of add_argument to handle files for you. It will fail with a proper error message if the file cannot be opened with the proper mode and will return the opened file object in the resulting parsed arguments.

Proposed improvements:

#!/usr/bin/env python

import argparse

def parse_command_line():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-t', '--text', help='Text')
    group.add_argument('-f', '--file', type=argparse.FileType('r'), help='File containing the text')
    return parser

if __name__ == '__main__':
    args = parse_command_line().parse_args()

    if args.text is not None:
        text = args.text
    elif args.file is not None:
        with args.file as f:
            text = f.read()

    # Program continues ...

Also note the use of with to properly close the provided file.


There are a number of things that may help you improve your program.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Use the required #includes

The code uses a number of #includes that are not listed.  It was not difficult to infer, but it helps reviewers if the code is complete.  After a bit of looking, it seems that this is what's needed:

#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <boost/algorithm/string.hpp>

Prefer modern initializers for constructors

The constructor use the more modern initializer style rather than the old style you're currently using.  Instead of this:

XYZCoordinate(int X, int Y, float Z){
x = X;
y = Y;
z = Z;
}

I would write this:

XYZCoordinate(int X, int Y, float Z) : x{X}, y{Y}, z{Z} {}

However, in this case, for such a simple class, in real code I wouldn't write a constructor at all and would simply delete the line.  The class can still be initialized like this: XYZCoordinate xyz{3, 5, -23.22}; via aggregate initialization.

Use better variable names

The variable names xmax, xmin, etc. are good, but the name file is not.  The first names explain something about what the variable means within the context of the code, but the latter is only confusing. A better name might be coordinates.  Similarly, Loadfileoutput is another poor name -- I'd suggest Coordinates for the name of that class.

Use C++ idiom

The code currently contains this:

vector<XYZCoordinate> file = vector<XYZCoordinate>();

That's really not necessary.  Just write this instead:

vector<XYZCoordinate> coordinates{};

Prefer a struct to a class for objects with no invariants

C++ has two primary means to encapsulate some behavior and data: struct and class.  The only difference is that a struct has its members public by default, while the class members are private by default.  If there is no invariant, (a thing that must always be true for the class to be coherent), then it often makes sense to use a struct instead.  In this case the XYZCoordinate class has no invariants and is probably better suited as a struct.

Write a custom extractor

Here's the code I'd prefer to write to read in and create the desired object:

std::ifstream in(filename);
Coordinates c;
in >> c;

This can be done by writing an extractor for the data.  In this case, I'd write two extractors.  One for the Coordinates class and one for the XYZCoordinate class.  Here's one way to write one for the XYZCoordinate class.  Here's the complete definition for that class, which I have converted to a struct:

struct XYZCoordinate{
    int x;
    int y;
    float z;
    friend std::istream& operator>>(std::istream& in, XYZCoordinate &xyz) {
        float a, b;
        in >> a >> b >> xyz.z;
        xyz.x = std::rint(a);
        xyz.y = std::rint(b);
        return in;
    }
};

Now we can write an extractor for the Coordinates class.  Here's that complete class:

class Coordinates
{
    int xmin;
    int xmax;
    int ymin;
    int ymax;
    std::vector<XYZCoordinate> values;

public:
    friend std::ostream& operator<<(std::ostream& out, const Coordinates &c) {
        return out << "[ " << c.xmin << ", " << c.xmax << "], [ "
            << c.ymin << ", " << c.ymax << "], with " << c.values.size() << " points\n";
    }
    friend std::istream& operator>>(std::istream& in, Coordinates &c) {
        // skip comment lines
        while (in.peek() == '#') {
            in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        XYZCoordinate xyz;
        while (in >> xyz) {
            c.values.push_back(xyz);
            c.xmin = std::min<int>(c.xmin, xyz.x);
            c.xmax = std::max<int>(c.xmax, xyz.x);
            c.ymin = std::min<int>(c.xmin, xyz.y);
            c.ymax = std::max<int>(c.xmax, xyz.y);
        }
        return in;
    }
};

Note that the values of xmin, xmax, etc. are invariants for this class, so we leave it as a class with only private data members.  If you need to access the items in the vector, you can add custom functions to handle that.

Provide a test driver

This is more about getting good reviews than the code itself, but it's often very useful if you provide some simple main that exercises the code.  This helps reviewers (and yourself!) understand how it's to be used in context.  In this case, I wrote this:

#include <vector>
#include <iostream>
#include <fstream>
#include <locale>
#include <limits>
#include <algorithm>

// all of the class code above goes here

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: xyz infile.txt\n";
        return 1;
    }
    std::ifstream in(argv[1]);
    in.imbue(std::locale(std::locale(), new csv_reader()));
    Coordinates c;
    in >> c;
    std::cout << c;
}

The call to imbue uses a locale that treats commas as whitespace.  That code is in this excellent answer.  Now you don't have to explicitly check for commas or spaces and don't need boost.  Everything here is standard C++.

Results

I wrote a program to create a set of 20 millon sets of random coordinates.  Using that input, your original program took 41.9 seconds on my machine, while the one presented above took 14.8 seconds.


Flatten an array of arbitrarily nested arrays of integers

The check for arr.length > 0 is not needed: forEach() can be called
on an empty array (and does nothing in that case).

The check if (arr) protects against a call with an undefined argument,
but not against a call with a non-array. As an example, flatten(123)
would cause a JavaScript error. So you have to decide:

If the argument to flatten() is known to be an array then the
outer if statement is not needed at all.
If flatten() can be called with any argument than you need to check
for an array before calling forEach().

See also Flatten an array on how reduce() can be used instead of a loop.


First, a couple of tips:

Using an int[] to represent the result is a poor choice. It would be better to create a class for this, for example called MixedNumber. Then, instead of accessing the elements by indexes, you can access them by field name. It could also have an appropriate toString method to print itself
The handling of negative numbers is very poor. You could determine the sign of the number in one place early on, use it to multiply the integral part and that's it. That would get rid of many confusing redundant logic. The current code also has a bug related to it: for the input (3, -2) it gives back -1 1/-2 instead of -1 1/2
An elegant implementation of the gcd algorithm is this recursive function: return b == 0 ? a : gcd(b, a % b);
The printing of the number can be cleaner and simpler using String.format

I recommend to rewrite the function in terms of this class:

class MixedNumber {
    private final int integral;
    private final int numerator;
    private final int denominator;

    private MixedNumber(int integral, int numerator, int denominator) {
        this.integral = integral;
        this.numerator = numerator;
        this.denominator = denominator;
    }

    private static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static MixedNumber fromFraction(int numerator, int denominator) {
        // TODO: simplified main implementation comes here
    }

    @Override
    public String toString() {
        if (numerator == 0) {
            return "" + integral;
        } else if (integral == 0) {
            return String.format("%d/%d", numerator, denominator);
        } else {
            return String.format("%d %d/%d", integral, numerator, denominator);
        }
    }
}

Rather than printing the output, use unit tests to verify.
After you finished the implementation above,
with the bug that I mentioned fixed,
these unit tests should pass:

@Test
public void testZeroNumerator() {
    assertEquals("0", MixedNumber.fromFraction(0, -2).toString());
}

@Test
public void test_minus3_over_2() {
    assertEquals("-1 1/2", MixedNumber.fromFraction(-3, 2).toString());
}

@Test
public void test_3_over_minus2() {
    assertEquals("-1 1/2", MixedNumber.fromFraction(3, -2).toString());
}

@Test
public void test_minus3_over_minus2() {
    assertEquals("1 1/2", MixedNumber.fromFraction(-3, -2).toString());
}

@Test
public void test_123_over_82() {
    assertEquals("1 1/2", MixedNumber.fromFraction(123, 82).toString());
}

@Test
public void test_82_over_123() {
    assertEquals("2/3", MixedNumber.fromFraction(82, 123).toString());
}

Whatever IDE you use, there is certainly an easy way to add a JUnit4 test class and run it. Give it a try!


Iterate through a 2D array. Kotlin extension method

s/forEach2d/forEach2D/

Meaning: "2d" can mean two-dimensional but it can also mean "second" while "2D" is unequivocally an abbreviation for two-dimensional.
Consistency: In java.awt.geom, there is a Point2D and no Point2d.
Convention:

Naming Style - Coding Conventions - Kotlin Programming Language
Code Conventions for the Java Programming Language: 9. Naming Conventions

Make it an inline function for performance reasons.
Consider renaming outer and inner. At first glance a reader might think that outer and inner refer to the outer array and an inner array but this isn't the case as outer is in fact an inner array and inner is an element in an inner array. e.g. s/outer/array/g/ and s/inner/element/g.
Optionally omit the braces on the 'for' loops. I don't feel strongly about this one either way. I personally keep them but for something as simple as this where there really isn't any logic it makes me wonder why explode it into so many lines. However, I've worked on teams where it is our convention to always use braces for if/for/etc. constructs so be consistent above being brief.
Document your Kotlin Code. It may seem like a small thing but it can also be surprisingly amazing how much more real/professional/reusable/etc. your code is once you and others can discover methods and documentation is right there explaining exactly what it does and doesn't do.

Example:

/**
 * Performs the given [action] on each element in each array.
 */
inline fun <T> Array<Array<T>>.forEach2D(action: (T) -> Unit): Unit {
    for (array in this) for (element in array) action(element)
}


Project Euler 11: Largest product in a grid, Python3

One of the potential improvements would be to extract the logic of generating the 4 numbers in each of the directions (let's even generalize it for k numbers). What if we would create a generator that would do this for an arbitrary square matrix and k input numbers:

def generate_adjacent_items(grid, k):
    """
    For a square grid, generates lists of all possible k numbers in every direction
    (up, down, left, right and diagonally).
    """
    size = len(grid)
    for row in range(size):
        for col in range(size):
            # left -> right
            if row + k - 1 < size:
                yield [grid[row + index][col] for index in range(k)]

            # top -> bottom
            if col + k - 1 < size:
                yield [grid[row][col + index] for index in range(k)]

            # diagonal: top-left -> bottom-right
            if row + k - 1 < size and col + k - 1 < size:
                yield [grid[row + index][col + index] for index in range(k)]

            # diagonal: bottom - left -> top - right
            if row - k + 1 >= 0 and col + k - 1 < size:
                yield [grid[row - index][col + index] for index in range(k)]

(please recheck for off-by-ones)

Then, you can iterate over the generator and get your maximum number, e.g.:

from operator import mul
from functools import reduce

K = 4

# list_ints and generate_adjacent_items function definitions here

if __name__ == '__main__':
    sub_lists = generate_adjacent_items(list_ints(), K)

    max_sublist = max(sub_lists, key=lambda x: reduce(mul, x))
    print(max_sublist, reduce(mul, max_sublist))

Note that I'm using functools.reduce(), operator.mul and the built-in max() to determine the maximum of the multiplications, but you can do it "manually" the way you were doing it in your presented solution.

For the provided sample input, it prints:

[87, 97, 94, 89] 70600674


Laravel controller to update appointment requests

public function update(UpdateAppointmentRequest $request)
{
    try {
        $data = array_filter($request->only(['user_id','status','note']));
        $appointment = $this->appointment->findOrFail($request->input('id'));
        $result = $appointment->update($data);
        return response()->json(['created' => $result]);
    } catch(\PDOException $e) {
        return $this->internalIssues($e->getMessage());
    }
}

What is wrong with this simple solution? If request does not have a field, say user_id, the only would not return that. And if there is an error while updating, the catch would catch that and return error. Why all those manual checking?


Program to check an item's price against available credit

Since you are a beginner, I will try to go easy on you.  That said, this looks very beginner-ish.

As noted in the comments above, you inadvertently put a line break which causes a compiler error.  There are many here you would CLOSE the question on that alone.

Beginner's frequently use double for binary floating point values.  However, anytime you are working with money or currency, then you should use Decimal.  Decimal is floating point as well but it's Base 10 rather than Base 2.

The static import of System.Console may be allowed but in general is frowned upon.  My eyes would rather see Console.WriteLine instead of WriteLine due to over dozen years of writing .NET apps.

Naming is important.  CreditCheck is a bad name.  It should be creditLimit or currentBalance if not simply balance.  But "Check" is an action verb and it would be a method that would perform that checking action, not a variable.  Note too that for local variable naming I am using camelCase.

Organization is less than desired.  Beginners will frequently put everything in Main method.  How about you create a separate method and pass the credit limit as an argument to it?  Or even a method that accepts the credit limit and item price?

You get to decide whether such a method should return a bool to denote you have sufficient funds, or perhaps return the remaining funds after the price.  If it returned remaining funds, you now have extra information, such as negative value denotes insufficient funds (that it the price check failed).

I don't think you need a special check for price == CreditCheck.  Nice of you to throw in something extra, but why not tell them "Approved.  Remaining funds = ?".

You use decent indentation and nice that braces are wrapped around one line of code.

Why fix the credit to 8000?  Again, pass it as an argument.  If you do that, you should see why it's wrong that you hardcode it with:

WriteLine("Your credit limit is $8,000.00.\n");

I get that you want a blank line to appear after that.  For some people "\n" is perfectly acceptable.  Others would recommend using Environment.NewLine.  Putting many suggestions together, and using String Interpolation, this would become:

Console.WriteLine($"Your credit limit is ${creditLimit.ToString("N2")}.{Environment.NewLine}");

Or you could issue a simple Console.WriteLine(); to avoid the whole "\n" versus NewLine debate.


Honestly, this is not a very good problem to do recursively, just pick another problem. Here's a better one: take in an integer, and print the sum of the digits.
Some general feedback:

ReverseString returns something, but you ignore its return value
You make x, but it's a shallow copy of s -- modifying x and s do the same thing, and returning them would do the same thing. Just don't declare 'x' at all.
See how short you can make this. It's not good general advice, but it can be good advice when learning recursion.

One last tip when learning recursion: next time, try to do it without modifying a single variable. Just use expressions and return values. Again, it's not always how you should write real code, but it will help you learn faster.


PHP, Is creating a class for templates to much?

This definitely wouldn't be going too far.  Any business logic that your program has to capture is best kept in a class.  Preferably, the class would have automated tests running against it as well to ensure that it is functioning properly.

In your example, the class isn't doing anything drastically different than what the preg_replace method does itself.  Rather than simply duplicating the built-in functionality of this method, I would suggest trying to think of what business goal you are trying to achieve and create methods that more closely mirror it.

class template {
    private $_templateText;

    // Initialize the template with this method, as an instance of
    // template doesn't make much sense without some text.
    public static function factory($templateText) {
        $template = new template();
        $template->_templateText = $templateText;

        return $template;
    }

    // This can be called as many times as needed.  Alternatively, you could add a
    // method that would take two arrays, with the idea that the two array's keys
    // are coupled and paired off.  If you choose to couple the two arrays, I would
    // recommend avoiding passing them in to two different methods.  Make the coupling
    // as obvious as possible by passing them in to the same method.
    public function replacePlaceholderTextWithString($placeholderText, $string) {
        // ...
    }

    // This could have some additional error handling code that would verify that
    // all placeholder text has been replaced and throw an exception if it hasn't.
    // Otherwise, it would simply format the template text based on what had
    // previously been passed in to replacePlaceholderTextWithString(...)
    public function getFormattedTemplateText() {
        // ...
    }
}

Lastly, I would add that a big advantage to using your own class for this is that you are able to change how you would like to implement this functionality in the future.  You could change from using preg_replace to using the MessageFormatter, or any number of other solutions.  It adds a great deal of flexibility and provides you the opportunity to put automated tests around it that can quickly notify you when it no longer works as expected.


Variable naming is very important for readability.
Now, as some background, when I first saw your question, it had the title:

What are your opinions on my javascript function?

Titles like that are an poor choice for code review, and as a moderator, we actively change titles like that to reflect what the code does, and not what the question asker sees as being the problems in the code.
Unfortunately, when I read your code, to try to see what it does, all I could think of was goofers... it took me a few moments to understand that the code was meant to be "go offers".
camelCase to the rescue...

gooffers should be goOffers
scope.returnoffers should be scope.returnOffers

Apart from those two, all your other variables are correcly cased. The following are good:

tarifSecondeFlex
tarifPremiere
scope.selectedGo
goPrice
etc.

Note, I believe you have mixed some natural language variable names in there. Is that French? In general, when programming, you should pick a language, and stick to it. You have a mix. Since you have goPrice and selectedGo which appear to be English, I would expect tarifPremiere to be primaryPrice, etc.
Language consistency goes a long way toward readability.
DRY code
Repetitive code is often an indication that function-extraction would be useful.
Consider a function like:
function selectedTarif(component, selection) {
    if (component == null || typeof component == 'undefined' || component.id !== selection) {
        return null;
    }
    return component.tarif;
}

Then, your code can become a cascading 'falsy' test:
var updatedPrice = selectedTarif(scope.goOffers[go].tarifPremiere, scope.selectedGo)
            || selectedTarif(scope.goOffers[go].tarifSecondeFlex, scope.selectedGo)
            || selectedTarif(scope.goOffers[go].tarifSecondeNoFlex, scope.selectedGo);
if (updatedPrice) {
    goPrice = updatedPrice;
}

var updatedReturn = selectedTarif(scope.returnOffers[go].tarifPremiere, scope.selectedReturn)
            || selectedTarif(scope.returnOffers[go].tarifSecondeFlex, scope.selectedReturn)
            || selectedTarif(scope.returnOffers[go].tarifSecondeNoFlex, scope.selectedReturn);
if (updatedReturn) {
    returnPrice = updatedReturn;
}


The iterative approach is likely the most efficient approach. It is sparing on memory allocation, it does not require stack manipulation (and frames), and it won't cause stack overflows for long lists.

The recursive options are really not worth considering for this problem.

Your iterative implementation is not as 'tight' as I would hope, though. Consider your code:

List* zipLists_iter(List* a, List* b) {
    List* root = a;
    while ( a && b ) {
        List* oldNextA = a->next;
        List* oldNextB = b->next;
        a->next = b;
        b->next = oldNextA;
        a = oldNextA;
        b = oldNextB;
    }
    return root;
}

Your code saves away the 'second' items. It cross links the current items, and then it advances both lists.

I would prefer a solution that does one item at a time (instead of 2), and then swaps the lists so that the second list becomes the first, and vice versa.

save away item 2 from listA
make item 1 on listB the new item 2 on listA
make the saved-away item 2 (now orphaned) the swapped list B
make what was the listB item 1 the new listA.

In code, it would look like:

List* zipLists_iter(List* a, List* b) {
    if (!a) {
        return b;
    }
    List* root = a;
    while ( b ) {
        List* tmp = a->next;
        a->next = b;
        a = b;
        b = tmp;
    }
    return root;
}

Note that I put a check in there for an empty List A. This allows it to work on unevenly sized lists, including an empty list A.

By thinking about the problem a little differently you can:

remove a temporary variable.
remove two assignments
remove a null-check (a is never null)
but, you loop more often.

The remainder of your code (excluding the recursion methods which I am not going to review) is really good in terms of neatness, and functionality. It was easy to follow, and it was great that I could compile and run your code without any issues, even when using -Wall, and compiling as C99 standard.

Nicely done.


Since your overall number of indices just fits into 31 bits, you could try a std::map:

uint32_t keyFrom5DIndex(uint32_t a, uint32_t b,
                        uint32_t x, uint32_t y, uint32_t z)
{
    return z+24000*(x+30*(y+30*(b+10*a)));
}

std::map<uint32_t, float> votes;
// Compute indices
votes[keyFrom5DIndex(a,b,z,y,z)] += this_vote;


Use indexing in HTML name attributes

        Dată / Interval orar
        Denumire
        Moderatori
        Detalii

        <input name="DataInterval[0]" type="text" id="DataInterval1">
        <input name="Denumire[0]" type="text" id="Denumire1">
        <input name="Moderatori[0]" type="text" id="Moderatori1">
        <input name="Detalii[0]" type="text" id="Detalii1">

    ...

        <input name="DataInterval[n]" type="text" id="DataIntervaln">
        <input name="Denumire[n]" type="text" id="Denumiren">
        <input name="Moderatori[n]" type="text" id="Moderatorin">
        <input name="Detalii[n]" type="text" id="Detaliin">

Use the indexing on the server side

<?php
$data = array();
foreach ($_POST["DataInterval"] as $index => $value) {
    $data[] = array(
        "DataInterval" => $_POST["DataInterval"][$index],
        "Denumire" => $_POST["Denumire"][$index],
        "Moderatori" => $_POST["Moderatori"][$index],
        "Detalii" => $_POST["Detalii"][$index],
    );
}

After this you only have to iterate throught the $data array and execute paramtrized INSERT SQL commands.

do not use old mysql lib
learn about PDO and prepared statements


Resistance is futile, Resistors have been dispatched to model your Resistance

Guards

Using so many if then and else is really weird in Haskell, I suggest using the guards:

resistor_mania resistor target
    | resistor == target = (show resistor)
    | resistor < target = (show resistor) ++ "+" ++ (resistor_mania resistor (target - resistor))
    | otherwise = (show resistor) ++ "||(" ++ (resistor_mania resistor (p_resistor resistor target)) ++ ")"

This is the standard way of listing mutually exclusive conditions in a function definition.

Semicolons

Haskell uses a two-dimensional syntax, semicolons are not needed and should be omitted as they convey no additional information, just noise.

Prefer mainstream function definitions

p_resistor = (\existing target -> (1 / ((1 / target) - (1 / existing))))

Becomes:

p_resistor existing target = (1 / ((1 / target) - (1 / existing))))

That looks maybe less cool, but surely faster to understand.

Types

  the type-signature of resistor_mania makes me uneasy :/

Haskell is type-centric, so it is good that you are worrying about types.

I deleted your types and asked the compiler what types it would like for your functions.

*Main> :t p_resistor
p_resistor :: Double -> Double -> Double
*Main> :t resistor_mania
resistor_mania :: Double -> Double -> String

I think these suggested types are simpler, and I would use them instead of your bulky type declarations.

Non-closing parenthesis

$ is like a parenthesis but you do not need to close it:

putStrLn $ show $ resistor_mania (read res_input) (read target_value)

This is somewhat subjective though...


Your approach

As pointed out by the other answers, you are practically hard-coding whitespaces in your arguments, which can get non-standard easily, even in your example. Otherwise, the use of StringBuilder is sound, although it wouldn't deal nicely with a single null value - the for-each loop will fail as it implicitly tries to get an Iterator for it.

Java 8

An alternative is to rely on the stream-based processing that Java 8 offers:

private static String format(Object... values) {
    if (values == null) {
        return "";
    }
    return Arrays.stream(values)
                    .map(Objects::toString)
                    .collect(Collectors.joining(" "));
}

Construct a Stream<Object> from values using Arrays.stream(T...).
map() each value using Objects.toString(Object) as a method reference.
collect() the stream into a String by joining(" ") them together.


Reduce repetition when sharing data across an application

I would not get all worked up about having to type a few extra letters when referencing a variable.  I could get worked up over possibly doubling the storage space required for your data depending on it's size. Let's walk though what PHP is doing behind the scenes here to understand:

// PHP references $this->data to $data by reference
$data = $this->data;

// since you modify $data here, PHP now copies the entirety of $this->data
// to $data and breaks reference
// you are now taking up double (plus some) storage for your data
$data['page_title'] = 'example';

As opposed to directly modifying $this->data before making assignment to $data like shown below , which would not double memory utilization:

$this->data['page_title'] = 'example';
$data = $this->data;

Just remember that as soon as you modify an array assigned in this manner, you remove the ability for PHP to perform it's behind the scenes memory optimization. But really you should not be relying on this anyway, as IMO it is bad coding form to be relying on some hidden, undocumented and possibly subject to change optimization for your code to be working in the best manner.

Alternately, instead of associative array for data, why not use an object (even stdClass), then you are always working with reference to the object (unless you specifically clone it)? For example:

// assuming $this->data holds object
// $data is just reference to $this->data here
$data = $this->data;

// here modifying $data would modify both $data and $this->data
$data->page_title = 'example';

This also gives you the possible side benefit of being able to type hint against an object in method signatures as you are passing this data around or injecting it as dependency.


Determine whether a number and its square are both the sum of two squares

You can speed it up by saving the squares in a set. If you wrote a function to do this, you can give it a mutable default argument for it to save all the squares instead of having to calculate them repeatedly.
# dict used because there’s no insertion ordered set
def sum_squares(n, saved_squares=dict()):
    # check for sum while saving squares for future calls
    check_end = n
    if int(n**(1/2)) > len(saved_squares):
        check_end = (len(saved_squares) + 1)**2
        found_while_saving = False
        for num_to_save in range(len(saved_squares) + 1, int(n**(1/2) + 1)):
            square = num_to_save**2
            saved_squares[square] = None
            if n - square in saved_squares:
                found_while_saving = True
        if found_while_saving == True:
            return True
    # check for sum in set of already calculated squares
    for square in saved_squares:
        if n - square in saved_squares:
            return True
        # insertion order needed so early return won’t happen
        if square >= check_end:
            return False

With the numbers 5881, 2048, 2670, and 3482, it will only have to calculate any squares for the first call with the number 5881. On the other three calls it can skip to checking the set of all the already calculated squares. But no matter what order of numbers it’s called with, it will only have to calculate the square of any number once.
This is how I tested it on repl.it:
nums_to_check = (2048, 2670, 3482, 5881)
for n in nums_to_check:
    print(sum_squares(n) and sum_squares(n**2))

It completed in under a second, so hopefully it’s fast enough for the site you’re using.


In general reflection is slow (relative), makes code harder to understand and near impossible to debug if things go wrong.

So if you already know the exact class it's far better to let the compiler check against typo's for you at compile time.

A second issue is that the way it's written now, you just shifted the problem of "rewriting the factory class" to "rewriting the Sorts class". You can't add any other public constant to that class based on an XML file.

This isn't entirely clear from the limited problem statement you've given, but perhaps you've misunderstood what kind of factory they expect.

Another interpretation of the factory method pattern expects you to provide a factory interface. This interface defines one or more methods that create some Sorter. That way you can "plug" in any other factory to use a different Sorter. (Which, compared to just plugging in a different Sorter directly, is only useful if certain Sorters require something extra to create them. For example an extra input parameter.)

Note that this is still usually defined at compile time.


I don't know jinja but I can give a few generic python pointers:

Generally, its considered best to put all imports at the top of the file not scattered throughout
Rather then importing a bunch of stuff to use once, use self.gettext = translation.gettext etc
Why empty lines after class, but nowhere else? I'd but a blank line before the start of a class and not inside.


Don't throw raw Exceptions, use always a subclass (as explained by MrLore). If you are throwing raw exceptions you also have to catch them, which might mask other exception or runtime exceptions. You would add a instanceof to any of your catch blocks.


Getting the frequency of letters in each position

That's a crazy amount of code for such a simple task.  There's no need to generate any intermediate files.  There's no need to create nine separate variables for the nine columns.

To process an input file (whether from sys.stdin or as a named argument on the command line), use fileinput.  That way, you don't have to hard-code 'infile.txt'.  Then, simply ignore the lines that start with > and strip off the newlines.

To work on columns rather than rows, use zip().

Suggested solution

These seven lines could replace your entire code.

import fileinput
from collections import Counter

def nucleotide_lines(f):
    for line in f:
        if not line.startswith('>'):
            yield line.rstrip()

print([Counter(col) for col in zip(*nucleotide_lines(fileinput.input()))])


I do not recommend this approach. There are entirely too many subjects and they are completely unnecessary. Too much boilerplate.

I recommend a more functional approach:

The view controller would contain something like this:

// assign viewModel before presenting.
var viewModel: (LoginInputs) -> LoginOutputs = { _ in fatalError("assign before view is loaded.") }

// called from viewDidLoad()
private func configureBinding() {

    let inputs = LoginInputs(
        username: loginLandingView.usernameTextField.rx.text.orEmpty.asObservable(),
        loginTrigger: loginLandingView.nextButton.rx.tap.asObservable()
    )

    let outputs = viewModel(inputs)

    outputs.navigateTrigger
        .subscribe(onNext: { [unowned self] in
            self.navigate()
        })
        .disposed(by: disposeBag)

    outputs.invalid
        .subscribe(onNext: { [unowned self] message in
            self.showAlert(with: message)
        })
        .disposed(by: disposeBag)
}

And the view model would look like:

struct LoginInputs {
    let username: Observable<String>
    let loginTrigger: Observable<Void>
}

struct LoginOutputs {
    let navigateTrigger: Observable<Void>
    let invalid: Observable<String>
}

func loginViewModel(minUsernameLength: Int) -> (_ inputs: LoginInputs) -> LoginOutputs {
    return { inputs in
        let usernameEntered = inputs.loginTrigger
            .withLatestFrom(inputs.username)

        let navigateTrigger = usernameEntered
            .filter { minUsernameLength <= $0.count }
            .map { _ in }
        let usernameTooShort = usernameEntered
            .filter { 1 <= $0.count && $0.count < minUsernameLength }
            .map { _ in "Please enter a valid username" }
        let usernameEmpty = usernameEntered
            .filter { $0.isEmpty }
            .map { _ in "Please enter a username" }

        return LoginOutputs(
            navigateTrigger: navigateTrigger,
            invalid: Observable.merge(usernameTooShort, usernameEmpty)
        )
    }
}

The code that presents the view controller would look something like:

let controller = LoginViewController()
controller.viewModel = loginViewModel(minUsernameLength: 8) // or whatever the minimum is.
// show the view controller

The above will maximize the testability of your code. You can test the view model by simply calling the function and pushing data into it. You can test the view controller by assigning a viewModel function that pushes test data.

The above will also establish a strong separation between your logic (in the view model) and your effects (in the view controller.)


DSSudokuSolver - A JavaScript Sudoku solving algorithm

It's not a huge improvement, just taking a stab at a few slight tweaks:

var sudoku = {
    CleanElements:function(comp_ary, Qsudoku){
        var i_factor,
            j_factor,
            i_min,
            i_max,
            i_index,
            j_index,
            index;

        for(var i=9; i--;){
            i_factor = (3*Math.floor(i/3));
            i_min = 6 - i_factor;
            i_max = 8 - i_factor;

            for(var j=9; j--;){
                j_factor = (3*Math.floor(j/3));
                j_min = 6 - j_factor;
                j_max = 8 - j_factor;

                for(var k=9; k--;){
                    i_index = comp_ary[i][k].indexOf(Qsudoku[i][j]);
                    j_index = comp_ary[k][j].indexOf(Qsudoku[i][j]);

                    if(i_index !== -1){
                        comp_ary[i][k].splice(i_index,1);
                    }

                    if(j_index !== -1){
                        comp_ary[k][j].splice(j_index,1);
                    }
                }

                for(var i_box=i_max; i_box>=i_min; i_box--){
                    for(var j_box=j_max; j_box>=j_min; j_box--){
                        index = comp_ary[i_box][j_box].indexOf(Qsudoku[i][j]);
                        if(index !== -1){
                            comp_ary[i_box][j_box].splice(index, 1);
                        }
                    }
                }
            }
        }
        return comp_ary;
    },
    FindElements:function(comp_ary, Qsudoku){
        for(var i=9; i--;){
            for(var j=9; j--;){
                if(comp_ary[i][j].length === 1){
                    // in case you were specifically checking that it was an empty string and not a null / undefined / etc, change to Qsudoku[i][j] === ''
                    if (Qsudoku[i][j].length === 0){
                        Qsudoku[i][j] = comp_ary[i][j][0];
                        comp_ary[i][j] = [];
                    }
                }
            }
        }
        return Qsudoku;
    },
    IsThereNullElement:function(Qsudoku){
        for(var i=9; i--;){
            for(var j=9; j--;){
                // same here, change to === '' if specifically needed
                if(Qsudoku[i][j].length === 0){
                    return false;
                }
            }
        }
        return true;
    },
    InitEmptyArray:function(){
        var empty_ary = Array();

        for(var i=9; i--;){
            empty_ary[i] = Array();

            for(var j=9; j--;){
                empty_ary[i][j] = Array();

                for(var k=9; k--;){
                    empty_ary[i][j][k] = (k+1)+'';
                }
            }
        }
        return empty_ary;
    },
    DSSolve:function(Qsudoku){
        var self = this,
            comp_ary = self.InitEmptyArray(),
            Qsudoku;

        this.comp_ary_old = comp_ary;

        for(var i=5000; i--;){
            comp_ary = self.CleanElements(comp_ary, Qsudoku);
            // console.log(comp_ary);

            if(sudoku.comp_ary_old === comp_ary){
                // implement this.
            } else {
                sudoku.comp_ary_old = comp_ary;
            }

            Qsudoku = self.FindElements(comp_ary, Qsudoku);
            // console.log(Qsudoku);

            if(self.IsThereNullElement(Qsudoku)){
                return Qsudoku;
            }

            if(i === 0){
                return null;
            }
        }
    }
};

And then you call it with this (Qsudoku being the value you want to pass in):

sudoku.DSSolve(Qsudoku);

Quick breakdown of changes:

changed all for loops and final while loop to decrement (faster in all browsers)
changed == '' to .length === 0 (faster in all browsers)
applied strict comparison === rather than implicit == (faster on certain browsers)
changed multiple if/else if/else statements to applying Math.floor to compute reduction factor
encapsulated all functions within object to allow for use of object comp_ary_old (instead of using window)
added explicit var statement for variable declaration (prevents bubbling up to window)
moved variables to top of respective function and assigned value at point where the fewest loops occur while retaining value integrity
changed the .toString() function to the +'' trick (its a miniscule improvement, more of a "squeeze every byte" thing, so if you would rather stick with code clarity switch it back to .toString())

I haven't tested this at all, so no benchmarks to show if it actually improves performance, but theoretically it should maintain your code operations while executing faster. Figured it was worth a shot, since no one else answered. Hope it helps!


Some suggestions:

Avoid flags. Oftentimes there are a hint that you can structure your code better
Learn the available language constructs and methods (e.g. case/when or #any?)
Avoid methods with side effects when you can better use a functional style. (E.g. a implement solutions method returning the solutions instead of a make_solutions method which modifies an instance variable with even has to be initialized before the call.) Among other things this improves reusability. You can still cache results in instance variables if needed.

Considering this you can write your provided code snippets a little neater:

def get_mark
  while (mark = gets.chomp)
    case mark
    when /x/i then chose_x
    when /o/i then chose_y
    else
      puts <<-EOS.gsub(/^ */, '')

      What is this strange mark? please choose 'X' or 'O'!
      EOS
      continue
    end
    break
  end
end

def game_won?
  solutions.any? do |solution|
    solution[0] != ' ' && solution[0] == solution[1] && solution[1] == solution[2]
  end
end

I didn't dig through your git repo though. If you have more specific questions you should ask them.


This review comes with the caveat that I've spent a few days in total on Elm so far... Take anything I say with a pinch of salt.

Firstly, some style things.

posX: Int -> Int -> Int
posX i n =
  round (33 + (15 * cos (6.28 * (toFloat(i) / toFloat(n)))))

Why so many brackets? You can cut it down to this very easily

posX i n =
  round (33 + 15 * cos (6.28 * toFloat(i) / toFloat(n)))

But you can make it even clearer by using a |>

posX i n =
  33 + 15 * cos (6.28 * toFloat(i) / toFloat(n))
    |> round

I like this more because it also promotes the calculation to its own line where nothing else happens. You could also have written:

posX i n =
  round <| 33 + 15 * cos (6.28 * toFloat(i) / toFloat(n))

I think it's up to you which one you prefer. I like to think about getting the value first and then rounding it.

There is a similar thing here:

drawFace : Int -> Html Msg
drawFace numDots =
  div [ style "width: 66px; height: 66px; padding: 10px" ] [
    svg
      [ version "1.1", width "66", height "66" ]
      (drawDice ::
      (List.map (\i -> drawDot i numDots) (range 0 (numDots - 1))))
  ]

I would instead have:

drawFace : Int -> Html Msg
drawFace numDots =
  div [ style "width: 66px; height: 66px; padding: 10px" ] [
    svg
      [ version "1.1", width "66", height "66" ]
      (range 0 (numDots - 1)
        |> List.map (\i -> drawDot i numDots)
        |> (::) drawDice
      )
  ]

It may look more complex but it's easier to follow in my opinion because each line does one thing.

Create your range
Map each to an Svg Msg (your dots)
Cons the face to the list of dots

Now, if you change the order of your arguments to drawDot you can simplify it further with currying.

drawDot: Int -> Int -> Svg Msg
drawDot n i =
  circle [ fill "black", cx (toString (posX i n)), cy (toString (posY i n)), r "5" ] []

(range 0 (numDots - 1)
    |> List.map (drawDot numDots)
    |> (::) drawDice
)

You'll find that you need to think about the usage of the function before writing it so you can get the parameter order right for currying.

In my limited understanding/knowledge of Elm, I'd say that your code is pretty good :)


Is my unity component validation overkill?

Right now you are calling GetComponent<T>() twice if the first call return a value != null.
Well, I would do this in a very simple way.
private void OnValidate()
{
    rigidbody = GetComponent<Rigidbody>();
    if (rigidbody != null) { return; }

    rigidbody = gameObject.AddComponent<Rigidbody>();
}


A reliable way to remove consecutive appearances of a substring

Your code looks like it does exactly what you want to me.

Some notes:

StringBuilder methods (which you're emulating by using an extension method) return the modified StringBuilder, so they can be used in a fluent manner. You should probably do the same.
I don't like changing the index of a for loop. Especially since i-- means “stay at the same index”, I think that's confusing. You should use a while loop instead.
You can shorten your code by quite a bit by using Regex:

public static string RemoveConsecutive(string text, string value)
{
    // validation omited

    string regex = string.Format(@"({0})+", Regex.Escape(value));
    return Regex.Replace(text, regex, match => value);
}

Shorter code is usually less error prone. But in this case, I'm not so sure about that, because there are some intricacies in this code:

Calling Escape() is crucial if value contains some regex special characters (e.g. *).
If the value was used directly as the replacement (instead of a delegate), it wouldn't work correctly if it contained any substitution (e.g. $0).


To begin with, you cannot use random.uniform() in your current design. The tutorial specifically emphasize that the  noise function shall be seeded, that is, for the same argument it shall always return the same result.

Second, the tutorial suggests that each octave must have its own noise generator. I believe it is essential (again, the noise it seeded, so you'd get literally the same noise for each octave).

You can get away with random.uniform() by calculating noise tables (one per octave), and use them as noise functions. In fact, I'd recommend this approach.


Best way to get the best performance of a large CSV upload in PHP

I would say that when you are dealing with bulk load operations, you might want to forego usage of your framework's ORM (data model) or query builder functionalities, in favor of more straightforward raw query or even command line functionality in order to leverage the DB's bulk load capabilities.

In this case, if your file and DB are on same server you might consider Postgres COPY query to bulk load the CSV.

For example:

COPY {table_name} (column1, column2, ...) FROM '$file_name' DELIMITER ',' CSV

Here you specify the table columns that match your columns in the CSV (in order given in CSV).  If you have timestamps properly defined on your table, you eliminate the need for you to "enrich" your inserted data with timestamps like you are currently doing (i.e. they could behave much like an autoincrement field upon row insert). In most cases, you should probably let the database be the authoritative source for generating timestamps anyway (unless you are trying to capture some client-specific timestamp value).

If your application and DB are on separate servers, you might consider forming a command-line statement using \copy to satisfy your requirement. This is pretty much the same syntax-wise as using COPY. This is the case that would be applicable to you since you are using RDS.

I think this would allow you to greatly simplify your code here such that you really only need to do your update check, your file system validation, then the bulk load command.

You would move away from the concept of interactively loading and refreshing data between the client and database.

You probably should also read through AWS documentation on bulk-loading into RDS for other considerations.

The bottom line here is that when you start thinking about bulk loading, you should probably understand that there are specific tools for this sort of work that go beyond the capabilities of your framework/ORM.

Other code review thoughts:

Should you have a more meaningful name for this method?  handle() seems kind of generic.
You should consider refactoring this method, as there is a lot of code complexity within this single method.  Perhaps individual (protected/private) methods for:

checking to see table(s) needing upload
file path generation and file system validation as readable
changing PHP ini settings at runtime - i.e. set_time_limit() - and resetting after execution which you fail to do here
actually executing bulk load.

You have some problems with style consistency. You should consider settling on a style and sticking to it (prefereably PSR-1/PSR-2 if you want to stick to best existing PHP-wide standards). Examples:

inconsistent indents
inconsistent spacing around and placement of flow control structures
mixing of camelCase and snake_case in your user-defined variables
inconsistent spacing around assignment operators

You are using exact and loose comparisons inconsistently.  I didn;t mention this as style problem, as this is more significant to code quality than those other items.  I would suggest getting in the habit of using strict comparisons as default and using loose comparisons only where you have specific reason to do so.  Codebases that are littered with loose comparisons are much more likely to have bugs in them due to unexpected truthy/falsey behaviors.


Conditionally displaying a notice about free shipping in Woocommerce

Don't Repeat Yourself
The D.R.Y. principle is a fundamental principle in programming. Anytime logic is repeated more than once, it should be abstracted. For example, the first three variable assignments contain the same ternary operation:

(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")

That could be put into a function:
function GetProtocol() {
    return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
}

That way if any of that logic needed to be updated, it could be changed in once place instead of three. The HTTP_HOST could also be included in that function - in that case, a name of GetProtocolAndDomain would be appropriate.
Like Peter's answer on SO mentions- the function sp_custom_notice() can be declared once, since the only difference between the two definitions appears to be the last line - where the first argument passed is 'free shipping for $40 & under' in the first case and the first argument is ' free shipping for $40 & under' in the second case. There isn't really a need for a space in the second case?
Peter also claims the first three variables are not necessary:

Firstly, you don't need the 3 $*_link variables as WooCommerce has 2 conditionals - is_shop() and is_cart() to check if you're on a shop page or a cart page. Also, the , $shop_link & , $cart_link in the setcookies aren't required, so you can safely get rid of them.1

This makes sense, since you can have the cookies available for all pages on the domain instead of just a single page. In the event that is_shop() and is_cart() weren't available, you could compare the last 5 characters of $_SERVER[REQUEST_URI] with cart/ or shop/ using substr() with -5 as the start parameter.
Threshold constant
It appears that the value for $free_shipping_threshold doesn't change. Because of this, it can be made a constant at the top of the file:
const FREE_SHIPPING_CONSTANT = 40;

Then that constant can be used in the sp_custom_notice function, and if that value needed to be updated, you could just look at the top of the file for the line to change.
Erroneous Line
I see the following line in your post:

$first_time_shop = true;

Did you manually add the HTML break tag (i.e.
) when posting here? I would expect that if that was actually in your code then the PHP interpreter would thrown an error.


You're dealing with a lot of incidental complexity here. Especially extracting the product attributes from the parameters seems to be quite involved. If you have control over the form that's producing those there might be more opportunity for making things easier. As things currently are, I decided to create a factory class to allow us to break things down into smaller methods.

I didn't think deeper about the performance problem but how to structure the code in a more OO way. The main idea is to always construct a new line item and compare that to all existing line items until a match is found. The matching logic can go into the LineItem class. We can further simplify things if the LineItem could also take care about its product attributes. I punted on this and created a serialized attribute, but you might as well set up a proper association for this, maybe with a custom writer method for convenience.

Of course you need good test coverage to do a refactoring like this.

class LineItemFactory
  def self.build(parameters)
    new(parameters).build
  end

  def initialize(parameters)
    @parameters = parameters
  end

  def build
    LineItem.build(
      product: product,
      quantity: quantity,
      product_attributes: product_attributes
    )
  end

  private

  attr_reader :parameters

  def product
    @product ||= Product.find(parameters[:product_id])
  end

  def quantity
    @quantity ||= parameters[:quantity].to_i
  end

  def product_attributes
    @product_attributes ||=
      begin
        product_attributes = parameters[:line_item_attributes_attributes].try(:to_unsafe_h) || {}
        product_attributes.values.map { |attribute| attribute[:product_attribute] }
          .flatten
          .reject(&:empty?)
          .map(&:to_i)
      end
  end
end

class LineItem
  serialize :product_attributes
  delegate :store, to: :product

  def matches?(other)
    self.product_id == other.product_id &&
      self.product_attributes.sort == other.product_attributes.sort
  end
end

class Cart
  # [...]

  def add_product(parameters)
    line_item = LineItemFactory.build(parameters)
    attach_store_to_cart(line_item.store) if line_items.empty?
    existing = line_items.detect { |li| li.matches?(line_item) }
    if existing
      existing.quantity += line_item.quantity
      existing.save
    else
      line_items << line_item
    end
  end

  def attach_store_to_cart(store)
    update_attribute(:store, store)
  end
end


Don't extend list when your class isn't actually a list. It makes every instance that much more complicated when there is no reason to. What does it mean when you call .insert() on a Piece? It breaks all of your code and should not be possible in the first place.

Note: I wrote the following section because I thought you were using the base class to represent the coordinate of the specific piece. After being confused at why you where comparing the y coordinate to Player(1), I had to look at your linked code. This showed that you were doing something entirely different. The fact that I got that far with a completely wrong understanding of how your code works is a huge indication that the design is bad.

A list is good for doing list type things. Don't use it as solution to everything and treat it like a bag you can do whatever you want with. There are many different core data structures that do different things. You should learn how they work and when to use them.

I'm going to leave the following section as it still has valid points about giving things names and how classes should be structured.

What you want is a Coordinate structure that represent a location on the board. A Coordinate has an x value and a y value for the corresponding axises. Using a collection where the index is significant hides information and requires readers to know that x comes before y. If you don't want to write the small amount of code it takes to create the fields, you can use namedtuple to generate the class for you. I would do this for the tuples you are getting passed in as arguments, as well. from_coord.x is much clearer than from_coord[0].

Taking this a step forward into object oriented design. A chess piece is not a Coordinate. A chess piece has a location on the board, which is a Coordinate. Based on this, it might makes sense for Piece to have a coord instance variable.

move is a bad variable name. By the name, it is not clear what it represents. When you look at the code, you see that is change in respective coordinate values between the from coordinate and the to coordinate. Since you are using lists for both your coordinates and these move delta values, things become harder to follow as a specific index is related, but not the same thing. At first glance, it looks like move is just a coordinate.

Using Player(1) to access the enum value (code that should have been included in the question directly, not linked to) can be confusing. At first glance it looks like you are creating an instance of a class. Instead Player.One looks like you are referencing a constant. Accessing the value programmatically is supported for:

  situations where Color.red won't do because the exact color is not known at program-writing time. Source

This is not that situation. You know exactly which value you wan to be accessing.

# Castling - AND has higher priority than OR
if move[0] == 0 and move[1] == 2:
    if self[1] == Player(1) and FromCoord == (0, 4) or self[1] == Player(2) and FromCoord == (7, 4):
        return True

You can use parenthesis to group boolean expressions in order to ensure the indented order of operations. Doing this would mean you wouldn't need a nested if clause.

Even though you are familiar with C# conventions, when you are working in Python, you should use Python conventions. In Python, method and variable names are in snake_case, not CapWords. Class names do stay as CapWords. (PEP8: Naming Convetions)


Use binary mode
Currently, you are opening your files like this:

    in = fopen(optarg, "r");
    out = fopen(optarg, "w");

On a UNIX system that would be fine, but on a Windows system, that could result in CRLF pairs being converted into a single LF when reading, and single LF characters converted to CRLF pairs when writing.  This is particularly important because once you do the xor operation, your output may contain random LF characters.
You should open your files in binary mode instead:
    in = fopen(optarg, "rb");
    out = fopen(optarg, "wb");


Just a few quick observations:

You mix business logic with UI code. Normally, you'd go for separation of concerns and move the conversion functions into a separate class which is used by the UI, but does not belong to the UI.
Running a separate thread: how long does the conversion take? 1 ms? 2? I really doubt that the overhead of thread-creation is necessary here. (Though it may indeed serve as an excercise!)
Binary to ascii validation: if the amount of bits does not match, you overwrite the user input? Thus, if I, the user, make a little mistake, type 319 bits instead of 320, you actually force me to start over? /me pissed user :-)

That's it for now (probably not complete.)


PHP

The commonly accepted approach to SQL statements is to make commands all caps, so I would convert my SQL statements to look like so...

$sql="SELECT * FROM tab_mem ORDER BY sn DESC ";

In other words, only the information from your tables should be lower case. This makes it easier to read.

You really should never use error suppression. Sure if it isn't a fatal error its nice to ignore those errors and let the program continue running, but you should never, no matter how minor, let an error go unresolved. It doesn't help your program and could potentially cause more problems rather than less.

You just declared $data and $row then turn around name a new $row that you just set $data to, never having used the old ones. Why? If you aren't going to use that information, don't set it. I'd just remove the $data and first $row variables. This is one of the few times I think its ok to set variables in an expression, otherwise I'd point this out too.

Don't know if it is just stackoverflow messing with your code or not, but ensure that your code is indented! If it is you can ignore this line, but judging from later bits of code, I have to assume that its not just stackoverflow. Examples given in JavaScript section.

Where in the world did $dom and $parnode come from? Does this even work?

JavaScript

I'll admit to not being well versed in JavaScript myself, only enough to write minor scripts for myself. However a lot of what I know from PHP can be trasferred over to JavaScript, and my first problem here is that you have JavaScript functions within your JavaScript functions. Move those! I can't imagine when that would be necessary. All functions should be within the same scope. Minor exceptions would be lamda functions, though I hold that if you can make it into a function to be reused, do so.

Your code indentation here is really lacking. If I did not have a text editor with matching-brace highlighting there is no way in the world I could read this. An I'm still having trouble anyways. Here's a couple of examples of good indentation:

var gmap = new google.maps.Map(
    map_div, {
        zoom:16,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
);
//etc...
while (markers.length){
    var address="";
    geocoder=new google.maps.Geocoder();
    alert("...");
}

Proper indentation would also show you that you have an extra closing brace } on the end of your onSuccess() function. Which probably causes errors.

I'm going to stop here. I've already pointed out quite a bit for you to look at. If after you have corrected these things you want me to look over it again you can update your question with the new code and drop me a comment and I'll try to come back to it. Good Luck!


Javascript function to return an array that needs to be in a specific order, depending on the order of a different array

I would

Encapsulate the names and colors in a data structure
Use .map instead of .forEach

So something like this;
function chartBackgroundColor(collection){
  const nameColorMap = {
    "TripAdvisor": "#00B98B",
    "Google": "#FFBD00",
    "Facebook": "#4B6DAA",
  };
  return collection.map(data => nameColorMap[data.name] || "#D9D9D9");
}


Changing a matrix by multiplying indexes of min element

Use error detection

With non-numeric input, scanf("%d", N); and following code will not function as expected.  Handle bad input.  For now, simple whine and take your toys home.  Later you can add more sophisticated error handling.

void InputArray(int a[][50], int M, int *N){
    // scanf("%d", N);
    if (scanf("%d", N) != 1) {
      perror("Invalid size");
      exit(EXIT_FAILURE);
    }

Seek clarification or state functionality on edge cases

"program needs to find the min element in each column. Then it needs to multiply the row in which the element is, with the difference of its indexes".  What should happen if the min value occurs twice?

Fold like functions together

Only difference between PrintA() and PrintB() is the header text.  Pass that in.

void PrintArray(const char *header, const int a[][50], int N){
    fputs(header, stdout);
    for (int i = 0; i < N; i++){
        for (int j = 0; j < N; j++){
            printf("%d  ", a[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}
...
PrintArray("You've entered:\n", a, N);
PrintArray("New matrix is :\n", b, N);

Avoid naked magic numbers

Rather than code 50 in many places, define it once and use that.

#defined ARRAY_DIM_MAX 50
// int a[50][50], b[50][50], N;
// InputArray(a, 50, &N);
int a[ARRAY_DIM_MAX][ARRAY_DIM_MAX], b[ARRAY_DIM_MAX][ARRAY_DIM_MAX], N;
InputArray(a, ARRAY_DIM_MAX, &N);

Further, consider using different constant names should you later want a rectangle matrix.  Even if both are 50, this better self documents the code.  Recommend to not declare many variables declares on a line.

#defined ARRAY_ROW_SZ 50
#defined ARRAY_COL_SZ 50

// int a[50][50], b[50][50], N;
// InputArray(a, 50, &N);
int a[ARRAY_ROW_SZ][ARRAY_COL_SZ];
int b[ARRAY_ROW_SZ][ARRAY_COL_SZ];
int N = 0; // Defensive coding to assign simple small objects.
InputArray(a, ARRAY_ROW_SZ, &N);

Minor stuff

No need for j==0 iteration

for (i = 0; i < N; i++){
    min = a[0][i];
    d = 0 - i;
    // for (j = 0; j < N; j++){
    for (j = 1; j < N; j++){

Use const when referenced data is unchanged

This allows for wider applications, convey to users of the function of data involatility and may allow additional optimizations.

// void PrintA(int a[][50], int N){
void PrintA(const int a[][50], int N){

Use standard signatures

void main() may be acceptable on your platform, but not others.   Better to return int.

Avoid non-portable code

system("cls"); is non-standard.

Use size_t

For array sizing and indexing, size_t is the Goldilocks type, neither not too narrow nor too wide.  As you develop, use that rather than int for indexing.  int is OK for learner code.

// void InputArray(int a[][50], int M, int *N){
void InputArray(int a[][50], size_t M, size_t *N){


GPA calculator, implemented for a course

In order, with come code comments first:

The StudentUtil-class:

package modul;

Try to avoid naming things as misspelled words. "Module" would probably not be a good choice for a package name because "Module" has a meaning in programming in general, and since version 1.9 it even has a specific meaning in Java. This doesn't mean, however, that "Modul" is better.

import java.util.ArrayList;

public class StudentUtil {

    public static double[] calculateGPA(int[] studentIdList, char[][] studentsGrades) {
        double[] grades = new double[studentIdList.length];
        int i = 0;

        for (char[] studentGrade : studentsGrades) {
            double sumGrades = 0.0;

            for (char grade : studentGrade) {

Double for loop, great, and without incrementing variables, even better. The names "grade" and "studentGrade" leave me a bit confused though. "studentGrade" contains more than one grade? I would replace "studentGrade" with something like "singleStudentGrades".

                if (grade == 'A') {
                    sumGrades += 4;
                } else if (grade == 'B') {
                    sumGrades += 3;
                } else {
                    sumGrades += 2;
                }

Consider having an explicit if (grade == 'C') case, and making your else case throw an error. It's a simple way to make sure your input is only ever A, B, or C. Unless we want to assume that anything not given a letter grade (e.g. something never assigned a grade) defaults to a 2.

            }
            grades[i++] = sumGrades / studentGrade.length;
        }

        return grades;
    }

    public static int[] getStudentsByGPA(double lower, double higher, int[] studentIdList, char[][] studentsGrades) {
        // perform parameter validation. Return null if passed parameters are not valid
        if (lower < 0.0) {
            return null;

Note about the nulls at the end of my answer

        }

        if (higher > 4.0) {
            return null;
        }

        if (lower > higher) {
            return null;
        }

        if (studentIdList.length != studentsGrades.length) {
            return null;
        }
        // invoke calculateGPA
        double[] gpas = calculateGPA(studentIdList, studentsGrades);
        ArrayList<Integer> ids = new ArrayList<>();

        for (int i = 0; i < studentIdList.length; i++) {
            if (gpas[i] >= lower && gpas[i] <= higher) {
                ids.add(studentIdList[i]);
            }
        }
        // construct the result array and return it. You would need an extra for loop to compute the size of the resulting array

I don't understand this comment - is it justification for calling ids.size()? If so, it's not quite right. You could add a counter variable that gets incremented in your if clause above. That doesn't mean that you necessarily should, though - see below

        int[] ret = new int[ids.size()];

        for (int i = 0; i < ret.length; i++) {
            ret[i] = ids.get(i);
        }

Rather than this, consider List.toArray() - it'll save you the indexing. Check out this question: Converting 'ArrayList to 'String[]' in Java

        return ret;
    }

}

test-class:

package modul;

import static java.lang.System.out;
import java.text.DecimalFormat;
import static java.lang.System.out;

public class Sandbox {

    public static void main (String[] args) throws Exception {
        int[] studentIdList = { 1001, 1002 };
        char[][] studentsGrades = { { 'A', 'A', 'A', 'B'  }, { 'A', 'B', 'B' } };

        double[] results = StudentUtil.calculateGPA(studentIdList, studentsGrades);

        for (double result : results) {
            out.printf("%.2f\n", result);
        }

        int[] ids = StudentUtil.getStudentsByGPA(3.2, 3.5, studentIdList, studentsGrades);

        for (int result : ids) {
            out.println(result);
        }
    }
}

I encourage you to consider writing unit tests (I recommend JUnit). It'll make your tests easier to write and read. The above tests are ok, but I would definitely add tests to check that you get null when you expect to.

Overall:

Your code is overall quite clean and easy to follow. It's not quite production-level, but it is good for a Java course. Nice job!

Regarding returning null:

There is a large discussion around this issue. I think most people believe something along these lines: 1.) null should not be used in place of an error. This is because in general, methods should enforce their contracts loudly, i.e. if a method's job is to take a number greater than zero and return it times two, and it gets a number less than zero, it should complain. By returning null, you force programmers who use your code (if they're responsible) to write in code to handle the possible null case, because otherwise there's no guarantee that they will be aware of the error that made your method return null.

And 2.) null can be used as "no results", but it might be better to return an Option or an empty data structure instead. For more, check out this question Is it better to return NULL or empty values from functions/methods where the return value is not present?

For a class assignment, though, it may well be the case that using null is "ok" because its fast - and it doesn't require you to shift focus from whatever the point of this assignment is to spend time writing exception throwing code. Avoiding using null as an error, and instead throwing an exception, is a best practice, though, and as you grow as a programmer you may want to do so even if it's not required. Be careful though - if your code is auto-graded and it is expected that it will return null for a given input, an exception will probably cause it to be marked wrong. In this case I suggest writing code to your assignment's specification, and being content with knowing that were you writing code in the "real world", you'd do it differently


Segmenting brain images (Dicom format) using region-growing algorithm

I don't have the Image Processing Toolbox, so I can't test your code, but I'll go through what I can.

Never do diff = 10; diff is a useful builtin function in Matlab, so using it as a variable name will cause the function to be useless. The same goes with max, sum, size and so on.

value1 = sum(sum(J > 0)); is a bit faster than value1 = sum(J(:)>0);, so with regards to performance you did the right thing. In my opinion however, sum(J(:)>0) is a bit cleaner, and it can also be scaled to more dimensions.

Instead of elseif N <= 10 you can simply do else, as they mean the same thing in this context.

If it takes 4-5 iterations pretty consistently, then maybe you can increase the initial value of th to e.g. th = 40. It will result in fewer iterations for most images, so a faster algorithm. You might benefit from guessing a good value, run the algorithm, if you don't hit convergence, jump to a lower value. This will perform better for most of the images, but will be slower for some. In total, it's likely faster.


Conner, I have a few minor points.

Firstly, you have no includes (ie, no -Idir). Do you really have no headers?
You should make the non-targets 'PHONY' so make knows they will never exist:

.PHONY clean
clean:
        rm -f ...

Same with all, server and client
It is not normal to clean everything on each build - usually you let make decide what is out of date and needs to be rebuilt.  For that you need to have all the dependencies declared to make (eg headers)
client and server depend upon the build directories and the executables, but not directly upon the sources.
the clean target remakes the build directories.  To me, these directories should be made when you build the targets:

$(CLIENT_OBJ_DIR) $(SERVER_OBJ_DIR):
        mkdir -p $@

client: $(CLIENT_OBJ_DIR) $(CLIENT_EXECUTABLE)

server: $(SERVER_OBJ_DIR) $(SERVER_EXECUTABLE)

-Wall does not really give you 'all' warnings. There are many more that are worth enabling.


Yes this raises concerns

You'll be skipping some controller logic which may involve;

Checking certain user conditions (ie: are they logged-in)
Can they perform this model action due to their ACL/permissions?
Collecting other data from other models/methods to pass into this model method

Depending on your design, accessing a model directly and skipping the controller logic can raise some unexpected errors (described above) and/or give users actions they wouldn't necessarily have. i.e: Admin@RemoveUser

Usually in an MVC pattern, the model and method names are guessable, depending on the action. Ie: http://example.com/user/view/1 = User model, viewAction method. So exposing this information isn't really a concern. What is a concern is users accessing model action that are restricted by controller logic.

So, what should I do?

Contact the controller directly, and have your view processor to detect it's an AJAX request (through the HTTP_X_REQUESTED_WITH=XMLHttpRequest header) to "disable" the default view with all the design, and just passback (usually) a JSON string that you can use with JavaScript (JSON.parse) and do as you want with the result.


Sorry, it just seems to me that issues lie outside of the piece of code that you're suggesting to review. The code itself is more or less fine, but some assumptions behind it seem not right.

  I had thought about Team objects but I was hoping not to get too complex. i can't access the filtering in the templates either.

Well, you still have teams anyway, you're just passing them around "implicitly", by their numbers. IMO it actually makes it more complex, and is less "pythonic" (remember, explicit is better than implicit).

And, although I don't know the exact requirements, but maybe what you're trying to do in templates could be achieved another way?

Update in response to comment:

  Also I want to point out that the code works. It just doesn't "mesh" in my head well.

The code may work, but it looks very… unconventional. And in Python conventions mean a lot. And in Django they mean even more: it's a framework, and, as any other framework, it has lots of design decisions already made for you. It allows you to focus on your data structures and your business logic, but it does that by taking from you some freedom.

So when you're starting to write such complex initialization methods, then probably something is going wrong. I'd say this, and "implicit" teams, are cases when you're beginning to "fight the framework". It's usually the losing battle. The conventional way is to just have a Team class. It will also make code more maintainable, which is very important. (What if the requirements change and you'll need to store more information about the team, not only its number?)

  i am also trying to keep the number of different objects in the DB to a minimum but its not THAT important

Seems like premature optimization. I doubt that could be a performance bottleneck. Although it depends on your requirements.


I made a Rock paper scissors game with Python 3.8

I give it a 0 because I tied the bot and the bot still wins.

Just kidding.

Without considering some of the ways this could be made simpler and more compact (ie. strictly from a style guide point of view), this would be rated exactly a 4.88/10 (at least, that's what pylint is claiming):

************* Module rps
rps.py:3:13: C0303: Trailing whitespace (trailing-whitespace)
rps.py:6:47: C0303: Trailing whitespace (trailing-whitespace)
rps.py:7:13: C0303: Trailing whitespace (trailing-whitespace)
rps.py:9:19: C0326: No space allowed before bracket
for tries in range (1,4):
                   ^ (bad-whitespace)
rps.py:9:21: C0326: Exactly one space required after comma
for tries in range (1,4):
                     ^ (bad-whitespace)
rps.py:13:25: C0326: Exactly one space required after comma
        choices = ['Rock','Paper','Scissors']
                         ^ (bad-whitespace)
rps.py:13:33: C0326: Exactly one space required after comma
        choices = ['Rock','Paper','Scissors']
                                 ^ (bad-whitespace)
rps.py:15:19: C0326: Exactly one space required before assignment
        bot_guess  = random.choice(choices) #Will randomly pick from the list 'choices'
                   ^ (bad-whitespace)
rps.py:17:0: C0301: Line too long (106/100) (line-too-long)
rps.py:21:110: C0303: Trailing whitespace (trailing-whitespace)
rps.py:21:0: C0301: Line too long (110/100) (line-too-long)
rps.py:32:22: C0303: Trailing whitespace (trailing-whitespace)
rps.py:35:23: C0303: Trailing whitespace (trailing-whitespace)
rps.py:38:22: C0303: Trailing whitespace (trailing-whitespace)
rps.py:41:23: C0303: Trailing whitespace (trailing-whitespace)
rps.py:44:23: C0303: Trailing whitespace (trailing-whitespace)
rps.py:45:58: C0303: Trailing whitespace (trailing-whitespace)
rps.py:59:37: C0303: Trailing whitespace (trailing-whitespace)
rps.py:1:0: C0114: Missing module docstring (missing-module-docstring)
rps.py:6:0: C0103: Constant name "user_point" doesn't conform to UPPER_CASE naming style (invalid-name)
rps.py:7:0: C0103: Constant name "bot_point" doesn't conform to UPPER_CASE naming style (invalid-name)

-----------------------------------
Your code has been rated at 4.88/10

It is OK to ignore the last 2 messages. Pylint thinks variable that are declared outside functions are supposed to be constants. But in this case the script is so short that creating functions doesn't make sense.

formatting on the trailing comments:

bot_guess  = random.choice(choices) #Will randomly pick from the list 'choices'
while user_guess not in choices:#if the user tries to put in anything other then the choices given

much nicer to do: <code><one space>#<one space><comment>

bot_guess  = random.choice(choices) # will randomly pick from the list 'choices'
while user_guess not in choices: # if the user tries to put in anything other then the choices given

The if-elif statements used to determine the winner can be simplified quite a bit. Think about it like this: there are only 3 outcomes, so you should only need 3 checks, at most. There are several ways to do it, but here is one I thought of:

    if user_guess == bot_guess:
        print('Tie!')
    elif choices.index(user_guess) == (choices.index(bot_guess) + 2) % 3:
        print('The bot earns a point!')
        bot_point += 1
    else:
        print('The user earns a point')
        user_point += 1

The list choices = ['Rock','Paper','Scissors'] is treated as a constant, so declare it at the top of the file, right after the import statements (and it actually should be in all UPPER CASE). Since the content won't change, it would be good practice to use a tuple instead of a list (just swap the square brackets [...] for parens (...)).
Python 3.4 introduced a feature called f-strings that make string formatting a lot cleaner. Read the link for all †he details, but the main takeaway from it is that if you prefix a string literal with an f, it allows for string interpolation "on the fly":

print('After ' + str(tries) + ' tries. ' + ' The score is') # NO!!!
print(f'After {tries} tries, the score is') # YES!!!!

The try-except block is not needed. You can replace it with:

user_guess = ''
bot_guess  = random.choice(choices)
while True:
    user_guess = input('Rock Paper Scissors? ')
    if user_guess in choices:
        break
    else:
        print("you must pick a choice from the list!")

You could also combine the user_point and bot_point into a single points variable, and assign negative points for the bot and positive points for the user. This is kind of like taking the users side: you earn points by winning, and lose them when the bot wins. The downside is that you can't keep track of how many points each player has earned, only the difference between the 2.

So in the end, I get this:

#!/usr/bin/env python3

import random

CHOICES = ('Rock', 'Paper', 'Scissors')
points = 0
print('Lets play Rock Paper Scissors')
for tries in range(1, 4):
    user_guess = ''
    bot_guess = random.choice(CHOICES)
    while True:
        user_guess = input('Rock Paper Scissors? ')
        if user_guess in CHOICES:
            break
        else:
            print("you must pick a choice from the list!")
    print(f"The bot did {bot_guess}")
    if user_guess == bot_guess:
        print('Tie!')
    elif CHOICES.index(user_guess) == (CHOICES.index(bot_guess) + 2) % 3:
        print('The bot earns a point!')
        points -= 1
    else:
        print('The user earns a point!')
        points += 1
if points > 0:
    print(f'After {tries} tries, THE USER IS THE WINNER BY {points}!!!')
elif points == 0:
    print(f'After {tries} tries, IT\'S A TIE!!!')
else:
    print(f'After {tries} tries, THE BOT IS THE WINNER BY {points * -1}!!!')


Controller making request to an external API

After running the code through JSHint, you are missing a semicolon on line 16 of the first code swatch (], cb)). The tests look good on JSHint.

I suggest making the following changes:

Remove async.waterfall in getFixture

As you said in your own words, "performance isn't really an issue". As such, I'd recommend to just remove the waterfall function to make the code cleaner and easier to maintain. You probably won't run into a noticeable speed difference anyways, if it is on cron.

Shorten callbacks

This may be more opinionated, but I would suggest in the first swatch to change your callbacks from this format:

var errorMsg = "Error in response with code: " + response.statusCode;
callback(null, errorMsg);

to this format:

callback(null, "Error in response with code: " + response.statusCode);

It is just as easy to read (if not easier) and works just the same, except without the variable instantiation.

Shorten a line

function getFixture(cb) {...
module.exports = getFixture;

Change to

module.exports = function(cb) {...

Or, even (according to choice):

module.exports = function getFixture(cb) {...

Good luck!


Cast inside the method or let the client code cast, which one is better?

In my opinion the generic method is better for two reasons. First, it's cleaner, both for the client calling it because they don't have to cast and for the process of casting because it is only done in one place. Secondly, the client that's asking for the control knows the type of the control in this instance so it's very sensible, and good practice, to have the client specify that rather than sending back an object just so the client has to cast it. That's why generics exist.

However, I recommend in your code in the method you use the as operator rather than a cast because even though the client calling you specified the type, the as operator will simply return null instead of throwing an exception.


Printing log messages with varying length fit into screen width

Let me assume you're writing in C++ (leaving a quick review of C++ Cish code for the end.)

For clarity I prefer to split code in separate functions, they may be even reused.

void print_message(const std::string& message, bool isPassed)
{
    const std::string result = resolve_result_message(isPassed);
    std::cout << message << get_line_padding(message, result) << result << std::endl;
}

std::string resolve_result_message(bool isPassed) {
    // Avoid hard-coded strings, move these to constants
    return isPassed ? "[  FAILED  ]" : "[  PASSED  ]";
}

std::string get_line_padding(const std::string& message, const std::string& result) {
    const int requiredPadding = SCREEN_WIDTH - message.length() - result.length();

    if (requiredPadding <= 0)
        return "";

    return std::string(requiredPadding, '.');
}

About original C code:

You have a maximum output size (which, BTW, will be unaligned with other lines) set to SPRINTF_BUFFER_SIZE. Note that if input is bigger than this then your application may crash and you do not perform any check about this. You may want to cut output (in this case just reused SCREEN_SIZE_X + 1 constant).

If you're using a C compiler then do not cast return value of malloc().

sprintf() to print characters is absolutely an overkill, after all this is enough (don't forget to add a NUL character at the end):

for (int start = strlen(sprintfBuffer), i = 0; i < iNumDots; ++i)
    sprintfBuffer[start + i] = '.';

Now you can see it's equivalent to (after checking if iNumDots is positive):

memset(sprintfBuffer + strlen(sprintfBuffer), '.', iNumDots);

If this function isn't invoked by multiple threads you can avoid to allocate/free the buffer each time marking it as static.

If you're working on resource limited environment you may want to avoid unnecessary allocations, for this example let me assume your code is single threaded and message is short enough to fit one line, let me write it in C:

void print_message(const char* message, bool isPassed) {
    static char buffer[SCREEN_WIDTH + 1] = { 0 };

    const char* passed = isPassed ? "[  FAILED  ]" : "[  PASSED  ]";

    memset(buffer, '.', SCREEN_WIDTH);
    memcpy(buffer, message, strlen(message);
    memcpy(buffer + SCREEN_WIDTH - strlen(passed), passed, strlen(passed);

    puts(buffer);
}


What is better? For-loops or generator expressions (in cases like this)

The second version can (and should) be written using sum instead of reduce(add,...), which is somewhat more readable:

sum(i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0)

That is the version that I'd prefer as far as implementations of this particular algorithm go because it's more declarative than a loop and just reads nicer in my opinion. (It's also faster though that's less of a concern).

However it should be noted that for summing all numbers up to n that divisible by 3 or 5, there's actually a better algorithm than going over all those numbers and summing them.


Editing Javascript and rendering HTML in one window

Style review

Added newlines between methods – Your code looks mighty cramped, and this makes it harder to read, which in turn makes it harder to understand. This also applies to places within code. When programming in Python the guidelines says to use two new lines between methods, and if needed one new line in code. That is good advice
Keep good indentation and consistent brace style – It looks like you mostly have good indentation, and consistent brace styles. I like that (mostly) you're using braces around even one line blocks. That's good!

There are a little slip up in the alert() method, and similar a hidden break in the alertException()
Add comments – You should have some comments in the code indicating what the different parts do, and when they do it. Not what the code does, but why it does is that way

Code suggestions

To me it is not clear when you execute the new code, of if it is continously being executed. I would not continuosly execute it, and rather have some buttons to start and stop execution.
I would also have a (scrolling) panel for the javascript console output, if possible. Lots of messages will be made to the console, and otherwise be hidden
In due time you'll also need to have the ability to have the possibility to edit the html section, so maybe you need to have a button or panel to allow editing that as well
In other words, I think I would divide the left panel into javascript and raw html, whilst the right panel is divided into the html output and javascript console. And some buttons or menu somewhere. If possible in JavaFX the divider in either panel should be movable to accomodate for whatever part is the longer, and of course they should have scrollbar if text extends the panel


Your jQuery function was okay, but it's common practice now to put your animations into CSS wherever possible.

I've rewritten your code, moving as much as possible into CSS. I'll explain how and why below, or you can skip to the final solution here.

Semantically your links shouldn't be data-attributes as they control page navigation and need to be visible and identifiable as such.

Breaking News:

            No 10 armed police arrested over hardcore pornography

            EDF extends life of UK nuclear plants

You shouldn't use float: left for this, these components are inline, not floating.

#news-ticker .ticker-title {
    display: inline-block;
    margin-right: 12px;
}

#news-ticker ul {
    display: inline-block;
    position: relative;
}

Next we want to make each news item invisible when not active, and we want them to all appear in the same place. A simple way to do this is to make their position absolute.

#news-ticker li {
    position: absolute;
    left: 0;
    width: 0;
    overflow: hidden;
    height: 1em;
    word-wrap: break-word;
    opacity: 0
}

There are a few more things I've added here as well...

width: 0: By making the width of the elements 0 they are invisible, and we can extend the width to show them a letter at a time.
word-wrap: break-word: This helps us get the tick each letter at a time effect.
overflow: hidden: stops us from seeing the rest of the sentence when the container isn't wide enough.

Next we make the animation. There's a good guide here about how they work.

#news-ticker li.tick {
    -webkit-animation: tick 5s linear;

}

@-webkit-keyframes tick {
  0% {
    width: 0;
  }
  5% {
      opacity: 1;
  }
  90% {
    width: 550px;
    opacity: 1;
  }
  100% {
     opacity: 0
  }
}

This means that when we add the class .tick to one of our list elements it will animate from 0 width to 550px.

Now for our small amount of JavaScript to switch the classes and make the wrap work on letters instead of words.

$(function () {
   var $ticker = $('#news-ticker'),
   $first = $('li:first-child', $ticker);

Unfortunately there's no letter-wrap CSS attribute, so we have to cheat a little. Here I insert a blank space inbetween each letter, essentially making it a word.

   $('a', $ticker).each(function () {
       var $this = $(this),
         text = $this.text();
       $this.html(text.split('').join('&#8203;'));
   });

And then start the ticker. Every time an animation ends, it grabs the next (or first) element and continues:

   function tick($el) {
     $el.addClass('tick')
       .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function () {

         $el.removeClass('tick');
           var $next = $el.next('li');
           $next = $next.length > 0 ? $next : $first;
         tick($next);
     });
   }

   tick($first);

});