Yes, code can be optimized to O(slotsA.length + slotsB.length) asumming that slotsA and slotsB are already sorted and the time ranges in each input do not overlap (which seems to be the case from your example).
Haven´t tested code and there are probably some edge cases missing but it should give you the idea:
    int idxA, idxB = 0;
    int maxStartDur, minEndDur, overlap;

    while (idxA < slotsA.length && idxB < slotsB.length) {
        maxStartDur = Math.max(slotsA[idxA][0],slotsB[idxB][0]);
        minEndDur = Math.min(slotsA[idxA][1], slotsB[idxB][1]);
        overlap =  minEndDur - maxStartDur;

        if (overlap >= dur) {
            optTime[0] = maxStartDur;
            optTime[1] = maxStartDur + dur;
            return optTime;
        }

        if (slotsA[idxA][1] > slotsB[idxB][1]) {
            idxB += 1;
        } else {
            idxA += 1;
        }

    }

In your case, you start with 10-50 and 0-15. It did not give enough overlap. Is it worth comparing 0-15 with the other slotA ranges? No, because the others will start at more than 50, and they won't overlap.
Is it worth comparing 10-50 with other slotB ranges? Yes, because there could be a 20-30 range afterwards. Basically, 50 is greater than 15, so thats our hint that we can keep growing that 15 going to next range from slotB and as long as its less than 50, we might keep having an overlap.
If you keep doing this, you will arrive at desired answer.
There might be data structures suited for this, but it is still simple enough to not need one.


Gin framework project with an endpoint to return a list of users based on their score

Let's start by addressing your 2 main questions:

1. Visibility (exporting) of functions

Yes, there's a very easy way of doing this, by using receiver functions (methods), and interfaces. Golang interfaces are incredibly powerful if you understand where they actually differ from "traditional" languages with a full-blown OOP model. you could have a directory type, and expose an interface to the service, which only declares the functions you want to use. Suppose you want your service to access GetUsers, but not a FilterByX, then just pass this directory type in as an interface type limiting how you can use it:

// in service
type Directory interface {
    GetUsers() []User
}

type service struct {
    dir Directory // interface type
}

func New(dir Directory) *service {
    return &service{
        dir: dir,
    }
}

The interface is declared in the package that uses it, not in the package implementing said interface. This makes unit-testing a lot easier. There's quite a few articles about this around. It's a bit odd at first, if you're used to OO, but it makes sense quite quickly. Don't try to make go look like C++, C#, or Java... it's its own thing, and though not perfect, it's got a lot of good things going for it.

As for the initUsers: that function is completely pointless. You could move the entire body of that function into your init function from the get-go. But why stop there? You can simply initialise your variable straight up, rather than creating 2 function calls to do the same thing:

var users = []User{
    {
        ID:         "1",
        Name:       "John",
        Country:    "UK",
        TotalScore: 500,
    },
    {
        ID:         "2",
        Name:       "Frank",
        Country:    "ES",
        TotalScore: 1500,
    },
    {
        ID:         "3",
        Name:       "Bob",
        Country:    "UK",
        TotalScore: 2000,
    },
    {
        ID:         "4",
        Name:       "Anna",
        Country:    "FR",
        TotalScore: 3000,
    },
}

That's it, all done.

2. Marshalling unexported fields.

Yes, this is possible, but I'd strongly advise against it. However, here's a couple of ways to do it. In both cases, we're relying on the fact that golang supports a JSON Marshaller and Unmarshaller interface out of the box.

type User struct {
    id      string
    name    string
    country string
    score   int
}

// manually creating a map
func (u User) MarshalJSON() ([]byte, error) {
    data := map[string]interface{}{
        "id":      u.id,
        "name":    u.name,
        "country": u.country,
        "score":   u.score,
    }
    return json.Marshal(data)
}

// now with some pointer magic... mimics the omitempty tag
func (u User) MarshalJSON() ([]byte, error) {
    data := map[string]interface{}{
        "id":      &u.id,
        "name":    &u.name,
        "country": &u.country,
        "score":   &u.score,
    }
    return json.Marshal(data)
}

Now for unmarshalling:

// note a pointer receiver is required here, we're changing the receiver state
func (u *User) UnmarshalJSON(v []byte) error {
    data := map[string]interface{}{} // empty map
    if err := json.Unmarshal(v, &data); err != nil {
        return err
    }
    if id, ok := data["id"]; ok {
        // technically we need to check the type assert, I'll do it once:
        strId, ok := id.(string)
        if !ok {
            return errors.New("id value is not a string!")
        }
        u.id = strId
    }
    if name, ok := data["name"]; ok {
        u.name = name.(string)
    }
    if country, ok := data["country"]; ok {
        u.country = country.(string)
    }
    if score, ok := data["score"]; ok {
        u.score = score.(int)
    }
    return nil
}

As you can probably see now, each field you add will add more code that needs to be written, changing the names of fields is a right PITA... it's better to just not bother IMO.

You could use the pointer trick from the marshaller here to avoid the type assertions, though:

func (u *User) UnmarshalJSON(v []byte) error {
    data := map[string]interface{}{
        "id":      &u.id,
        "name":    &u.name,
        "country": &u.country,
        "score":   &u.score,
    }
    // unmarshals into map[string]<pointer to fields on struct>
    return json.Unmarshal(v, &data)
}

Still, this doesn't look nice to me. I'd just stick with exported fields + json tags. If you really don't want people to access fields in certain places, just use interfaces as explained above.

Something you really ought not to do, is your over-use of package aliases. You may, or may not have noticed that I've always used the User type, without a package name. You've got aliases like:

user "liveops-tool/user/model"
// and the even worse
userModel "liveops-tool/user/model"

This is what sometimes is referred to as stuttering names. Read this aloud and ask yourself whether your package name is giving the user of your code any clearer understanding of what the User type represents:

u := user.User{} // u is an instance of User from the user package

What's in the user package? What is this User? I don't know. I'm just annoyed at having to type user twice.

u := userModel.User{} // u us a user from the userModel package

OK, now I know User is probably some kind of data structure. Good, but did I really need to know that I'm getting a User form the userModel package? I'm still annoyed at having to type user twice. The file itself is in the directory called model (perhaps models would be better). That's the bit of information that I want, so why not just:

import (
    "liveops-tool/user/model"
)

func foo() {
    u := model.User{} // u is a user model
}

That's a lot better, isn't it? You may want to have a look at the golang code review comments page. There's a lot of stuff in there that makes your code nicer. It's mainly sensible stuff: keep package aliases to a minimum, keep package names short, but communicative. Avoid name stutter, etc...

A particular bug-bear of mine is when people have a package like handler, and have a New function in there like this:

package handler

func NewHandler() (*h, error) {
    return &h{}, nil
}

Forcing me to write handler.NewHandler(). There's a reason why people find Java overly verbose (SomeFooBarImpl foobar = new SomeFooBarImpl();). What else do you expect handler.New() to return, other than a new handler?

/rant...

Might revisit this one later on, I'm heading home for the day now :P


Smart pointer mark II - my answer to C++ 11 shared_ptr

(1) Style nit: Prefer #pragma once to fragile #ifndef-based include guards. #pragma once isn't yet part of the standard; but any compiler that supports C++11 will definitely have supported #pragma once for years already.

(2) Obviously, remove the std::cout usage from your constructors when using this class for real. :)

(3) This is a MAJOR issue, and a common one, which is why I want to make a big deal of it:

T& operator*() { return *ptr_; }
const T& operator*() const { return *ptr_; }

No no no no no. You should provide only one operator*, and it should look like this:

T& operator*() const { return *ptr_; }

The act of dereferencing a (smart) pointer does not modify the pointer object, and therefore should be a const method of that pointer object. Also, the result of dereferencing a (smart) pointer to T had darn well better be a reference to T! Adding const to the return type is just plain wrong.

This is the same confusion that people often have between int * const and int const *, or between std::vector<int>::iterator const and std::vector<int>::const_iterator. In your case the confusion is between sp<int> const and sp<int const>.

(4) As above, you should have only one operator-> and one get(), and both should be const methods:

T* operator->() const { return ptr_; }
T* get() const { return ptr_; }

(5) Your constructor should almost certainly be explicit:

explicit sp(T* ptr) : ptr_(ptr), ref_cnt_(new unsigned(1))

The exception-safety guarantees here look good to me. I would argue that size_t would be more appropriate than unsigned (you're probably paying for a 16-byte allocation anyway, so why not use that space?), but that's a nitpick.

If you really care about memory allocations, and want to keep learning about how the standard shared_ptr does things, you should try to implement the equivalent of std::make_shared for your smart pointer type, so that the memory allocations can be wrapped up together into a single call to new. I'd imagine that the tricky parts of make_shared have to do with alignment requirements.

(6) Your ref_cnt_ doesn't point to a std::atomic<unsigned>, so addref() is not atomic; copying the same sp from two threads at once may result in undefined behavior.

(7) In C++11, it would be advisable to implement a move constructor and a move assignment operator in order to avoid a pointless addref() and removeref() when moving an rvalue. However, there's no problem with correctness in C++11; because you implement a user-defined copy constructor, the compiler will correctly suppress the generation of default move constructor and assignment functions (which would do the Wrong Thing if they were generated, so it's a good thing they're not).

(8) Your copy assignment operator performs unnecessary operations in the case that x is being assigned from a copy of x; for example:

sp<int> x(new int);
sp<int> y = x;  // adds a ref, correctly
x = y;  // removes a ref, then adds a ref; could be implemented as a no-op instead

(9) You don't use remove_ref except inside try_delete. Personally, I would inline the one call to remove_ref, and then rename try_delete to remove_ref. I would also rename addref to add_ref for consistency, and remove its unused return value.

(Future) To continue building your smart pointer into something like the standard's std::shared_ptr, consider the following use-cases:

sp<int> s(nullptr);  // or (int *)NULL
s = nullptr;
s.reset();  // same as =nullptr

Consider inheritance, upcasting and downcasting. This will require fleshing out your ref_cnt_ pointer from unsigned* to struct ref_cnt*, and careful consideration of what metadata you need to keep in there.

class Mother { int m; };
class Father { int f; };
class Child : public Mother, public Father { int c; };

sp<Child> ch(new Child);
sp<Father> fa = ch;  // casting derived to base should work
ch.reset();
fa.reset();  // this should call ~Child on the correct pointer

Consider providing "weak references", which the standard library provides as std::weak_ptr. Weak references (weak_ptr) and strong references (shared_ptr) work tightly together, using the same infrastructure.

Consider providing the ability to pass in a custom deleter:

sp<char> buf(malloc(1024), (void(char*))free);
buf.reset();  // this should call free on the correct pointer


This looks quite fine, except this part:

if [ "$PART" -eq 0 ]
then
arecord -f cd -c 1 -d$DURATION -t raw -v -v | lame -b 128 -q2 -mm
-r - ./Documents/"LoggerAudio "$DAY-$MO-$YR\ $H"00".mp3
else
arecord -f cd -c 1 -d$DURATION -t raw -v -v | lame -b 128 -q2 -mm
-r - ./Documents/"LoggerAudio "$DAY-$MO-$YR\ $H"00 - Part - "$PART.mp3
fi

One problem here is indentation:
it's a lot easier to read when the branches of conditionals are indented.

A bigger problem is that a long and complicated pipeline is duplicated (looks copy-pasted),
which is a bad practice, because it's prone to errors.
Since only the filename is different,
you can set that in the conditional branches,
and then write the complicated pipeline only once.

if [ "$PART" -eq 0 ]
then
    out="LoggerAudio $DAY-$MO-$YR ${H}00.mp3"
else
    out="LoggerAudio $DAY-$MO-$YR ${H}00 - Part - $PART.mp3"
fi
arecord -f cd -c 1 -d$DURATION -t raw -v -v | lame -b 128 -q2 -mm -r - ./Documents/"$out"

Notice that I also slightly simplified the writing style of the filename.


Parsing XML with double nested tags using mindom

This is probably as good as you can get with minidom.
However, consider ditching minidom--it's really only there when you absolutely, postively need some kind of DOM api and only have the standard library. Note the documentation for minidom.

Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead
Warning: The xml.dom.minidom module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.

XML in Python is almost always processed with the ElementTree interface, not a DOM interface. There are many implementations of ElementTree including xml.etree.ElementTree (pure Python, in stdlib) and xml.etree.cElementTree (CPython, in stdlib), and lxml (third-party all-singing, all-dancing xml processing library that uses libxml2).
Here is how I would do this:
try:
    # On Python 2.x, use the faster C implementation if available
    from xml.etree import cElementTree as ET
except ImportError:
    # pure-python fallback
    # In Python3 just use this, not the one above:
    # Python3 will automatically choose the fastest implementation available.
    from xml.etree import ElementTree as ET

xmlstr = """<root>
<skill>
   <id>14</id>
   <name>C++</name>
 </skill>
 <skill>
   <id>15</id>
   <name>Java</name>
 </skill>
</root>"""

root = ET.fromstring(xmlstr)

def get_subelem_texts(elem, subelems):
    """Return {subelem: textval,...} or None if any subelems are missing (present but empty is ok)"""
    attrs = {}
    for sa in skillattrs:
        textval = skill.findtext(sa)
        if textval is None:
            return None
        attrs[sa] = textval.strip()
    return attrs

skillattrs = 'id name'.split()

for skill in root.find('skill'):
    args = get_subelem_texts(skill, skillattrs)
    if args is not None:
        my_object.create(**args)


Python program that gets basic information on a Github user

Just a note:
instead of using string.split() to check for spaces, you can directly check with in.

From:

if len(username.split()) != 1:
        print('Github usernames must be one word in length! Exiting!')
        return

To:

if ' ' in username:
        print('Github usernames cannot contain spaces! Exiting!')
        return

Also, instead of multiple print statements, you can use multiline strings: """...""" or '''...'''.

From:

print(f'The following information was found on user: {username}',
      end='\n\n')
print(f'Name: {responses_json["name"]}')
print(f'Bio: {responses_json["bio"]}')
print(f'Followers: {responses_json["followers"]}')
print(f'Following: {responses_json["following"]}')

To:

print(f'''
The following information was found on user: {username}

Name: {responses_json["name"]}
Bio: {responses_json["bio"]}
Followers: {responses_json["followers"]}
Following: {responses_json["following"]}''')


Set-uid root program that runs a program as the user “restrict” (follow-up)

You should really check the return value of getpwnam(). If, for whatever reason, the user "restrict" is not found, your program will crash. I'm not sure whether a null dereference can be exploited (I think not), but it's a "bad thing" anyways.

As already mentioned, giving a descriptive error message when execv fails is a good idea, too. In fact, do this on every possible error; no need for extra verbosity where you don't exepect an error -- in this case a perror with the failed function name should be enough.

You probably don't want the user name configurable in any way for security reasons, but just to make it easier to "configure" at compile time, I'd suggest to #define it.

All in all somehow like this:

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>

#define USERNAME "restrict"

int main (int argc, char **argv)
{
    if (argc < 2) return 1;
    struct passwd *r = getpwnam(USERNAME);
    if (!r)
    {
        perror("User " USERNAME " not found");
        return 1;
    }

    gid_t supp[] = {};
    if (setgroups(0, supp))
    {
        perror("setgroups");
        return 1;
    }

    if (setgid(r->pw_gid))
    {
        perror("setgid");
        return 1;
    }

    if (setuid(r->pw_uid))
    {
        perror("setuid");
        return 1;
    }

    char *env[] = {NULL};
    execvpe(argv[1], &argv[1], env);
    /* the following is only reached on error */

    fprintf(stderr, "Cannot execute `%s': %s\n", argv[1],
            strerror(errno));
    return 1;
}


Automate the Boring Stuff with Python 2nd Edition - Sandwich Maker Practice Project

while True
First of all, using "flag" variables is not customary in Python. Instead of using a boolean variable to control a while loop, you can just do while True: ... break.
Avoiding many ifs
You might notice the repeating structure of:
print(f'{item}= {price}')
total_amount += price

under every if. This is because your logic is reversed. You are currently iterating over ALL possible ingredients and checking if you need them. But there might be many that are not in use. It makes more sense to create a list of ingredients in use and then just take their price in a loop. This will require changing how you save your sauces. Instead of saving them as 'yes', we will save them with their name - to match with the prices dict keys.
So we will create a list of ingredients, and add the sauces as well:
if pyp.inputYesNo('Do you want mayo?(Y/N) \n') == 'yes':
    ingredients.append('mayo')

And now the printing loop will be if-free:
print(f'Your sandwich ingredients and prices are as follows: \n')
for item in ingredients:
    price = prices[item]
    print(f'{item}= {price}')
    total_amount += price

Full Code
import pyinputplus as pyp

# price of all ingredients
prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,
          'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,
          'ketchup': 1}

while True:
    ingredients = []
    # options to select bread, protein, cheese with inputMenu() method
    ingredients.append(pyp.inputMenu(['wheat', 'white', 'sour dough'],
                          prompt='Please select the type of bread you want for your sandwich: \n',
                          numbered=True))

    ingredients.append(pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],
                            prompt='Which type of protein you would like: \n',
                            numbered=True))

    if pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n')== 'yes':
        ingredients.append(pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True))

    # using inputYesNo() for single ingredients with no further types
    if pyp.inputYesNo('Do you want mayo?(Y/N) \n') == 'yes':
        ingredients.append('mayo')
    if pyp.inputYesNo('Do you want mustard?(Y/N) \n') == 'yes':
        ingredients.append('mustard')
    if pyp.inputYesNo('Do you want lettuce?(Y/N) \n') == 'yes':
        ingredients.append('lettuce')
    if pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n') == 'yes':
        ingredients.append('ketchup')

    # using inputInt() and blockRegexes that do not allow negative integer, float or 0
    sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n',
                              blockRegexes=['[0|-|.]'])

    total_amount = 0
    # using for loop to print items, prices and adding their amount to total_amount variable
    print(f'Your sandwich ingredients and prices are as follows: \n')
    for item in ingredients:
        price = prices[item]
        print(f'{item}= {price}')
        total_amount += price

    # at the end printing total amount and how much sandwiches have been ordered
    print(f"sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = "
          f"{total_amount*sandwichQT}")

    # confirming if the user need to reorder or user wants to confirm the order by simple yes/no
    # if user confirm by typing yes or y then menu will become false and while loop will terminate
    if pyp.inputYesNo('Please confirm your order: (Y/N)\n')== 'yes':
        print('Please take your order number from the machine and you will be notified when '
              'its ready')
        break


You could use min_by_key to find the minimum's index and the method swap defined in slices:

fn selection_sort(array: &mut [i32]) {
    let len = array.len();
    for i in 0..len {
        let min = (i..len).min_by_key(|x| array[*x])
                          .unwrap();
        array.swap(min, i);
    }
}


Accessing list elements when counting the number of rectilinear paths

Code organization

The definitions of readInts and read2Ints disrupt the mathematical code.  The I/O routines belong further down, just before main.

import Data.Maybe and import qualified Data.ByteString.Char8 as C appear to be superfluous.

Abstraction

It is not immediately obvious from reading

solve x y = anstable!!(x+y)*(modExp (anstable!!x) ip p)*(modExp (anstable!!y) ip p)`rem`1000000007

that it is calculating

$$ \left(\begin{array}{c} x+y \\ y \end{array}\right) = \frac{(x + y)!}{x!\ y!}\mod p $$

I would expect to see

solve x y = modCombination (x + y) y p

modCombination n r p =
  (factorial n) * (modInvFactorial r) * (modFactorial (n - r)) `rem` p'
  where …

In some ways, you come close, but anstable obscures your intention.  Why not ansTable, with the customary capitalization so that it doesn't look like an stable? Why did you rename it from fact in the first place, making it more confusing?  Why is 1000000007 hard-coded at the end, when you could have used p?

What is ip?  1000000005 is a magic number that appears nowhere in the stated challenge.  What about 2000001?  Where did that limit come from?


Selecting an email template and BCC address based on the message type

I would create two new static variables in your class, arrays that contain all options, like

public static $template = [
    self::EMAIL_NEW_SUBSCRIPTION => DataHelper::XML_PATH_SUBSCRIPTION_EMAIL,
    self::EMAIL_CARD_ADD         => DataHelper::XML_PATH_NEW_CARD_ADD_EMAIL_BCC,
    // and so on
];

then setting the email template will be as simple as just one line:

$template = self::$template[self::EMAIL_CARD_ADD] ?? '';

and the same goes for BCC


Don't evaluate docs.length in every iteration - it's constant so it only needs to be evaluated once:

for (var i = 0, n = docs.length; i < n; ++i)

Deference docs[i] into an aliased variable so that you're not repeatedly doing an array lookup into the same element, and don't use strings for keys unless the key is variable:

var doc = docs[i];
var a = doc.a;
...

If the above local variables a through e are only used once, don't bother storing them at all, just put them in as trivial parameters when needed (see below)

Use DOM properties instead of setAttribute function calls when you can:

trEl.id = doc._e;                // instead of 'e'
imgEl.src = 'css/bullet.png';

Don't use inline event handlers:

trEl.addEventListener('dblclick', scan, false);

There's no need to pass the variable e to scan since it's just the clicked element's ID and therefore trivially extracted within the event handler:

function scan(event) {
    var e = this.id;
    ...
}

Use a DocumentFragment to store all of the new elements, and then add the entire fragment into the document in one go, allowing the browser to handle all of the visible DOM changes in one hit:

var rows = document.createDocumentFragment();

for (...) {
    ...
    rows.appendChild(trEl);
}

document.getElementById("search-results").appendChild(rows);


JSON backup to backend server if connection issues

load_be_data

Parameter name is not very descriptive. I'd say that 'file_path' would be better.
Assuming that there is some end user, it would be better to add some descriptive messages for different kinds of exceptions instead of printing the message. Also, it is a good practice to note where the exception was caught. For example, 'Exception with message XYZ was raised in load_the_data'.

get_files

I don't think there is any reason to create a local variable.
Just do :

def get_files():
    return glob("backend_data/*.json")

send_to_be

Again, parameter name is not descriptive.
Is there any reason why do you want to return boolean value instead of raising the error? The 'most pythonic' way is to ask for forgiveness than permission EAFP. In my opinion, what should happen here is that the function should raise an exception when something bad happens or continue when everything is okay. This would help you because you wouldn't need to handle errors separately.

Try this in persist_dump:

try:
    send_to_be(load_be_data(f))
    sleep(300)
except (some exception) as ex:
    print("Exception thrown in ...")
    remove(f)
    sleep(1)

Both "insert" and "update" should be a global variables (so you can possibly reuse them somewhere else).
If create_new_component and update_component are not calculated inside the method, it would be good to make them global variables.

persist_dump

I don't think that it is a good idea to call persist_dump recursively. Assuming that you script will run for a while you are using more memory than you need to. Additionally, at some point in the future you might get RuntimeError: maximum recursion depth exceeded.


Rating the quality of a response based on the number of typos

What happens when @typos.percent_of(@word_length) is exactly 30?  You need to fill in the gaps.  The last case should be an else rather than an elsif, to ensure that all cases are covered.

Is it guaranteed that response_quality will be 1, 2, or 3?  If it's not obvious from context, then there should be an explanatory comment that other values are or aren't possible.

The solution below would reduce the code a bit, but it's not necessarily better than your original approach, which did have the advantage of regularity in the pattern.

def rating
  if @typos.zero?
    case response_quality
    when 1; return 5
    when 2; return 4
    when 3; return 3
    end
  end

  typo_pct = @typos.percent_of(@word_length)
  typo_pct < 20 ? 2 :
  typo_pct < 30 ? 1 :
                  0
end


Without more information what, when asked for a reason for two "time limit exceeded" results, motivated your teacher to mention the possibility to "get" a faster minHeap, you deprive yourself of getting more useful answers. See How to get the best value out of Code Review - Asking Questions
First and foremost, just what is the task timed?
I can't see anything seriously detrimental in your implementation:
I guess a bigger task than, say, handle a batch of insertions and min extractions gets timed, in need of an algorithmic improvement more likely than any tuning.

That said, there are principles like YAGNI, KISS and DRY.
Let me start with the bright side of YAGNI - You Are Gonna Need It:

Documentation. The type that does not get separated from the code:
Documentation in the code

Otherwise, the code presented looks a pretty decent beginner's stab at coding a heap.
Catch:

There are omissions from the deletes:
• not relevant when using an array of primitives as presented in the question:
 Failing to set the reference at the index deallocated to something innocent (as null) does not immediately impede garbage collection, as it gets copied to a lower index. Enter the next delete…

bug in delete(int d):
It replaces element atD with formerLast and restores the heap relations in formerLast and its descendants.
But what about its ancestors?
Not to worry if
1) it ends up at an index abode d or
a) it was a descendant of atD: none of those has higher priority
There are many ways to handle the situation -
I'd prefer just dropping delete(int d) over just calling bubbleUp() or some elaborate handling trying to keep the number of comparisons low.

Room for improvement:

Part of Don't Repeat Yourself is using interfaces:
Define an interface for an, um, PriorityCollection<E> extends Collection<E>.
One advantage is that implementations don't get to reduce visibility of interface methods like isEmpty().
Another is inheriting documentation, too.
• have an E extractTop() return the top priority element it just removed from the Collection
• nowadays, Java interfaces can include unit test code, too.
Keep It Short&Simple meets You Ain't Gonna Need It in fixing arity at 2:
• simpler/shorter code
• fixes a naming issue in d (maximal degree?)
• maximises information in relative position of keys
• doesn't show in the interface, anyway

If and when competent (→ framework) measurements suggest the performance being a problem,
• consider returning to an array of primitives.
• If the cost of comparing elements is high, change tactics in bubbleDown(sink?): find the path along which to sink/bubble down, and look for elements that should stay in place starting from the bottom: this may almost half the number of comparisons.
• an E replaceTop(E replacement) may save considerable work
  it may be useful to additionally have the similar E addAndExtractTop(E addition)


Get a specific value from a big JSON response

Since Swift 1.2, multiple optional bindings and boolean conditions
can be combined to a single if-statement. This helps to avoid the
"Swift if-let pyramid of doom". In your case that would be

if jsonResult.value(forKey: "status") as! String == "OK",
    let routes = jsonResult.value(forKey: "routes") as? NSArray,
    let legs = routes.value(forKey: "legs") as? NSArray,
    let duration = legs.value(forKey: "duration_in_traffic") as? NSArray {

    for i in 0..<duration.count {
        let timeDuration = duration[i] as! NSArray
        if let time = timeDuration.value(forKey: "value") as? NSArray {
            print("Current Time: \(Int(time[0] as! NSNumber)/60) Min")

        }
    }
}

and reduces the maximal nesting level by three.

There are two "forced unwraps" in your code:

let jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

and

if jsonResult.value(forKey: "status") as! String == "OK",

which can cause a program termination at runtime. Better use
optional casts. In the second case that would simply be

if jsonResult.value(forKey: "status") as? String == "OK",

because optionals and non-optionals can be compared.

The JSONSerialization.ReadingOptions.mutableContainers option
is not needed because you are not modifying the returned dictionaries
or arrays.

You are using value(forKey:) a lot. This is a method from the
Key-Value Coding protocol, and is often not what you need. In

let routes = jsonResult.value(forKey: "routes")

you are simply retrieving a dictionary value, that is:

let routes = jsonResult.object(forKey: "routes")

In

let legs = routes.value(forKey: "legs")

you are mapping the routes array to a new array legs. This is
Key-Value coding, however it can be confusing, in particular in this
case where legs would be an array of arrays. This makes duration
and timeDuration nested arrays as well, and is the reason why
you have to subscript time[0] finally. If you are interested
in the first route only, then it is easier to extract the first
element of routes and continue to work with that.

Generally it is preferred to use native Swift type instead of
Foundation types, e.g. [Any] (or a more specific type) for an array,
or [String, Any] for a dictionary. Compare
Working with JSON in Swift from the Swift blog for more information.

Instead of

for i in 0..<duration.count {
    let timeDuration = duration[i]
    // ...
}

you can simpler write

for timeDuration in duration {
    // ...
}

Putting it all together, I would write the code like this:

let jsonResult = try JSONSerialization.jsonObject(with: data)

DispatchQueue.main.sync {
    if let jsonDict = jsonResult as? [String: Any],
        jsonDict["status"] as? String == "OK",
        let routes = jsonDict["routes"] as? [[String: Any]],
        let route = routes.first,
        let legs = route["legs"] as? [[String: Any]] {

        for leg in legs {
            if let duration = leg["duration_in_traffic"] as? [String: Any] {
                if let time = duration["value"] as? Int {
                    print("\(time / 60) Min")
                }
            }
        }
    }
}

Note how duration["value"] can be conditionally cast to  an Int
without an intermediate NSNumber.

Finally you can factor the extraction of the duration data into
a separate function:

func durations(from directions: [String: Any]) -> [Int]? {
    guard directions["status"] as? String == "OK",
        let routes = directions["routes"] as? [[String: Any]],
        let route = routes.first,
        let legs = route["legs"] as? [[String: Any]]  else {
            return nil
    }

    return legs
        .flatMap { $0["duration_in_traffic"] as? [String: Any] }
        .flatMap { $0["value"] as? Int }
}

which can then be used as

if let directions = (try JSONSerialization.jsonObject(with: data)) as? [String: Any],
    let durations = durations(from: directions) {
    DispatchQueue.main.sync {
        for time in durations {
            print("\(time / 60) Min")
        }
    }
}

Here flatMap() is used to map each "leg" to its duration,
this is essentially what you did with value(forKey:) in your
original code.


In-place reversal of a singly linked list

You don't use delete after allocating nodes with new, resulting in a memory leak.  As a general rule, delete should be used in the same way new was used.

In this case, have an identical for loop and use delete on each node:

for (int i=0; i<10; i++) {
    delete n;
}

With these two loops, you might as well have a constant to hold the number of nodes to use, so that you can make sure the same number is used.
You don't need to have return 0 at the end of main().  Reaching the end implies successful completion, and the compiler will insert this return for you.


"Sequence full of colors" challenge on HackerRank

step does two things: (1) step to the next state, and (2) check that the state is valid. Its name suggests only the first meaning. The repetition of wrapValidInJust suggests that they can be separated.

Instead of == you can use pattern-matching.

isgood :: String -> Bool
isgood = isValidFinal . foldM (check . step) (0, 0)
  where

    step (x, y) 'R' = (x-1, y)
    step (x, y) 'G' = (x+1, y)
    step (x, y) 'Y' = (x, y-1)
    step (x, y) 'B' = (x, y+1)

    check (x, y) = if abs x <= 1 && abs y <= 1 then Just (x, y) else Nothing

    ...

Another reason step is hard to read is that you need to keep track of differences, which complexifies the meaning of x and y. You can just as easily count the four colors independently and compute the difference only in check. This is also the opportunity to use a record or a map to make the update syntax more uniform:
data RGBY = RGBY { r, g, b, y :: Int }

isgood :: String -> Bool
isgood = isValidFinal . foldM (check . step) (RGBY 0 0 0 0)
  where

    step x 'R' = x { r = r x + 1 }
    step x 'G' = x { g = g x + 1 }
    step x 'Y' = x { y = y x + 1 }
    step x 'B' = x { b = b x + 1 }

    check x = if abs (r x - g x) <= 1 && abs (y x - b x) <= 1
      then Just (x, y) else Nothing

    ...


The first most glaring problem I see is sleep(2).  We really don't want to be doing this, particularly with Objective-C programs.  The main reason I add emphasis on Objective-C is because virtually every program written in Objective-C is either an OSX or iOS app with a GUI.  And in these cases, the main thread is the thread that handles the GUI.  You'll also be writing the bulk of your code on the main thread--certainly until you start figuring out multithreading.  Everything defaults on the main thread.

And a call to sleep(someNum) on the main thread means that the user only has one way of interacting with our program for someNum amount of time--by closing it out.

There are other ways to delay actions in our code without putting the entire thread to sleep.  In the case of this simple code, there's no interaction anyways, but in the future, you will run into this problem.

For the most simple example of how to point you in the right direction, Objective-C offers performSelector:withObject:afterDelay: (though this requires the use of objects & methods).

But there's also a non-OOP way of executing code after delays in Objective-C (it's a lot messier than performSelector:withObject:afterDelay:, and I had to look up the exact syntax...).  It makes use of code blocks.

A code block is similar to a C-style function, but we have a variable that is a pointer to it (yes, I know C and other languages have "function pointers"--we call them blocks in Objective-C).  Anyway, the syntax for executing code in a block after a delay looks like this:

int delay = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);

dispatch_after(delay, dispatch_get_main_queue(), ^{
    // any code you want executed after delay
    // in this case, delay is 2 seconds
});

Where 2 is the number of seconds you want to delay, and everything else is built-in C or Objective-C constants/functions.


split returns a list already, so you don't need the list call
unless you really want to reimplement the reverse method, use it, or the function reversed if you want a return value instead
concatenating strings is much easier with " ".join(...)

So this can then be compressed to

# Alex Grattan
# 17/10/14

message = input("Enter your message to have it printed backwards:")
print (" ".join(reversed(message.split())))


ADT Stack with a doubly circular linked list

The class doesn't expose a method that let's users benefit from the circular property.
The enq, deq, front, empty methods could work just fine without the circular property.
As such, it's an unnecessary complexity.
If you want to use a circular linked list,
then expose some methods that need or benefit from the circular property.

The class QueueCircularDLL<T> implements the ADTQueue<T> interface,
but it's not clear which methods belong to the interface.
It's strongly recommended to make that clear using the @Override annotation.

In front, instead of returning null when the list is empty,
a more common practice is to throw java.util.NoSuchElementException,
as done by the various linked list and queue implementations in the JDK.


HackerRank Code "Determining DNA Health"

The Algorithm
This has a bad worst-case complexity,
for (int i = first; i <= last; i++) {
    for (int index = d.indexOf(genes.get(i)); index >= 0; index = d.indexOf(genes.get(i), index + 1)) {
        sum += Integer.parseInt(health.get(i));
    }
}

Consider a strand "aaaaaaaaaaaaaaaaaaaaaaa" and genes {"aaaaa", "aaaaa" ...
Now for every gene, at almost every position of the strand, there will be a string comparison. The amount of character comparisons is approximately TotalSize(genes) * strand.length, so that can easily lead to a TLE if the data is a little annoying, which of course it will be.
Here are a couple of other techniques you could try,

Building a suffix array and LCP array for the strand, so for every gene the number of occurrences in the strand can be counted in O(geneLength + log strandLength) (so without even visiting the occurrences!) by binary-searching for the start and end of the contiguous range in the SA that contains all those occurrences. A suffix trie is good as well but more dangerous for the memory footprint. SA and suffix trie can both be constructed in linear time (in the length of the string), but it is non-trivial to implement. The LCP array can be given as a secondary result of SA construction (depending on the algorithm) or otherwise created in linear time as well by using the SA.
Building a trie with the healthy genes, then go over the strand while descending down the trie, backing up as needed. This has a bunch of edge-cases that need to be considered. There are slow cases, for example if a gene is very big (half the length of the strand) and matches nearly everywhere (for example if the strand and gene are both only the same character), which I think is still a quadratic case. Some additional trickery may be able to work around that.

The solutions that I could find quickly seemed to use the second approach, but I think the first one would be a "safer" choice in terms of avoiding a quadratic worst-case complexity, though the second one seems useful enough in practice (it has been successfully used, after all).
Unnecessary Map
When the keys of a map are a dense and non-changing range of integers like this,
Map<Integer, String> genes = new HashMap<>();
for (int i = 0; i < n; i++) {
    genes.put(i, genesItems[i]);
}

Using an ArrayList or plain array is a little more efficient and maybe more convenient (the array genesItems is already available anyway). Though of course this does not significantly contribute to TLEs in competitive programming.
The skeleton code under the problem uses arrays.
Avoid re-parsing
The inner loop contains Integer.parseInt(health.get(i)), but that should usually be done up front when reading in the problem data. The skeleton code under the problem parses up front.


Scraper for downloading and saving images from web page

I would focus on the following things specifically:

variable and function naming:

use lower_case_with_underscores naming convention
what if we rename title to movie and movie_title to title - I think that would be a bit more descriptive
response should probably be named page_source since it is not a Response instance but already the text of the response

use of spaces and line breaks:

according to PEP8 coding style, you should have 2 line breaks between the functions
when passing a keyword argument to a function, don't put spaces around the =

code organization:

I would use a class to share a web-scraping session and have it parameterized with a url and a download directory. I think that would be more modular.

Improved code:

import os

import requests
from lxml import html

class ImageScraper:
    def __init__(self, url, download_path):
        self.url = url
        self.download_path = download_path

        self.session = requests.Session()

    def scrape_images(self):
        response = self.session.get(self.url).text

        tree = html.fromstring(response)
        for movie in tree.xpath('//div[@class="mv"]'):
            title = movie.findtext('.//h3/a')

            image_url = "https:" + movie.xpath('.//img/@src')[0]
            image_name = image_url.split('/')[-1]

            self.save_image(title, image_name, image_url)

    def save_image(self, movie_name, file_name, item_link):
        response = self.session.get(item_link, stream=True)

        if response.status_code == 200:
            with open(os.path.join(self.download_path, file_name), 'wb') as image_file:
                for chunk in response.iter_content(1024):
                    image_file.write(chunk)

        print(movie_name, file_name)

if __name__ == '__main__':
    scraper = ImageScraper(url="https://www.yify-torrent.org/search/1080p/",
                           download_path=r"C:\Users\ar\Desktop\mth")
    scraper.scrape_images()


I'm not able to review the functionality of the code currently, but to address your concerns:

In dequeue(), rather than returning the node, add a parameter (pointer to QueueNode) to store that node in. This is similar to functions like memcpy(3), strtoul(3) (end pointer), and so on. It allows you to return an error value however you wish.

int dequeue(struct Queue *queue, struct QueueNode *out);

If the queue is empty, don't bother modifying out, and just return an error code.

I would also avoid printing & exiting from within the queue's functions upon error. Instead return some kind of error value and leave it for the user to check.

For example, consider if malloc fails. The user may want to check errno, or use a fallback data structure.

int enqueue(struct Queue *queue, int num) {
    struct QueueNode *queuenode = malloc(sizeof(struct QueueNode));

    if(queuenode == NULL){
        return -1;
    }

    queuenode->data = num;
    queuenode->nextNode = NULL;

    if(!queue->priorNode){
        queue->priorNode = queuenode;
    }

    if(queue->lastNode){
        struct QueueNode* temp = queue->lastNode;
        queue->lastNode = queuenode;
        temp->nextNode = queue->lastNode;
    } else {
        queue->lastNode = queuenode;
    }

    return 0;
}


Trying for an efficient and readable merge-sort implementation

The single most important advantage of merge sort is its stability. The elements compared equal retain their original order. Your code loses stability. If l[i] compares equal to r[j], the latter is merged first.

Your code assumes closed ranges (that is, end is a valid index). That leads to some unpleasant fiddling with indices. Semi-open ranges (that is, end is the first invalid index) are much cleaner to deal with.

size_t middle = (start+end)/2; is vulnerable to arithmetic overflow. Consider
  size_t middle = start + (end - start)/2;

Avoid VLAs. They are vulnerable to stack overflow, and besides, they are not supported by c++ standard.

No naked loops, please. Every loop implements an algorithm, and therefore deserves a name. The before and after the actual merge in fact implement copy.

I don't see anything resembling c++.  The entire code is plain old c.


This bit is a little too much to digest:

this.Controls.Add(new Xml {
    DocumentContent = new XElement("keys",
                            from key in this.Keys
                            select new XElement("key",
                                        new XAttribute("name", key),
                                        this[key])).ToString(),
    TransformSource = DumpKeyValuePairs.XsltPath,
});

The trailing comma is annoying, but the LINQ query syntax is a little bit overboard. The instruction is doing too many things.

Wouldn't this be clearer?

Controls.Add(xml);

There's no need to qualify XsltPath with the DumpKeyValuePairs type, even if the field is static - you're in the same type anyway. Actually, this:

static string XsltPath = "~/Controls/DumpKeys.xslt";

Should really be this:

private static readonly string XsltPath = "~/Controls/DumpKeys.xslt";

Now, in order to turn that LINQ jam into a simple Controls.Add(xml); instruction, things need to happen.

var xml = new Xml
{
    DocumentContent = CreateDocumentContent(),
    TransformSource = XsltPath
};

The CreateDocumentContent() method could be where that LINQ query lives.

private string CreateDocumentContent()
{
    return new XElement("keys", Keys.Select(CreateKeyElement)).ToString();
}

And that CreateKeyElement method group, extracted to its own one-liner method again, makes it pretty clear what's going on:

private XElement CreateKeyElement(string key)
{
    return new XElement("key", new XAttribute("name", key), this[key]);
}

Cramming all these functions into a single instruction is making maintenance much harder than it needs to be.

abstract protected string this[string index] { get; }

Maybe it's just me, but in my mind an index is an int that specifies the position of an item in a collection. What you really have here is a string name for accessing the values in some dictionary; correctly naming the indexer parameter can avoid confusion here.


Speeding up Python depth-first search in large graph

Can anyone see a way I could speed this up

The predicate filtering approach is correct, but slow. It offers little guidance on which branches are worth exploring deeply.

Switch from hard boolean to a scoring approach, so you can sort candidate scores into rank order, which allows deeper exploration of more promising nodes earlier.


React/Redux/Node/Express crud application with a React class component

Sorry you didn't get the position, but perhaps the interviewers/code reviewers were looking for something else or some very specific things.
You cannot, in fact, use useSelector or useDispatch, nor any other react hook as they are only compatible with functional components. Other than that this appears to be clean and readable code, although it does have some redundancy.
Suggestions

The constructor doesn't actually do anything, so it can be removed
All the class functions simply proxy props that are passed, so they, too, can be removed
This is debatable, but IMO you should explicitly map the actions to props that you will use, it makes it clearer what the component can do
The connect HOC's second parameter mapDispatchToProps automagically wraps each actionCreator with a call to dispatch as well
It appears this.props.expenses object shape is identical to the props ExpenseTable takes, so you can spread those in, more DRY

Nit-picky Suggestions

Try to be as precise/explicit when defining proptypes
Consistently use semi-colons
In react only Components are PascalCased, most other variables and objects should be normal camelCased
Destructure props to be more DRY, i.e. much less this.props.X, this.props.Y, this.props.Z. This one is debatable however as the argument against is that not destructuring them it is easy to see what is a prop versus state versus neither. I say you can just look to the top of the function where variables should normally be defined anyway to glean these details.

Component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import ExpenseTable from '../components/ExpenseTable';
import {
    CancelEditing,
    CreateExpense,
    DeleteExpense,
    StartEditing,
    UpdateExpense,
} from '../actions/ExpenseActions';

export class ExpenseContainer extends Component {
    render() {
        const {
            CancelEditing,
            CreateExpense,
            DeleteExpense,
            expenses,
            StartEditing,
            UpdateExpense,
        } = this.props;

        return (

                <ExpenseTable
                    {...expenses}
                    createExpense={CreateExpense}
                    startEditing={StartEditing}
                    cancelEditing={CancelEditing}
                    editExpense={UpdateExpense}
                    deleteExpense={DeleteExpense}
                />

        );
    }
}

ExpenseContainer.propTypes = {
    CancelEditing: PropTypes.func.isRequired,
    CreateExpense: PropTypes.func.isRequired,
    DeleteExpense: PropTypes.func.isRequired,
    StartEditing: PropTypes.func.isRequired,
    UpdateExpense: PropTypes.func.isRequired,
    expenses: PropTypes.shape({
      expenses: PropTypes.string.isRequired, // or number or whatever the specific type is
      subTotal: PropTypes.string.isRequired,
      total: PropTypes.string.isRequired,
    }).isRequired
};

function mapStateToProps(state) {
    return {
        expenses: state.expenses
    }
};

const mapDispatchToProps = {
    CancelEditing,
    CreateExpense,
    DeleteExpense,
    StartEditing,
    UpdateExpense,
};

export default connect(mapStateToProps, mapDispatchToProps)(ExpenseContainer);

A final suggestion would be to just convert ExpenseContainer to a functional component since it doesn't use any of the class-based lifecycle functions.
export const ExpenseContainer = ({
    CancelEditing,
    CreateExpense,
    DeleteExpense,
    expenses,
    StartEditing,
    UpdateExpense,
}) => (

        <ExpenseTable
            {...expenses}
            createExpense={CreateExpense}
            startEditing={StartEditing}
            cancelEditing={CancelEditing}
            editExpense={UpdateExpense}
            deleteExpense = {DeleteExpense}
        />

);

ExpenseContainer.propTypes = { ... };

function mapStateToProps(state) { ... };

const mapDispatchToProps = { ... };

export default connect(mapStateToProps, mapDispatchToProps)(ExpenseContainer);


Get ruby Hash#each to return a built hash

Some notes:

Avoid the pattern init + each + update. Use map or other functional methods.
In Ruby >= 2.1.0 you have Array#to_h. Use Hash[...] in older Rubies.
Use File.join

I'd write:

def get_data(dir)
  newest = get_most_recent_file_numbers(dir)
  $file_prefixes.map do |type, file_prefix|
    path = File.join(dir, file_prefix + "_" + newest[type] + ".csv")
    [type, File.readlines(path)]
  end.to_h
end


Looks pretty clean for me.

the only improvement i suggest, is avoid the animateBack harcode position. Maybe you can save before the animation start, and then, back to the last position.

    containerMove: function() {
        var mO = morphObject;
        mO.overlay.fadeIn();

        startPosition = {
            top: morphObject.top(),
            left: morphObject.left(),
            width: morphObject.width(),
            height: morphObject.height(),
            marginLeft: ....
        };

        mO.container.animate({
            top: 300,
            left: '50%',
            width: 600,
            height: 400,
            marginLeft: -300
        },
        400,
        function() {
                mO.content.fadeIn();
                span.fadeIn();
                mO.close();
        });

    },
    animateBack: function() {
        var mO = morphObject;
        mO.container.animate(startPosition);
    }

Also, for my suggestion is a little anoying using a literal object { }, you can use a constructor new function () {} is better for set properties and  handle scopes.


I think this is a good exercise for trying out OOP design.  When I was learning OOP I found that working with real-life objects helped a lot and slowly I started getting use to objects that represented abstract concepts.  In this example you have a mixture, real-life dominoes and abstract concepts such as the 'Game' object.

The Domino Class is a good candidate for an immutable object.  It is often a good idea to create immutable objects when you can as this can be a powerful mechanism to stop erroneous state from being accidentally recycled.

There seems to be quite a bit of duplication going on within the Domino Class.  This can sometimes lead to confusion when debugging.  If you are debugging, and the name of a domino says "3,2" but the Head and Tail show 4 and 1 then you are left not sure about what happened.  Best to try and avoid this from happening.

I think it is also a good idea to make sure that all the logic that represents dominoes is wrapped up in the Domino class.  This will help to avoid abstraction leakage.  It is fairly obvious that a domino has a head and a tail and this is exposed via your properties but it may not be obvious how the domino name should be formatted (e.g. should it use a comma 3,4 or a colon 3:4) or how a domino's weight is determined.  If you have to evaluate the weight of a domino outside of the domino class then this might be considered as abstraction leakage.

Putting these concepts together, here is how I would program the Domino Class:

// Represents a tile used in a domino game.
// This class is designed to be immutable.
public class Domino
{
    // Private constructor means that dominos can
    // only be crated from a static method in this class.
    private Domino(string name, int weight)
    {
        // domino name can either be in the format H,T or H:T
        string[] nameParts = name.Split(',', ':');
        if (nameParts.Length != 2)
        {
            throw new ArgumentException("Invalid name format.");
        }

        try
        {
            Head = Int32.Parse(nameParts[0]);
            Tail = Int32.Parse(nameParts[1]);
        }
        catch
        {
            throw new ArgumentException("Invalid name format.");
        }

        Weight = weight;
    }

    // The properties of the domino class have a private set
    // because this class is designed to be immutable.
    public int Head { get; private set; }
    public int Tail { get; private set; }
    public int Weight { get; private set; }

    public bool IsDouble { get { return (Head == Tail); } }

    // Avoid duplicating the head and tail values by
    // generating the name every time it is needed.
    // This will be quick enough that it won't impact
    // performance.  Only worry about performance once
    // it starts to become a problem.
    public string Name { get { return Head.ToString() + "," + Tail.ToString(); } }

    public override string ToString() { return Name; }

    // Returns a full collection of shuffled dominos
    // this static method is part of the domino class
    // and so it can use the private constructor.
    public static DominoCollection GetAll()
    {
        string[] tiles = new string[]
        {
            "0,1","0,2","0,3","0,4","0,5","0,6",
            "1,2","1,3","1,4","1,5","1,6",
            "2,3","2,4","2,5","2,6",
            "3,4","3,5","3,6",
            "4,5","4,6",
            "5,6",
            "0,0","1,1","2,2", "3,3", "4,4","5,5","6,6"
        };

        DominoCollection dominos = new DominoCollection();
        for (int i = 0; i < tiles.Length; i++)
        {
            dominos.Add(new Domino(tiles[i], i));
        }

        dominos.Shuffle();
        return dominos;
    }
}

I would define the DominoCollection class to make as much use of the built-in features as possible by inheriting it from the generic collection class:

public class DominoCollection : Collection<Domino>
{
    // shuffels the dominos in this collection
    public void Shuffle()
    {
        Random r = new Random();

        int n = Count;
        while (n-- > 1)
        {
            int k = r.Next(n + 1);
            Swap(k, n);
        }
    }

    // swap the domino in index 1 with the domino in index 2
    private void Swap(int i1, int i2)
    {
        Domino temp = this[i1];
        this[i1] = this[i2];
        this[i2] = temp;
    }
}

Now you can get the full set of dominoes like this:

DominoCollection dominos = Domino.GetAll();

This still might not be considered ideal and there maybe some who suggest that the Domino.GetAll() method should not be a static method of Domino but instead should be in the collection class (similar to your original code) but at least you will have considered the alternatives and thought about the concept of abstraction leakage.


Gives a live view to a changing file on server

Global variables
In side your function readUtilLog, in both cases of your if conditional, you have this:
d=data1 + data;

or this:
d=data;

Why are you using the d variable here? No where else in your code did you write var d, so when one of these conditional cases first runs, you are going to create a global d variable, which is just bad practice.
Since all you are doing with that d variable is setting an element's value to it in the very next line, then why not just set the element's value immediately?
That would look like this:
$('textarea#livewindow').val(data1 + data);

and:
$('textarea#livewindow').val(data);

OC$ (obsessive compulsive $)
Every 5 seconds, no matter what conditional passes, you do this:
$('textarea#livewindow')...

This magical $ function does quite a lot work under the hood to find an element. Therefore, this can be a pretty huge performance impact, especially if you are calling it every 5 seconds.
Your code would benefit a lot speed and efficiency wise if you store the this element in a variable, and then access it's .val through the variable.
var liveWindow = $("textarea#livewindow");

Now, when you are accessing the variable(for example):
liveWindow.val(data);

setTimeout vs setInterval
I have two thoughts on why this is bad.

Possible bad way 1
It's quite dangerous that you are using setInterval as a timer for calling readUtilLog every 5 seconds, and here's why:
After you have created an interval with setInterval, the interval now is going to create a new thread running the readUtilLog every 5 seconds even if the last readUtilLog has not yet completed.
And that's the problem: completing the last readUtilLog. The readUtilLog function has two very intensive and performance reducing tasks: XHR requests.
XHR requests can take quite a while. That means that, as these requests are taking their time, the interval could be spawning new threads background, which will eventually run your browser dry of threads and possibly cause it to crash.

Possible bad way 2
The same thing as above, only a thought on $.get.
In vanilla JavaScript, XHR requests occur asynchronously. That means that, every time you launch an XHR request, you are creating a new thread for the return.
Now you have two sources spawning threads: your interval, and the function that your interval runs.
That means that every 5 seconds, your interval is going to create a thread running readUtilLog, which is going to create a thread to handle the XHR request, which could potentially create another thread for another XHR request.
That is just complete madness, and could easily run your browser dry of threads potentially crashing it.

Solution
Use setTimeout.
As an example, this is what your code would look like if you were to switch to setTimeout:
function foo() {
    ...
    setTimeout(foo, 5000);
}

foo();

Why is this better? This will wait for the last thread to complete before starting a new one.
If there is an intensive function running in foo that will take longer than 5 seconds, who cares? That setTimeout isn't going to run until the end of the function.
This prevents thread build-up.

Nit-picks
There are just small things in your code that I'd like to point out.

setInterval(function(){readUtilLog();}, 5000);

Since you aren't trying to pass any parameters to readUtilLog, wrapping it an anonymous function is unnecessary:
setInterval(readUtilLog, 5000);

if (data.length < 256000){

Where did the 256000 come from?. You should create a constant at the top of your code and use that constant instead of just the straight-up value 256000.
var CONSTANT_NAME = 256000;

CONSTANT_NAME is not a good name; I could not derive a good name out of context.


Exists Method Implementation for Multidimensional Array in C#

You can simply use the LINQ Enumerable.Any extension Method.
bool result = array4.Cast<int>().Any(x => x == 1);

This works for any collection implementing IEnumerable<T> and also for enumerations created algorithmically by C# Iterators.
According the the C# Programming Guide (Arrays):

Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

This statement is, however, misleading, since we need to cast the array here. Obviously, we only have the access to the non-generic interface IEnumerable.
LINQ Extension methods found in the Enumerable Class apply to IEnumerable<T> or IEnumerable.


Leaky abstractions
A specific implementation should not leak into an abstraction. By making IUnitOfWork extend IDisposable, that's what you're doing:

public interface IUnitOfWork : IDisposable

The goal of the abstraction, is to abstract implementation details away - in this case, the fact that you're using NHibernate. You had a specific implementation in mind when you created this interface, and that implementation leaked into the abstraction. What if you wanted to implement an IUnitOfWork that worked off a List<T>, for testing purposes?
Not all implementations of IUnitOfWork need to implement IDisposable - better leave that up to the implementation:
public class NHibernateUnitOfWork : IUnitOfWork, IDisposable
{
    private readonly ISession _session;

    /* implementation */

    public void Dispose()
    {
        _session.Dispose();
    }
}

public class TestUnitOfWork : IUnitOfWork
{
    /* implementation */
}

IQueryable
Every single implementation of the Repository & Unit of Work patterns I have seen, were different. Every single one.
Without seeing what your implementations and client code looks like (/how you're using these interfaces), it's very hard to tell whether you've done something wrong.
For one thing, exposing IQueryable<T> is leaking the query outside your repository, making it possible for client code to call IRepository<T>.FindAll() and then from there, add a Where clause or Join on another repository, which means the repository completely loses control of query materialization, which [unless I missed something] defeats its purpose.
By exposing a IRepository<T> GetRepository<T>() method on your IUnitOfWork, you're also making it possible for the unit of work's clients to own the materialization of the query.
Whether that's good or bad, entirely depends on your architecture; I cannot tell just from the interfaces... I can only raise a flag.


Calculating the maximum drawdown of a set of returns

You are correct to point out that your implementation is terribly inefficient compared to most built-in Numpy operations of similar complexity.  100X speedup would be reasonable for large arrays once you eliminate the python loop.  It would be trivial to replace your python loop with some Numpy indexing or broadcasting if it weren't for the pesky draw_series[r-1] = -(1 - max_draw) line which operates on the next-to-be-computed item in the array.  This is analogous to Numpy's accumulate but obviously there's no implementation of it for your particular algorithm.  You have three options as I see it:

Study your problem hard and see if you decompose it into numpy-only
accumulate and regular operations.
See if your algorithm can be expressed as a compiled numexpr
expression.
Compile this function using Cython, f2py or ctypes

One minor improvement is to replace returns = returns + 1 with returns += 1 which will operate in-place and avoid re-allocating the returns array.

Hope this helps.  good luck.


cache with least accessed items eviction

I don't really feel subclassing a built-in data structure and defining your custom get() and set() methods is a good idea. One of the downsides of the current implementation is that if I would do self.cache[key] = value - this will not go through the cache's set() method and, hence, will not go through the "eviction" check at all. If you are subclassing a dictionary or an ordered dictionary, properly define the __getitem__() and __setitem__() magic methods instead of writing your custom get() and set() on top of it.

Also check this implementation that has a simpler wrapper, but uses a "proxy" "cached function" helper class.

And, here is the source code of the Python's functools.lru_cache for the reference.

Some other minor notes:

use print() as a function for Python-3.x compatibility


I find your code fairly complicated. Especially the part where you split the list into sequences of sublists of equal elements is a bit convoluted. Here's what you're doing in pseudocode:

given a comparator,
for each element in the list:
    for each sublist:
       if per the comparator, the element is equal to an element in that sublist:
           add the element to the sublist,
           continue with next element
    if no sublist matched:
        add a new sublist containing that element

The most straightforward way to implement that in Java is using a labeled loop. Using that, we can continue with the next element in the outer loop once a match was found. We do not have to maintain a matchFound variable:

List<List<T>> subCollections = new ArrayList<>();

element:
for (T element : list) {
    for (List<T> subList : subCollections) {
        if (comparators[0].compare(element, subList.get(0)) == 0) {
            subList.add(element);
            continue element;
        }
    }
    // no sublist matched
    List<T> newList = new ArrayList<>();
    newList.add(element);
    subCollections.add(newList);
}

There's also no need to use a lastIndex here.

Unfortunately, what you are doing is tremendously inefficient. You re-sort each list multiple times, and invoke each comparator unnecessarily often. You are more or less implementing a crazy inefficient multi-level quicksort that partitions into multiple parts per level.

The better solution would be to create a custom comparator that loops through the list of comparators and stops when they are no longer equal:

class MultiComparator<T> implements Comparator<T> {
    private final List<Comparator<T>> comparators;

    public MultiComparator(List<Comparator<? super T>> comparators) {
        this.comparators = comparators;
    }

    public MultiComparator(Comparator<? super T>... comparators) {
        this(Arrays.asList(comparators));
    }

    public int compare(T o1, T o2) {
        for (Comparator<T> c : comparators) {
            int result = c.compare(o1, o2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }

    public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
        Collections.sort(list, new MultiComparator<T>(comparators));
    }
}

(untested)


Are my one-method (and a couple attribute) classes overkill?

You are correct - in this case classes are an overkill.

Think of classes as nouns, and methods as verbs. Functions do things, while classes are those actual things.

For instance - compare DataFrameBuilder (noun) with build_data_frame (verb). Which makes more sense? Which describes the business logic better? I think the second, since the focus here on building data, and not on a builder itself.

I think I picked up the idea from Steve Yegge's post "Execution in the Kingdom of Nouns" (great article, you should read it when you have time).


Return the best factors of a whole number

I don't understand the logic specifically

allFactors(15) = 1,3,5,15
bestFactors(15) = 3,5

allFactors(7) = 1,7
bestFactors(7) = 7

allFactors(1) = 1
bestFactors(1) = 1

allFactors(0) = empty
bestFactors(0) = empty

allFactors(-15) = empty
bestFactors(-15) = empty

All of your Single variables can be Long - single is hardly used in VBA.

Your naming could use some improvement:

Sub TestForFactors()

    Dim allFactors As Collection
    Set allFactors = New Collection

    Dim bestFactors As Collection
    Set bestFactors = New Collection

    Set allFactors = GetFactors(15) 'Change number - will return all factors.
    Set bestFactors = GetBestFactors(15) 'Change number - will return best factors.

    Debug.Assert False

End Sub

That's easier to understand.

Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names. Variable names - give your variables meaningful names. Instead of

NumToFactor = numberToFactor
Count = count
Factor = factor
tmpCollection = getFactorsCollection
tmpFactors = bestFactorsCollection
FactorNums = factorNumbers
FirstFactor = firstFactor

x,y,z = ??

All of your procedures are Public - they should be Private unless needed to be Public.

All of your function arguments are being passed ByRef - they should be passed ByVal

In terms of your logic, you're looping through every number to find factors. There are certain rules you know you can abide by
 - things that end with 0 or 5
 - no primes end in an even number
 - If 5 is a factor, no need to test any multiples of 5 etc

You're using a lot of Collections - https://stackoverflow.com/questions/10579457/why-use-arrays-in-vba-when-there-are-collections you might want to try arrays or dictionaries.

In GetFactors what is Count doing? It's set to 0 then.. never used.

This is one heck of an arrow

    If FactorNums.Count = 1 Or FactorNums.Count = 2 Then
        tmpFactors.Add FactorNums(FactorNums.Count)
    Else
        For x = FactorNums.Count - 1 To 1 Step -1
            If FactorNums(x) ^ 2 = NumToFactor Then
                tmpFactors.Add FactorNums(x)
                tmpFactors.Add FactorNums(x)
                Exit For
            Else
                For y = x To 1 Step -1
                    FirstFactor = FactorNums(y)
                    For z = y - 1 To 1 Step -1
                        If FirstFactor * FactorNums(z) = NumToFactor Then
                            tmpFactors.Add FirstFactor
                            tmpFactors.Add FactorNums(z)
                            Exit For
                        End If
                    Next z
                    If tmpFactors.Count = 2 Then Exit For
                Next y
            End If
            If tmpFactors.Count = 2 Then Exit For
        Next x
    End If

And a lot of Exit For - there's four of those against 3 For Next loops - hard to follow which exits what loop.


Following implementation provides generic solution, which mimics other foundation methods like filter, map etc. Though extends Array instead of SequenceType.

Main benefit from this solution comparing to the original provided by Ashley Mills is that it does not mutate an array.

extension Array {

    func trim(@noescape predicate: (Element) throws -> Bool) rethrows -> [Element] {
        guard let
            start = try (indexOf { try !predicate($0) }),
            end = try (reverse().indexOf { try !predicate($0) }) else {
                return []
        }
        return Array(self[start..<end.base])
    }

}

Usage Example:

persons.trim { $0.isMale }


Descriptive names

    private static void printSortedArr (int[] arr) {

I don't like these names.  I would rather write out array if that's what's being said.  E.g.

    private static void printSortedArray(int[] numbers) {

Now I don't have to figure out that Arr is short for array.  And numbers is more descriptive than array anyway.

Favor arrays over numbered variables

        int count0 = 0, count1 = 0, count2 = 0;

So here you have three variables that hold different values based on their names.  However, we have a data type that enforces that relation, the array.

As proposed here:

    private static void printSortedArray(int[] array, int maxElement) {
        int[] counts = new int[maxElement + 1];

Now you have a more reusable method.  It's no longer limited to just sorting an array of 0s, 1s, and 2s.  It can sort any array of 0, ..., maxElement.  Further, it is now self-organizing.  Instead of

            if (elem == 0) {
                count0++;
            }
            else if (elem == 1) {
                count1++;
            }
            else {
                count2++;
            }

You can just say

            counts[element]++;

You no longer have to expand the if/else each time you add a new element value.

In a comment, you said

  Isn't storing the values in an array a space overhead?

The difference between your original three variables and this array is the length variable.  Other than that, both use the same space.  The cost of the extra variable is more than made up with the reduction in errors from replacing the if/else monster with the simple array update.

For example, your original has a bug if the array contains numbers other than 0, 1, or 2.  It silently counts any other number as a 2.  The revised version would throw an array out of bounds exception in that case, and it will do so without any added checking on your part.

In another comment, you say

  I thought that according to the problem statement, there was no explicit need to store the sorted elements in the array causing me to just print them. Also, I thought that using an array would be a space overhead.

In that case, the array duplicated the original array and was a space overhead.  But the thing that you gain there is that you can reuse the created array for other things.

You are correct in pointing out that the current problem statement does not require separate action and display.  What we are trying to tell you though is that in the real world, problem statements change.  Your code is fragile.  If the problem statement changes, you have to rewrite it.  We want to encourage you to write robust code that will continue to work even if the goal changes.  This is because the goal in a project tends to change a lot.

Donald Knuth said:

  The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.

You are generally going to be better off writing for good engineering principles and then, in those rare instances where it matters, optimizing.  Don't fall in love with your optimized solutions, as user requirements will stomp all over them.

What if you were asked to print out the counts for each element?  You would have to modify this code to do that.  However, if your method was

    // numbers can only contain values from 0 to maximumValue
    private static int[] countElementsByValue(int[] numbers, int maximumValue) {
        int[] counts = new int[maximumValue + 1];

        for (int element : numbers) {
            counts[element]++;
        }

        return counts;
    }

Then you could easily display the counts or the array.  Or both.  Because you have that information right there.  With the original method, you would either need to rewrite it like this or recount the elements to do that display.  Because the original method discards that information immediately.  Or you could modify the original method.  But then what happens when someone says that they want just the array without the counts?

In general, we prefer small methods that do one thing and only one thing over more complicated methods that do multiple things.  This is especially true about mixing generation and display.  That fails quite often, as we have found that requiring multiple displays over the same basic data is quite common.  So there is a specific instance (don't mix generation and display) of the more general rule to keep difference actions separate.

Your original method might become something like

        int[] counts = countElementsByValue(numbers, 2);
        int[] sorted = expandCounts(counts);
        System.out.println(Arrays.toString(sorted));

Note how the last line doesn't have to know that it's displaying a sorted array.  It doesn't care.  Whatever the array is, it displays.

We could probably improve performance by writing a special display routine that works off the counts directly.  But it wouldn't be that much of an improvement.  And most of the time, it won't matter.  With your example input, the time difference is going to be trivial.  We'll spend more time compiling the program than running it.

Performance

If you're really worried about storage performance, then why read the data into an array at all?

            String line3 = br.readLine();
            String[] inps = line3.split(" ");

            for (int j = 0; j < size; j++) {
                arr[j] = Integer.parseInt(inps[j]);
            }

            printSortedArr(arr);

Could be

            for (String token : br.readline().split(" ")) {
                 char digit = token.charAt(0);
                 if (digit == '0') {
                     System.out.print("0 ");
                 } else {
                     counts[digit - '0']++;
                 }
            }

            int value = '0';
            for (int count : counts) {
                while (count > 0) {
                    System.out.print(value + " ");
                    count--;
                }

                value++;
            }
            System.out.println();

One reason not to do this is that, counter-intuitively, it is actually slower to mix input and output like this than to use more storage.  In particular, System.out.print is not high performance with printing two characters at a time.  You'd usually be better off using a StringBuilder to generate the string and then outputting that.

Why use readline?  The resulting array could potentially be huge, and you are committing yourself to two arrays, one of strings and one of integers.  Consider

            int read = br.read();
            while (read >= 0) {
                if (read != ' ') {
                    counts[read - '0']++;
                }

                read = br.read();
            }

This saves us two arrays and a string at the cost of one smaller array.  If you are really space constrained, mixing input and generation like this is better than mixing generation and output.

Of course, it is quite possible that this is slower than your original.  That's a common trade-off, speed for space.

Then with Java 8, you can use something like (from Stack Overflow):

            for (i = 0; i < counts.length; i++) {
                String value = Integer.toString(i);
                System.out.print(String.join(" ", Collections.nCopies(counts[i], value)));
            }
            System.out.println();

This will display with only four print statements.

Or if that uses too much space (it's unclear to me if it creates a temporary collection or not), stick to your original output method.  That may be slow, but it uses very little space.

Remember though, that this kind of optimization is something you should do after you establish that you need it.  Most of the time this is going to be unnecessary and it may even be counter-productive.  E.g. if you're worrying about space constraints when you are actually time constrained.


You're on the right track.  Good job using the try-with-resources block for the BufferedReader.  You could use a Scanner instead for convenience.  (You could even use Scanner.nextInt(), but it would work slightly differently: the newline in the input would be optional.)

The variables antenna and eye can be local to main(), and therefore should not be static members of the class.

In Java, a common naming convention for methods that return a boolean is isSomething() or hasSomething().  In this case, though, maybeSomething() seems more appropriate.

It is rarely necessary to write return true; or return false; explicitly.  Usually, you would be better off returning a boolean expression.

import java.util.Scanner;

public class Alien {
    public static void main(String args[]) {
        try (Scanner in = new Scanner(System.in)) {
            System.out.println("How many antennas?");
            int antenna = Integer.parseInt(in.nextLine());

            System.out.println("How many eyes?");
            int eye = Integer.parseInt(in.nextLine());

            if (maybeTroy(antenna, eye)) {
                System.out.println("TroyMartian");
            }

            if (maybeVlad(antenna, eye)) {
                System.out.println("VladSaturnian");
            }

            if (maybeGraeme(antenna, eye)) {
                System.out.println("GraemeMercurian");
            }
        }
    }

    public static boolean maybeTroy(int antenna, int eye) {
        return ((antenna >= 3) && (eye <= 4));
    }

    public static boolean maybeVlad(int antenna, int eye) {
        return ((antenna <= 6) && (eye >= 2));
    }

    public static boolean maybeGraeme(int antenna, int eye) {
        return ((antenna <= 2) && (eye <= 3));
    }
}


Stack challenge - improving memory consumption

My main problem is that you are dynamically allocating all objects with new and or malloc. In C++ object can be created locally without new just by declaring them in the local scope.

MyStack   stack;      // Creates and initializes a MyStack object.

MyStack   data[10];   // Create and initialize an array of MyStack objects.

See no need to call new at all most of the time.

The second problem is that you are using malloc. This is C memory management. The blocks are not necessarily in the same areas as memory allocated by new and thus not compatible to be deleted by either. Also they don't run the constructor and free will not run the destructor. So a very bad idea.

The third observation is that you are building a container (linked list). There is already a built-in linked list.

std::list<int>   data;

For this structure of a stack. The list is not the optimal data structure. A std::vector or std::deque is probably better. But we have a built-in std::stack which is actually a container adapter that wraps another container type (by default it uses std::deque).

std::stack<int>   data;  // This is probably your best option
                         // for holding data.

If you want multiple stacks. I would just create a std::vector of stacks that you can the size at runtime to get all the stacks you need.

std::vector<std::stack<int>> data;
data.resize(<Number-Of-Stacks-You-Need>);

That should solve your memory problems.

Looking at your code we could go into your design of MyStack (but I think that is superflous). But some common rules:

Don't use C facilities when better C++ ones exist.
scanf() => operator>>
Don't mix dynamic memory allocation.
Only use new and delete in C++ code.
Every call to new should be matched with a call to delete
But you should not even do that normally:
a. Use local object most of the time.
b. Use containers when you have groups of objects.
c. When you really need dynamic allocation use smart pointers.
Learn the Rule of 3


You need better constants - "\u201d" is too magic - I would have no idea that it is a right double quotation mark just looking at that.

Don't use a bare except - you'll catch things you don't want to (for example, Ctrl+C).  Also, narrow the try as much as you can - if it is this big, it will be very hard to tell what caused the error. You should strongly prefer catching specific errors over all errors - errors you aren't expecting are probably bugs, and you'll want to learn about them.

Instead of calling __contains__ use in.

Don't use string concatenation the way you are - that's gonna be wasteful. Instead, use string.join.

You also don't need to forward declare all of these variables.

Using a format string will help the debug section be clearer.

You probably also want to factor out the first if branch into its own function, but given that it seems a little similar to the outer branch and the loop.  My guess is that the entire function this is in could be redesigned to be simpler and more modular, however without seeing that I can't speak exactly to it.

If you always increment pointer_position, put it in a finally block.

Overall, I'd recommend something more like this

elif current_command == "\u201d":
    compressed_strings = []
    position = pointer_position
    while position < len(commands) - 1:
        position += 1

        try:
            current_command = commands[position]
            if current_command in dictionary.unicode_index:
                position += 1
                pointer_position += 1
                next_command = commands[position]

                f = lambda x: str(dictionary.unicode_index.index(x))
                index = f(current_command) + f(next_command)

                next_string = dictionary.dictionary[int(temp_index)].title()

                compressed_strings.append(("" if not compressed_strings else " ") + next_string)
            elif current_command == "\u201d":
                break
            elif current_command == "\u00ff":
                compressed_strings.append(str(pop_stack(1)))
            else:
                compressed_strings.append(current_command)
        except Exception:
            break
        finally:
            pointer_position += 1
        if debug:
            print("{} with {}".format(pointer_position, hex(ord(current_command))))

    stack.append(''.join(compressed_strings))


The main problem I see is that it's not obvious what the output is because there's too much auxiliary code that effectively obfuscates the logic.

Offload some of the code into a function.
Use template strings.

If the data amount isn't in multi-megabyte range I would write a single string to improve readability:

const dataJson = JSON.parse(data);
const breakpointMap = dataJson['breakpoints-map'];
delete dataJson['breakpoints-map'];

const entryToCss = ([mapKey, mapValues], breakpoint) => {
  const property = functions.getProperty(mapKey);
  return Object.entries(mapValues)
    .map(([k, v]) => `.${breakpoint}${k}{ ${property}: ${v}}\n`)
    .join('');
};

cssWriter.write(
  Object.entries(breakpointMap).map(([bpKey, bpVal]) => {
    const breakpoint = functions.isDefault(bpKey) ? `${bpKey}\\:` : '';
    return `${
      breakpoint ? `@media ${bpVal} {\n` : ''
    }${
      Object.entries(dataJson)
        .map(entry => entryToCss(entry, breakpoint))
        .join('')
    }${
      breakpoint ? '}\n' : ''
    }`;
  }).join('')
);


If your dataset were coming from an outside source, like an API call, I'd say the atom would make sense.  In this case, your dataset is static.  In that case, I think I might find it more intuitive to use a var for the series and then select the items out that you want to plot.   In that case, your state is really just a list of which series (you are selecting).

So, if you had all your series:

(def all-series
  {:series1 :...series1
   :series2 :...series2
   :series3 :...series3})

!chart might contain #{:series1 :series3} and you could get all the values out using (select-keys all-series @!chart).

You might find you can avoid the atom altogether, but at the very least I'd always look for ways to keep that state as simple as


IrregularDelaySequence

I don't think the base IrregularDelaySequence class is needed here since it doesn't contain any members. To check if a specified instance is an irregular sequence, you could just compare its type to the RegularDelaySequence. If the type isn't RegularDelaySequence, the sequence is definitly irregular.

FibonacciDelaySequence

The logic of this class isn't quite clear for me.
I'd prefer to use an "oldschool" variables instead of the Queue:

public class FibonacciDelaySequence : DelaySequence
{
    private TimeSpan _prev;
    private TimeSpan _cur;

    public FibonacciDelaySequence(TimeSpan firstTwo, TimeSpan firstStep, int count) : base(count)
    {
        _prev = firstTwo;
        _cur = _prev + firstStep;
    }
    protected override IEnumerable<TimeSpan> Generate()
    {
        yield return _prev;
        yield return _prev;
        yield return _cur;

        while (true)
        {
            var current = _prev + _cur;
            yield return current;
            _prev = _cur;
            _cur = current;
        }
    }
}


Removing spam from a database using NodeJS

Well, your code can use a little formatting. I usually go with 2-character indents (tabs or spaces) since in JS, code tends to be nested. I usually also limit my newlines to 1 or 2, one being a "breather" and 2 for totally different blocks of code. While everyone's preferences vary, always consider consistency and readability.

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123',
    database : 'mydb',
    //debug: true,
    multipleStatements: true
});

var akismet = require('akismet').client({ blog: 'http://example.com', apiKey: 'xxxxxxx' });

I suggest you read your credentials from environment variables. You wouldn't want anyone seeing your passwords or API keys, especially when you start to use a version control system. This also makes it easy for multiple deployments (multiple machines, virtual hosts etc) as the credentials can be configured from a provisioning tool. I doubt your host will always be localhost on every machine, or your database be named mydb on every instance, or your API key be just one across your system.

const POSTS_QUERY = `
  SELECT
    p.topic_id as id,
    poster_ip,
    t.subject as message,
    p.poster
  FROM
    topics
  LEFT JOIN
    posts p on t.first_post_id = p.id
  WHERE
    poster_ip != ''
`;

If you're using the newer Node.js (I believe the 4.x onwards), it should have ES6 support, which includes multi-line (backticked) strings. This allows you to write SQL queries like the one above. Much cleaner than your single-lined strings. And since it's probably a constant string, I suggest using const as well as a conventional all-caps, snake-cased name.

I notice that your async functions are "node functions" (receive an error object first, data second). You can take advantage of Bluebird's promisify function to turn them into Promise-returning functions. That way, you can take advantage of Promises and write fairly linear-looking code.

Here's an excerpt of what I came up with:

let Promise = require("bluebird");

let connection = require('mysql').createConnection({
  host: 'localhost',
  user: 'root',
  password: '123',
  database: 'mydb',
  //debug: true,
  multipleStatements: true
});

let akismet = require('akismet').client({
  blog: 'http://example.com',
  apiKey: 'xxxxxxx'
});

const SELECT_POSTS = `
  SELECT
    p.topic_id as id,
    poster_ip,
    t.subject as message,
    p.poster
  FROM
    topics
  LEFT JOIN
    posts p on t.first_post_id = p.id
  WHERE
    poster_ip != ''
`;

let verifyKey = Promise.promisify(akismet.verifyKey);
let query = Promise.promisify(connection.query, { multiargs: true });
let checkSpam = Promise.promisify(akismet.checkSpam);

let verifyKeyPromise = verifyKey()
.then(function(verified){
  console.log('API key successfully verified');
  connection.connect()
  return query(SELECT_POSTS);
}, function(err){
  console.log('Unable to verify API key');
})
.then(function(rows, fields){
  console.log('Posts retrieved');
  return Promise.all(rows.map(function(entry){
    return checkSpam({
      user_ip: entry['poster_ip'],
      comment_author: entry['poster'],
      comment_content: entry['message']
    });
  });
}, function(v){
  console.log('Failed to retrieve posts');
})
.then(function(entrySpamStatus){
  console.log('Spam check succeeded');
  // and so on...
}, function(err){
  console.log('Spam check failed');
  // and so on...
})

// and so on...


1) No more than one instruction per line.

if (string.length() == 0 || string.length() == 1) return string.toString();

i.e.:

if (string.length() == 0 || string.length() == 1) {
    return string.toString();
}
// or, better:
// if (string.length() < 2) {
//     return string.toString();
// }

2) Your main while feels strange, I don't like this creative use of postdecrement and greater then operator

while (numberOfTestCases --> 0)  // BAD! See https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c

In this case a for loop is better because you know the number of iterations.

3) while (true) is bad and force the developer to read all the code to understand how to break the loop

4) No need to pass a StringBuilder to reverseVowels: the method itself should create it.

5) Use temporary variables to improve readability:

...
for (int i = 0; i < numberOfTestCases; i++) {
    String input = scanner.nextLine();

    String vowelsReversedString = reverseVowels(input);

    System.out.println("OUTPUT: " + vowelsReversedString);
}
...

...
private static String reverseVowels(String string) {
    if (string == null || string.length() < 2) {
        return string;
    }

    StringBuilder sb = new StringBuilder(string);

    int start = 0;
    int end = sb.length() - 1;

    while (start < end) {
        ...
    }

    return sb.toString();
}
...


The biggest problem I see is that the objects you pass around in EJB3 are part of the transaction. If you try to reload the payment again from the EntityManager, you will get back the exact same instance you are trying to avoid changing. You will have to jump through hoops in order to reload the payment as a completely new object and that pretty much negates anything that makes pure methods less error prone.

Following best practises is a valid reason but in this case I get the feeling that the baby gets thrown out with the bath water. Don't feel bad, though. EJB3 transaction model is not intuitive at all, needs very good project documentation and guidelines and it still needs constant care taking anyway.


Writing slice compare in a more compact way

What about this:

fn compare(a: &[u8], b: &[u8]) -> cmp::Ordering {
    for (ai, bi) in a.iter().zip(b.iter()) {
        match ai.cmp(&bi) {
            Ordering::Equal => continue,
            ord => return ord
        }
    }

    /* if every single element was equal, compare length */
    a.len().cmp(&b.len())
}

I've removed the self argument, and used the cmp-module to do the actual comparison and zip() as @alexv already suggested.


This DRY's the code in self.memcache and simply uses a ternary operator for self.fetch.

require 'dalli'
class Cache
  def self.fetch(key, ttl, &block)
    memcache ? memcache.fetch(key, ttl, &block) : block.call
  end

  def self.memcache
    @memcache ||= Dalli::Client.new((ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development) ?
                                    'cache.amazonaws.com:11211' :
                                    'localhost:11211')
  rescue Exception
    false
  end
end


Function to parse a Javascript object and return a CSV

Description

It would appear that your current solution is a bit complicated. Using JSON.parse just to ensure that you escape , is overkill.

The overall solution can be drastically simplified as you will see in this post.

const before let and let before var

All variables should be declared by default with const. If a variable is going to be mutated then use let. Don't use var unless that is what you intended.

/// bad
var dataFromAPI = ...

/// good
const dataFromAPI = ...

note: pushing an element to a list will only mutate the array and not the variable, thus no error

Work with arrays and not with strings.

/// bad
csvOutput = "Index,Field Value\n";

/// good
const csvOutput = [
  ["Index", "Field", "Value"]
];

Function names should describe what they do.

The convertToCSVandDownload method only converts to CSV but doesn't download. Change the name to convertToCSV

Working Solution

Use Array#reduce, destructuring assignment, Array#map, Array#join and spread syntax

const dataFromAPI = [{"name":"first"},{"name":"sec,ond"},{"name":"third 'jibberish"},{"name":"fourth, jibberish"}]

function convertToCSV(data, headers) {
  return data
  .reduce((a,{name},i)=>[...a, [i, `"${name}"`]], [headers])
  .map(row=>row.join(","))
  .join("\n");
}

const res = convertToCSV(dataFromAPI, ["Index", "Field Value"]);

console.log(res)