Do I really need to take a lock in my WriteUnlock() method? It looks like all I'm doing is unlock right away.

YES, you need the lock, because you are accessing queuedWriters and you need to make sure nobody changes it (by calling writeLock) before you notify readers or writers based on the check. You could have seen queuedWriters being zero, therefore notifying readers, but some writer could get sleeping in the meantime and never get woken.

  And is it recommended to perform a lock.unlock() before I do a notify_one or a notify_all?

Unlock before, because the thread being woken would immediatelly try to hold the lock, thus being blocked again (to be woken for second time when you unlock).

  Does performing a condition_variable.wait(lock, lambda) where the lambda is true cause a performance loss?

It is same as while (!pred()) wait(lck);
What else could you do? It checks first, so, would not wait if the condition is true.


Elegant function to "increase" a JavaScript string - for example, turning "aac" into "aad"

A recursive approach is much more elegant in this case:

function inc_str(str) {
  var last = str[str.length - 1],
    head = str.substr(0, str.length - 1);
  if (last === "z") {
    return inc_str(head) + "a";
  } else {
    return head + String.fromCharCode(last.charCodeAt(0) + 1);
  }
}

Making it wrap around for inc_str('z') is left as an exercise for the reader (hint: last becomes undefined).


Congratulations

You mostly follows standards which is good. You also have good documentation which is great. All in all the code reads well and is easily understandable.

Style-wise, I just have some nitpicks:

from PEP8, you should name your constants using all caps (SAMPLE_RATE, DAMPING);
you should not abreviate that much your variable names frequency and volume are to be prefered to f and vol;
you may want to name things to avoid comments: A_major = [220, 220 * 5 // 4, 220 * 6 // 4, 220 * 2].

Summation

In pure Python world the following code:

value = 0
for element in array:
    value += compute(element)
return value

is prefered written as:

return sum(compute(element) for element in array)

As it is both cleaner and faster. In numpy world, it is pretty much the same. You can write:

def generate_chord(frequencies, samples):
    plucks = (generate(note, 0.5, samples) for note in frequencies)
    return np.sum(plucks, axis=0)

and get the same result.

Interface

When reading your docstrings, I wondered why you would ask your users (or yourself) to pass in a number of samples if what is more natural to them is to use a duration in seconds. Do not expose implementation details such as your sample rate to the users and let them use what is more natural to them.

I also wonder why you hardcode the volume in generate_chord and let it variable in generate. If the aim is to not have to choose it for each test, you can still use a parameter with default value instead of hardcoding it. It will make things more obvious.

Lastly, I don't really understand the need for integral frequencies as the computations can be performed just as well with floating point values. Just make sure to truncate the computation of N.

I would use the following code as a base for improvements:

import numpy as np

SAMPLE_RATE = 44100
DAMPING = 0.999

def generate(frequency, volume, duration):
    """Generate a Karplus-Strong pluck.

    Arguments:
    frequency -- the frequency, as a float
    volume -- volume, a float in [0.0, 1.0]
    duration -- the length of the generated pluck, in seconds.

    Return value:
    A numpy array of floats with length nsamples.
    """

    samples_count = duration * SAMPLE_RATE
    N = int(SAMPLE_RATE / frequency)
    buf = np.random.rand(N) * 2 - 1
    samples = np.empty(samples_count, dtype=float)

    for i in range(samples_count):
        samples[i] = buf[i % N]
        avg = DAMPING * 0.5 * (buf[i % N] + buf[(1 + i) % N])
        buf[i % N] = avg

    return samples * volume

def generate_chord(frequencies, duration, volume=0.5):
    """Generate a chord of several plucks

    Arguments:
    frequencies -- a (usually short) list of frequencies
    describing a chord.
    duration -- the length of the generated pluck, in seconds.

    Return value:
    A numpy array
    """

    plucks = (generate(note, volume, duration) for note in frequencies)
    return np.sum(plucks, axis=0)

if __name__ == "__main__":
    import scipy.io.wavfile
    import matplotlib.pyplot as plt

    A_major = [220, 220 * 5 // 4, 220 * 6 // 4, 220 * 2]
    strum = generate_chord(A_major, duration=5)

    plt.plot(strum)
    plt.show()

    scipy.io.wavfile.write(filename, SAMPLE_RATE, strum)

Beyond frequencies

Now, I’m not musician. And even if I were, I would need to look up frequencies of required note as I don't think your average user would know them by heart. It would be best to provide named constants to remember that for us.

Reading at https://en.wikipedia.org/wiki/Musical_note one can easily define something like:

C = 2 ** (-9/12) * 440
C_sharp = 2 ** (-8/12) * 440
D_flat = 2 ** (-8/12) * 440
D = 2 ** (-7/12) * 440
D_sharp = 2 ** (-6/12) * 440
E_flat = 2 ** (-6/12) * 440
E = 2 ** (-5/12) * 440
F = 2 ** (-4/12) * 440
F_sharp = 2 ** (-3/12) * 440
G_flat = 2 ** (-3/12) * 440
G = 2 ** (-2/12) * 440
G_sharp = 2 ** (-1/12) * 440
A_flat = 2 ** (-1/12) * 440
A = 2 ** (0/12) * 440
A_sharp = 2 ** (1/12) * 440
B_flat = 2 ** (1/12) * 440
B = 2 ** (2/12) * 440

But this does not account for every octave. Let's fix that and simplify the reading using an enum:

import enum

def octave(order):
    frequency_of_A = 440 * 2 ** (order - 4)

    class Octave(enum.Enum):
        C = -9
        C_sharp = -8
        D_flat = -8
        D = -7
        D_sharp = -6
        E_flat = -6
        E = -5
        F = -4
        F_sharp = -3
        G_flat = -3
        G = -2
        G_sharp = -1
        A_flat = -1
        A = 0
        A_sharp = 1
        B_flat = 1
        B = 2

        def __float__(self):
            return 2 ** (self.value/12) * frequency_of_A

    return Octave

SubSubContra = octave(-1)
SubContra = octave(0)
Contra = octave(1)
Great = octave(2)
Small = octave(3)
OneLined = octave(4)
TwoLined = octave(5)
ThreeLined = octave(6)
FourLined = octave(7)
FiveLined = octave(8)
SixLined = octave(9)

Now I can easily define A Major using:

A_major = [Small.A, OneLined.C_sharp, OneLined.E, OneLined.A]

Proposed improvements

import enum
import numpy as np

SAMPLE_RATE = 44100
DAMPING = 0.999

def octave(order):
    """Create an enum of all the notes in the octave
    of the given order.
    """
    frequency_of_A = 440 * 2 ** (order - 4)

    class Octave(enum.Enum):
        C = -9
        C_sharp = -8
        D_flat = -8
        D = -7
        D_sharp = -6
        E_flat = -6
        E = -5
        F = -4
        F_sharp = -3
        G_flat = -3
        G = -2
        G_sharp = -1
        A_flat = -1
        A = 0
        A_sharp = 1
        B_flat = 1
        B = 2

        def __float__(self):
            return 2 ** (self.value/12) * frequency_of_A

    return Octave

SubSubContra = octave(-1)
SubContra = octave(0)
Contra = octave(1)
Great = octave(2)
Small = octave(3)
OneLined = octave(4)
TwoLined = octave(5)
ThreeLined = octave(6)
FourLined = octave(7)
FiveLined = octave(8)
SixLined = octave(9)

def generate(frequency, volume, duration):
    """Generate a Karplus-Strong pluck.

    Arguments:
    frequency -- the frequency, as a float
    volume -- volume, a float in [0.0, 1.0]
    duration -- the length of the generated pluck, in seconds.

    Return value:
    A numpy array of floats with length nsamples.
    """

    samples_count = duration * SAMPLE_RATE
    N = int(SAMPLE_RATE / frequency)
    buf = np.random.rand(N) * 2 - 1
    samples = np.empty(samples_count, dtype=float)

    for i in range(samples_count):
        samples[i] = buf[i % N]
        avg = DAMPING * 0.5 * (buf[i % N] + buf[(1 + i) % N])
        buf[i % N] = avg

    return samples * volume

def generate_chord(frequencies, duration, volume=0.5):
    """Generate a chord of several plucks

    Arguments:
    frequencies -- a (usually short) list of frequencies
    describing a chord.
    duration -- the length of the generated pluck, in seconds.

    Return value:
    A numpy array
    """

    notes = map(float, frequencies)
    plucks = (generate(note, volume, duration) for note in notes)
    return np.sum(plucks, axis=0)

if __name__ == "__main__":
    import scipy.io.wavfile
    import matplotlib.pyplot as plt

    A_major = [Small.A, OneLined.C_sharp, OneLined.E, OneLined.A]
    strum = generate_chord(A_major, duration=5)

    plt.plot(strum)
    plt.show()

    scipy.io.wavfile.write(filename, SAMPLE_RATE, strum)


(sort of) casting types in Ruby: changing class of an instance

First off, why bother with a separate Square class?

Personally, I'd make a Rectangle class' to_square! method simply set both width and height to Math.sqrt(area). The result is still a Rectangle, just a square one.

The Rectangle's initializer method could also be written with an optional second argument; If there's only one argument, use that for both width and height, and you have a square.

Furthermore, I'd add a square? method. Checking obj.square? is, in my view, preferable to checking obj.class == Square. You could also use square? in to_s to return one string or the other.

To answer your question, though, I don't know of any way to just change an instance's class. You could however experiment with including different modules depending on whether the rectangle in question is a square or not. But that all seems pretty complex.

Finally, if you want a Square method, simply define one:

def Square(side)
  Rectangle.new(side, side)
end

Even if you have a Square class already, you can still have a method of the same name:

class Square
  # ...
end

def Square(side) # no naming conflict
  Square.new(side)
end


Check if two strings are permutations of each other

Test cases

From an interview perspective, I would suggest that you're missing the test case for the null-handling. Creating full unit test cases in an interview is overkill, but is it too much to just add:

try {
    System.out.println("Should not happen: " + isPermutation(null, ""));
} catch (IllegalArgumentException e) {
    System.out.println("Got expected exception for null");
}

Java features

Your use of Java features is OK, but you are not really doing a whole lot.

Bugs

Your spec says the strings will contain ASCII characters, and, to me, things like spaces  and punctuation -_!@#$%.... are all ASCII. Your code subtracts the 0 character value from the string's character to get the array index. This will fail for the spaces and punctuation. Why do you need to do the 0 subtraction at all? The code would work for all ASCII without that anyway.

Algorithm

My biggest suggestion is about the algorithm, anyway. Your code counts each character and compares the counts. A much simpler, and intuitive algorithm, is to sort the characters and compare the results.....

Consider:

private static String normalize(String value) {
    char[] chars = value.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

public static boolean isPermutation(String s1, String s2) {
    if (s1 == null || s2 == null) {
      throw new IllegalArgumentException("Input string cannot be null");
    }
    return normalize(s1).equals(normalize(s2));
}


There are a number of things that I see that may help you improve your code.

Use the appropriate form for #includes

The code has the appropriate #include files but they should be in angle brackets and not quotes.  When you write #include "math.h" it is different from #include <math.h>.  For standard headers, you should use the <> form.  If you're not sure about the difference, see this question for more detail.

Don't use Hungarian notation

Prefixing every variable with an abbreviation of its type (e.g. pStr) is usually called "Hungarian notation" and it was once popular.  Even then it was a bad idea.  Don't clutter up your source code with that; instead, concentrate on defining meaningful names for each variable and choose types appropriately.

Return an error code

The myStrInsert function can detect errors, but gives no indication to the calling program that anything went wrong.  A more robust design would return an error code.

Avoid memory fragmentation

The code allocates new space even if the original space would have had room.  This is somewhat wasteful and can lead to memory fragmentation.  Better would be to use realloc.

Do more error checking

It's good that pos is checked for a negative number, but it might be good to also check to assure that the pointers are not NULL before dereferencing them.

A possible rewrite

Using all of these suggestions, one might rewrite to something like this:

int myStrInsert(const char *inserted, char **target, int pos)
{
    if (inserted == NULL || target == NULL || *target == NULL || pos < 0) {
        return -2;
    }
    size_t wordlen = strlen(inserted);
    size_t origlen = strlen(*target);
    char *orig = realloc(*target, origlen+wordlen+1);
    if (orig == NULL) {
        return -1;
    }
    if (pos > origlen) {
        pos = origlen;
    } else {
        memmove(&orig[pos+wordlen], &orig[pos], origlen-pos);
    }
    memmove(&orig[pos], inserted, wordlen);
    orig[origlen+wordlen] = '\0';
    *target = orig;
    return 0;
}

Limitations

One thing I think I should mention is that, unlike the original code, this code is not robust if we attempt to splice a string into itself.  That is, if we try to insert "fox" into the string "the fox" by passing in the first parameter as a pointer into the same string we're modifying, it's not necessarily well-behaved.  It's something that isn't hard to fix, but I wanted to make sure that readers were aware of the limitation before attempting to use this code.


It seems you simply need process a fixed set of work items in parallel with a fixed degree of parallelism and in an async compatible way. Stephen Toub has written a very elegant way to do that in just a couple lines of code.

public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
    return Task.WhenAll(
        from partition in Partitioner.Create(source).GetPartitions(dop)
        select Task.Run(async delegate {
            using (partition)
                while (partition.MoveNext())
                    await body(partition.Current);
        }));
}

Your new code would be:

await ForEachAsync(GetWorkItems(), dop: 16, body: async item => {
 await ProcessItem(item); //TODO
});

There is no need to explicitly maintain a queue. But if you want to, you can du that by feeding ConcurrentQueue.GetConsumingEnumerable() into that ForEachAsync helper.


GLSL Shader that displays a Rotating Rainbow Ring

Distance

In both your step(...) functions, you are computing distance(st, vec2(0.5)).  If you computed this once, and stored this in a local variable, you'd be able to reuse this computed value, which should save time in your shader.

But ... wait a second ...

vec2 toCenter = vec2(0.5)-st;
float radius = length(toCenter)*2.0;

You've already computed this distance (length, actually), and stored it (doubled) in the local variable radius.  We can use this value directly, by doubling your step thresholds:

float outsideMask = 1.0 - step(radius, 0.6);
float insideMask = 1.0 - step(0.4, radius);
float visibleArea = 1.0 - insideMask - outsideMask;

Or don't multiply the computed radius by 2.0 for the radius variable, and multiply it by 2 when you use it to compute the colour:

float radius = length(toCenter);

float outsideMask = 1.0 - step(radius, 0.3);
float insideMask = 1.0 - step(0.2, radius);
float visibleArea = 1.0 - insideMask - outsideMask;

color = hsb2rgb(vec3((angle/TWO_PI)+0.5, radius*2.0, 1.0));

visibleArea

outsideMask = 1.0 - step(radius, 0.3)
insideMask = 1.0 - step(0.2, radius)
visibleArea = 1.0 - insideMask - outsideMask

Substituting insideMask into (3):

visibleArea = 1.0 - (1.0 - step(0.2, radius)) - outsideMask
visibleArea = 1.0 - 1.0 + step(0.2, radius) - outsideMask
visibleArea = step(0.2, radius) - outsideMask

From step(A,B) = 1 - step(B,A), we can reworking (1) as:

outsideMask = step(0.3, radius)

And substituting into (6):

visibleArea = step(0.2, radius) - step(0.3, radius)


When you navigate away from the page the WebElements get invalidated as DOM changes therefore I would recommend going for List Comprehension and convert the list of WebElements into the list of links text.
Once done you should be able to use normalize-text() function just in case the text belongs to child element or has starting/trailing spaces
And last but not the least consider using Explicit Wait just in case the link is populated via AJAX call.

Example code:

driver.get("http://yandex.ru")
links = [link.text for link in driver.find_elements_by_css_selector("a")]
for link in links:
    WebDriverWait(driver, 10) \
        .until(expected_conditions
        .presence_of_element_located(
        (By.XPATH, "//a[normalize-space()='" + link + "']"))).click()
    # do what you need here
    print(driver.title)
    driver.back()
driver.quit()


Is there a good way to do this C++ single-player class?

There's not a lot of substance here to review, but anyway, here are some things that may help you improve your code.

Use include guards

There should be an include guard in the .h file.  That is, start the file with:

#ifndef PLAYER_H
#define PLAYER_H
// file contents go here
#endif // PLAYER_H

Make sure you have all required #includes

The code uses std:string within player.h but doesn't #include <string>.  Also, carefully consider which #includes are part of the interface (and belong in the .h file) and which are part of the implementation.

Let the compiler create default destructor

The compiler will create a destructor by default which is essentially identical to what you've got, so you can simply omit both the declaraton and implementation from your code.

Prefer modern initializers for constructors

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

Player(std::string playerName)
{
    name = playerName;
    cash = 0;
    workers = 0;
}

You could use this:

Player(std::string playerName) :
    cash{0},
    workers{0},
    name{playerName}
{ }

Write member initializers in declaration order

When you start writing constructors in the modern style mentioned above, you'll want to make sure that you write the initializers in the same order as they are declared. Because members are always initialized in declaration order and cash is declared before name in this class. To avoid misleading another programmer, you should make the order match in all constructors.

Don't write Java in C++

While it may be fashionable in Java to write canonical getters and setters of the form you've got, it's definitely not C++ style.  Consider these two lines from main:

std::string pName = player.getPlayerName();
std::cout << pName << std::endl;

We already know the object is a player, so saying player.getPlayerName() seems redundant.  I'd prefer to just write player.name() like this:

std::cout << player.name() << std::endl;

Rethink namespaces

Is it really necessary to have a player namespace encapsulating a Player class?  Specifying your own namespace is a good idea, but nesting them deeply is probably not.

Consider using inheritance

It's likely that your eventual game is going to have more than just Player class objects and it's also likely that those other objects will also have names.  This suggests that it might make sense to have a base class that includes common things such as name and then derive more specialized objects from it.

Provide the entire code to simplify reviews

Finally, it's not really about the code but about the review process.  A minimal real main.cpp would look something like this:

#include <iostream>
#include <string>
#include "player.h"

int main() {
    using namespace SDLGamecore::player;
    Player player("Test");

    std::cout << player.name() << std::endl;
}

It's usually better to post code that will actually compile without modification rather than snippets of code that require the reviewer to imagine the missing bits.  Including everything needed will help you get better and more useful reviews.


Your question is surprisingly hard to answer, largely because you ask one question in your words, but a different question in your code. Your written question is whether looking up a value by sequentially scanning a vector is the best or worst way to do it. And the answer to that question is nuanced. I'll talk more about this in a bit.

However your code shows a full scenario in which you read a file, look up and edit your single user, and display the full vector's contents. In this fuller context, the performance questions of the sequential scan almost definitely do not matter, as reading and displaying the whole vector will cost more time than you could save by having a smarter look-up. A more typical program might let you perform multiple edits, and then the time it took to look up each person might be more important. So that's another improvement to consider.

Scanning a Vector

Scanning a vector with a hand-rolled for loop is not generally considered the best way to do things. It's often much better to find an algorithm that does what you want, and use it. In this case we don't know anything particularly useful about the contents of your vector, so the best bet is going to be find or find_if. To use find, you'll have to overload operator== in something, and pass it around; to use find_if you can instead create a helper function or overload operator(), or in C++11 you can pass a lambda function. Let's examine the middle option:

struct user_by_name {
    user_by_name(string name) : name(name) {}
    bool operator()(user& user) { return user.getUserName() == name; }
    string name;
};

: : :

vector<user>::iterator iterFound = std::find_if(userDetails.begin(), userDetails.end(), user_by_name(name));
if (iterFound != userDetails.end())
{
    : : :
}

The nice thing about this approach is you can create ways to find users by other criteria, such as a user_by_salary, and substitute it in with almost no code change. The downside is that without making other changes, you'll never get better than "linear" performance - on average you'll always have to look through half of the items in your vector to find the one you need.

Scanning faster

If there's a natural ordering for the items in your vector, you have two main options. Both of them require implementing an operator<, and thus do change your user struct's usage paterns. And both of them scan faster by being able to skip past some items while finding the one you want.

You can keep the items in the vector, but sort them by this ordering. This allows you to use an algorithm such as lower_bound to find them in a fraction of the time.
You can store the items in a different data structure such as a std::map which makes similar use of the ordering to give you the same performance assistance that lower_bound does on the sorted vector.

Choosing between these cases depends on how the data will be used. Again, with just a single edit in your main program, this is all overkill. But if you are going to have a long-running multi-edit scenario, especially one with thousands of employees being looked up by name and updated, it might be worth examining these options.

Other options

If you were storing a realistic amount of data about each employee, had a realistic number of employees, and had a lot of tasks you wanted to perform on them, chances are you'd find storing their information in a database would make a lot more sense. Databases solve a lot of problems for you; not only do they support fast look-ups, they handle persistence of the data (loading and saving it as necessary) and, for the right scenarios, save you a lot of time and effort. Obviously for learning how to do some of the C++ programming that you show here, using a database may help you less (although learning how to use a database isn't a bad skill either).

Other comments

Finally I wanted to end this review with a list of more generic comments about your actual code. A lot of these things are details you don't need to care about yet, or that may have occurred just in trying to post your code here, but they may help you form better habits as you advance your C++ programming skills.

using namespace std is frowned upon. It's utter anathema in a header file (which you didn't do), but it's also a risk in your cpp file. You're better off either adding the std:: prefixes, or adding using std::string; using std::vector; etc. However it's unlikely to matter in code like you show here.
Your use of whitespace is inconsistent. You don't always put spaces after commas, and sometimes use newlines instead. In some places you use more blank lines that I would consider helpful. Also not going to really matter in code this short.
Your property accessors (getUserName, getSalary) should be const as they should not visibly modify the object, and probably should return a const string& instead of a mutable copy.
Your header should include <string> instead of <iostream>, and user.cpp can similarly drop its incldue of <iostream>; you don't appear to use anything from iostream in there. Your main.cpp similarly has a lot of unused includes, but I would expect it's more of a testing file so won't harp on it.
Your search loop will find multiple matches. If you have multiple employees named bruce, your code will stop at each of them and ask for a new salary. If this is not intentional, you can use break; to avoid this. Note that most of my commentary above assumes you will want to only update a single employee at a time.
If there's no match, the program directly displays the output without any explanatory messages. That seems a little surprising to me, but perhaps it's intentional.

There's not a lot of self-documentation in your code. You'll note the last two bullets I talk about what's intentional, and in particular that I'm uncertain what you meant for your code to do. Finding the right balance between variable names, function names, and comments will help resolve that in the future. This can start as simply as adding the description you gave in your post as a comment in your main.cpp.

But all that said, I think you're starting off on the right foot. You show some solid understanding, and you also show interest in refining your skills. Congratulations on a good first post here!


Questions

Should Root take props or wrap children components?

<Root navLinks={this.state.navLinks}></Root>

vs
<Root>
  <NavLinks navLinks={this.state.navLinks} />
</Root>

I think this primarily comes down to the purpose of Root. If it is a general purpose wrapper container component, then the latter pattern makes sense. I.E. it is providing the layout but no actual UI, this works well. If on the other hand it isn't very generalizable, i.e. it is more single purpose, then passing it props is preferred. I understand this doesn't sound like an answer, but like many things in javascript, there's no clear, hard line between them and this could also simply come down to personal preference/opinion.

Do I need an App.js file or index.js file and could have one rather than the other?

Again, these both exist by convention, but you could easily merge the two if you so desired. The distinction basically comes down to separation of concerns. index.js is primarily concerned with rendering the application into the DOM whereas App.js is primarily concerned with being the root application container. This is typically where redux stores & providers, react contexts & providers (well, all "providers" in general), root routers/navigation, theming, etc, etc... would/could reside and provide functionality to the app.
Code Review
App.js

For such simple components (no state updates or no state, no lifecycle functions, etc..) it is recommended to instead use functional components
There is no compelling reason to store the static link data in react state, just pass it directly to props
navLinks isn't a component so it probably shouldn't be stored in that directory, better suited for a utility directory or similar
Root doesn't wrap any children components so it can be self-closed

Suggestion
import React from "react";
import { navLinks } from "./components/nav-links";
import Root from "./components/Root";

export const App = () => <Root navLinks={navLinks} />;

/components/Root.js

Many of the same comments as for App.js
If the element ids are actually used (CSS, testing) then keep them, otherwise they just clutter the JSX
BodyCode is already wrapped in a div, so the div here is extraneous and helps increase clutter in the DOM

Suggestion
import React from "react";
import NavMenu from "./nav-menu";
import BodyCode from "./body-code";

export const Root = ({ navLinks }) => (

      <NavMenu navLinks={navLinks} />

    <BodyCode />

);

/components/body-code.js

By convention react component names are PascalCased
handleClick can be defined as an arrow function, which would make binding this to it in the constructor unnecessary
Great job on using a functional state update to toggle the isToggleOn state value
While not a necessity, the constructor can be removed and state defined as a class property
Also not a necessity, this component is still simple enough and doesn't utilize any lifecycle functions that it is also a good candidate for conversion to functional component

Class-based suggestion
import React, { Component } from "react";

export class BodyCode extends Component {
  state = {
    isToggleOn: true,
  };

  handleClick = () => this.setState(
    prevState => ({ isToggleOn: !prevState.isToggleOn })
  );

  render() {
    return (

some body text

        <button onClick={this.handleClick}>
          {this.state.isToggleOn ? 'ON' : 'OFF'}
        </button>

    )
  }
}

Functional component suggestion
import React, { useState } from "react";

export const BodyCode = () => {
  const [isToggleOn, setIsToggleOn] = useState(true);

  const handleClick = () => setIsToggleOn(on => !on);

  return (

some body text

      <button onClick={handleClick}>
        {isToggleOn ? 'ON' : 'OFF'}
      </button>

  );
};

/components/nav-menu.js

Should follow react component naming convention
Simple and should probably be converted to functional component

Suggestion
import React from "react";

export const NavBar = ({ navLinks }) => navLinks.map(link => (

    {link.name}

));

Other Suggestions
Use a routing/navigation solution versus using anchor () tags as these actually reload the app. These typically provide all the functionality of links and navigating around your app by manipulating the browser's history stack but won't reload the page between navigations.
react-router/react-router-dom is a common routing solution. The idea being you define Routes, wrapped in a Router/Switch, to render each "page" of your app, and instead of anchor tags a Link is used to go to a specified path.
A sample router in BodyCode
import { BrowserRouter as Router, Route } from 'react-router-dom';

...

some body text

  <button onClick={this.handleClick}>
    {isToggleOn ? 'ON' : 'OFF'}
  </button>
  <Router>
    <Route path="/subs" component={Subs} />
    <Route path="/" component={Home} />
  </Router>

NavMenu
import { Link } from 'react-router-dom';

...

navLinks.map(link => (
  <Link key={link.href} to={link.href}>
    {link.name}
  </Link>
))


Safe init using failable guarded initializer

The separation into a non-failable and a failable init method is
fine.

The forced casts with as! are safe in your code, because it is verified before
that the three variables id, displayName, number have the
respective types Number, String and NSNumber.

However:

The code is error-prone: Changes to the types must be done at two places.
It is not immediately obvious that it works correctly.

Forced casts should (and can!) be avoided in most cases, in the
same way as forced unwrappings. The program would be terminated
immediately if the cast fails.

In your code that is quite easy,
by replacing the type checks is T by  conditional casts as? T.
The latter return a value of the type T and that makes the forced
cast unnecessary. In addition, it simplifies and shortens the code
of  the failable init method:

init?(dictionary: NSDictionary) {

    guard let id = dictionary["id"] as? NSNumber else {
        return nil
    }
    guard let displayName = dictionary["display_name"] as? String else {
        return nil
    }
    guard let amount = dictionary["amount"] as? NSNumber else {
        return nil
    }
    self.init(id: id, displayName: displayName, amount: amount)
}

As a further simplification, combine the optional bindings into
a single guard statement (attribution goes to @Knight0fDragon who
reminded my in a comment):

init?(dictionary: NSDictionary) {
    guard
        let id = dictionary["id"] as? NSNumber,
        let displayName = dictionary["display_name"] as? String,
        let amount = dictionary["amount"] as? NSNumber else {
            return nil
    }
    self.init(id: id, displayName: displayName, amount: amount)
}

Some other points:

Your spacing is not consistent.
The indenting is totally wrong.
The correct spelling is dictionary.


Using a base class but defining a property

You solution does look a bit fragile, but I can't help that without seeing more of the hierarchy. The way I'd approach this is to add value=None to your argument function header, and then do this for each attribute:

if value is not None:
    self.value = value

That way the inheriting classes can signal that they don't want the attribute initialised by just leaving the attribute out of the __init__ args, or passing None (this won't work if you actually want None as a value. You'd have to find another placeholder). That way, the system will be a bit more flexible, and there will not be any bad consequences caused by trying to initialise an attribute which is not meant to be initialised.


Object-oriented implementation of a real-world scenario of using a bathroom

You should be programming for interfaces.

In Bathroom instead of

ArrayList<Fitting> fittings;

use

List<Fitting> fittings;

Also you should be using Enums instead of variables. So instead of

public static final int TAP = 0;
public static final int SHOWER = 1;
public static final int SINK = 2;

you should be using

package fittings;

public enum FittingType {
   TAP, SHOWER, SINK;
}

That is a general thing - use enums instead of instance variables. But in your example you don't need that. You can do something like

public Fitting getBathroomFitting(Class<? extends Fitting> fittingType) {

    for (Fitting fitting : fittings) {
        if (fittingType.isInstance(fitting)) {
            return fitting;
        }
    }
    return null;
}

And then in your main method use

bathroom.getBathroomFitting(Tap.class).use(rutvik);

Having a enum which enumerates the sub classes of a class? Not a good idea. You can use the sub classes themselves if you want like above.

BTW in your design, if your bathroom has two taps then how are you going to use the second tap? The method just returns the first instance of that type.

About casting, you will have to cast it somewhere when you are storing as a superclass but using sub class specific things.

  What if I add new Object like WaterTank how will it interact with fitting?

That all depends on what you want to represent in the code.


size++ should be extracted from both branches and called only once
there is no need to cache instance variables where local method variables should be used instead: newNode,oldNode,displayNode
prefer while(currentNode != null) over while(true) and currentNode should start with firstNode and be chained inside the while-loop as currentNode = currentNode.next
you should also provide remove and iterator functionality
DisplayLinklist should not be inside this class and it should be camel cased
variable firstNode is usually called head
class linkedlist should be called LinkedList
get rid of unwanted blank lines


Using/reusing the SQL Command for several Inserts in the SQL Transaction

Not clear what AssignCreateISOParam(type, AZ) is and why it is above dbCmd.ExecuteNonQuery()

Create the command and parameter(s) outside the loop.  In the loop just assign the value and execute.

dbCmd = New SqlCommand("spNewAZ", dbConn, dbTran)


Proper way to find newest file in a directory

some minore issues only...

naming / return type

public static Path getLatestFile() assumes that you return only ONE file, but it's easily possible that you have two files of the same date... so you should maybe return a Set<Path> from your method getLatestFiles(). This method would return all files with the latest time stamp.

use a logging framework

you should write infos into a proper logging stream:

System.out.println("Latest file: " + pathToReturn + " - " + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

note:

you could write the corresponding information directly inside the loop.

for (Path path : pathSet) {
        attr = getBasicFileAttributes(path);
        if (attr.creationTime().toMillis() > fileTime) {
        fileTime = attr.creationTime().toMillis();
            pathToReturn = path;
            //here
            System.out.println("Latest file: " + pathToReturn + " - " + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        }
    }

    //instead of here:
    //attr = getBasicFileAttributes(pathToReturn);
    //System.out.println("Latest file: " + pathToReturn + " - " + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

more significant code (tell, don't ask):

maybe it's just my style but i would really directly return what is said:

private static BasicFileAttributes getBasicFileAttributes(Path pathToReturn) throws IOException {
    return Files.readAttributes(pathToReturn, BasicFileAttributes.class);
}

use a test case

instead of testing your code in a main-methode write a junit test. that makes the code clearer to read and you can get rid of the methods getFilesFromDirectory() and iteratePaths() which are only for testing.

ever since the test methods are still in review let me advise you about these:

possible NPE

it's possible to create a NullPointerException:

Stream<Path> stream = null;
try {...} catch (IOException e) {...}
//if an exception is raised within this block above an NPE will be thrown!
stream.close();

maybe you could consider a try-with-resources block? maybe you don't care because it's a mere test method, haha =)

use a Logger / Handle Exceptions

what do you do if an exception really happens? you should implement the actions that should happen in case of exception - not just printing to stacktrace:

Stream<Path> stream = null;
    try {...} catch (IOException e) {
        //don't print - take actions instead!
        //e.printStackTrace();
    }

as said above, maybe you don't care because it's a mere test method...


This problem can be solved much faster with a Sieve of Eratosthenes algorithm, especially since you need every prime between 2 and n for you to sum them up.
However, there are a few optimizations you could make to your particular algorithm.

Dynamic Programming
Your code preforms some redundant calculations. For example, once you've checked if n % 2 is zero, you know n % 4, n % 6... are also zero. To avoid these calculations you could instead divide by only the prime numbers up to and including √n:
primes = [2] #define your array of prime numbers

def checkPrime(number):
    if number < primes[0]:
        return False

    for p in primes: #only iterate through the primes
        if p > number**0.5:
            break; #no need to keep going
        if number % p == 0:
            return False

    primes.append(number);
    return True

primes = [i for i in range(10) if checkPrime(i)]
print sum(primes)


If you make your custom callback node style (i.e. function(err, result)), you can simplify this greatly:

'use strict';
var MongoClient = require('mongodb').MongoClient,
    db;

module.exports = function connectToMongo(url, callback) {
    if (db) { callback(null, db); }
    else {
        MongoClient.connect(url, function(err, conn) {
            db = conn;
            callback(err, conn);
        });
    }
}

And use it:

var connectToMongo = require('./mongodb.js');

/* ... */

connectToMongo('mongodb://127.0.0.1:27017/test', function(err, db) {
    collection = db.collection('test');
});

An even better option would be to use Promises. I use bluebird in my projects, but we'll soon have native Promise support (bluebird will probably still be better).

var mongo = require('mongodb'),
    Promise = require('bluebird');

Promise.promisifyAll(mongo);
Promise.promisifyAll(require('mongodb/lib/mongodb/db').Db.prototype);

var db;

module.exports = function connectToMongo(url) {
    if (!db) {
        db = mongo.connectAsync(url); //This returns a promise!
    }
    return db;
};

Then use it like

var connecttoMongo = requiure('./mongodb.js');
connectToMongo('mongodb://127.0.0.1:27017/test').then(function(conn) {
    //Do stuff here
});


Hotel reservation system with discounts and deposits

Not a full & detailed answer but some initial thoughts.

Some of the fields in the reservations table look decidedly non-normalised - remaining_amount, isDeposit and paid. Shouldn't these be derived from the payments table when needed for a view or a query? Otherwise, when you receive a payment you would also have to update at least two of these fields. Are you planning on using triggers for these updates?

If you want to keep the isDeposit field, then think carefully how you use it. Does it tell you that only a deposit has been paid so it gets set to 0 once the full amount is paid? Or does it tell you that the guest initially paid a deposit so it gets set to 1 when the deposit is paid and then gets left?

What happens when a reservation gets cancelled? There is no status field and presumably you cannot delete the record (and any payments records)?

You've also got user_id, guest_id and guests fields. If you want the user to enter names of any guests for the reservation you will need another structure.


Formatting database results to be consumed as multiple tables by the view

If you add a group by clause to your query on the AMVEND column, you won't have to do any looping before you pass the data to the view. You can simply detect when the vendor changes in the view's foreach loop.


Update extremities losses when selected type changes

The access to a property should be fast. If anything in a getter or setter of a property needs more time than usual to return it should better be a method.

So if UpdateExtremitiesLosses() is rather time consuming or if it should react on the changes made and there is an event which should handle changes like you mentioned, this call should better live inside this event.

public TypeSignalDTO SelectedTypeSignal
{
    get { return _selectedTypeSignal; }
    set
    {
        _selectedTypeSignal = value;
        RaisePropertyChanged(() => SelectedTypeSignal);
        UpdateExtremitiesLosses(); //This really bugs me.
    }
}

If you haven't done it already, you should override the =, != operators together with the Equals() and GetHashCode() methods and check before you call RaisePropertyChanged() if they are equal by any chance. If they are equal you shouldn't raise the event to prevent unneeded code execution.

RaisePropertyChanged(() => SelectedTypeSignal);

here you should simply use the _selectedTypeSignal instead of the property, because there is no need to call the getter of the property if you already has its value stored in a local variable.


JavaScript function for to find a defined element within a nested array

Your function is fine for me according to the structure you mentioned. But it's slow because it has to run a full search every time it's called. The main reason is the structure. So I would suggest that build an index which will help you to search quicker.

Building an index

An index is simply a map associating each id to the corresponding Part. You will only need to fill it once then use it to access Parts by id more quickly.

var index = {};
fillIndexFrom(index, structure);

function buildIndexFrom (index, list) {
    list.forEach(function(part) {
        index[part.id] = part;
        if (part.subParts)
            fillIndexFrom(index, part.subParts);
    });
}

// Then to get the part of id 4 for example you simply do
var part = index[4];

Complexity comparison

If we assume that there are N parts and that you will do M searches then:

Your initial solution will cost O(M*N) (every search costs O(N) in worst case)
The index solution will cost O(N) + M * O(logN) (O(N) to fill the index and then O(logN) for every search)


I'm not a big fan of the functional solution for following reasons:

the pointless use of the some() method, because its callback always returns false. This is this possibly an error? The call would short-circuit, if Boolean(ret = x) weren't negated. But even then some() would be the wrong choice, because it's just used for short-circuiting. I believe find() would be a better choice.
the conditional expression together with Boolean(...) expressions are a bit if a crutch. The conditional expression seems to be only used to be shorter that an full if, but that requires Boolean(), so that it still returns a boolean value needed for some().

Using find() I've come up with

const findDuplicate = lst => {
  const set = new Set();
  return lst.find(
    x => set.has(x) || !set.add(x)
  );
};

However I do admit it may be a bit cryptic.


Naming

sub_merge is weird, as it doesn't match up at all with the meaning of the english word "submerge". I get its origin ("subroutine merge"), but why not simply call it merge instead?

Algorithm

This seems like a straightforward top-down implementation of mergesort. However, there are some issues:

Stability

sub_merge doesn't preserve the relative order of elements that compare equal. However, this can easily be fixed by changing the comparison operator in if(*left_iter < *right_iter) from < to <=.
Allocations + copies

Since each sub_merge call creates its own scratch space, there are \$2n\$ allocations in total. This could be replaced by creating one scratch buffer at the highest level instead.

A benefit of doing so is the reduction in the number of necessary copies. Currently, sub_merge has to copy each element into the scratch space and then back into the original range. One of those copies could be skipped using a preallocated scratch buffer and alternating between it and the original range on different recursion levels, at the cost of one fixed copy when creating the scratch buffer.

Implementation

Why not use std::vector<std::iterator_traits<RandIter>::value_type> instead of manually managing the memory via those std::unique_ptrs?

Iterator categories

You are correct that a ForwardIterator would technically work for merge sort. However, using those would mean that you'd need 1.5 extra passes over the range for each midpoint calculation (1 pass for the std::distance call, and half a pass to find the mid iterator).

This wouldn't raise the runtime complexity into a worse category, but there are more efficient sorting strategies for those cases that don't require that many passes (especially since those passes usually aren't that cheap in data structures that only have ForwardIterators or BidirectionalIterators).

That's why RandomAccessIterators are preferred for merge sort.

  However, a lot of code would need to be changed for that to work, as ForwardIterators only need to support a small subset of the operations a RandomAccessIterator has to provide (i.e. they only have operators *, ->, ++, == and !=, so no comparisons using < or iteration using -).

So, why won't InputIterators work? Because merge sort requires multiple passes over the input/output range, and InputIterators don't guarantee that they can do so.

Improved version

With some improvements, the implementation could look something like this:

#include <vector>
#include <type_traits>

template<typename Iter>
constexpr bool is_forward_iterator_v = std::is_base_of_v<std::forward_iterator_tag, typename std::iterator_traits<Iter>::iterator_category>;

template<typename ForwardIter>
ForwardIter middle_iterator(ForwardIter first, ForwardIter last) {
    static_assert(is_forward_iterator_v<ForwardIter>, "middle_iterator requires at least a ForwardIterator to work properly");

    auto dist = std::distance(first, last);
    if(dist == 0) return first;

    return std::next(first, (dist + 1) / 2);
}

template<typename InIter1, typename InIter2, typename OutIter>
OutIter merge(InIter1 left, InIter1 left_end, InIter2 right, InIter2 right_end, OutIter out) {
    while(left != left_end && right != right_end) {
        if(*left <= *right) {
            *out++ = *left++;
        } else {
            *out++ = *right++;
        }
    }

    if(left != left_end) return std::copy(left, left_end, out);
    else return std::copy(right, right_end, out);
}

template<typename Iter, typename Iter2>
void merge_sort(Iter first, Iter last, Iter2 scratch, Iter2 scratch_end) {
    const auto mid = middle_iterator(first, last);
    if(mid != last) {
        const auto scratch_mid = middle_iterator(scratch, scratch_end);

        merge_sort(scratch, scratch_mid, first, mid);
        merge_sort(scratch_mid, scratch_end, mid, last);

        merge(scratch, scratch_mid, scratch_mid, scratch_end, first);
    }
}

template<typename Iter>
void merge_sort(Iter first, Iter last) {
    auto scratch_buffer = std::vector<typename std::iterator_traits<Iter>::value_type>(first, last);

    merge_sort(first, last, scratch_buffer.begin(), scratch_buffer.end());
}

  To Do:

  Better assert iterator requirements
  Add noexcept specifications where possible
  Maybe add support for move-only types?


Bug

I generally like your logic.  You have a bug, though:

>>> number_to_words(1_000_001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr175527.py", line 94, in number_to_words
    chunk_words.append(chunk_to_words(chunk, position))
  File "cr175527.py", line 81, in chunk_to_words
    return three_digit_to_words(hundreds, tens, ones) + multiplier
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

The problem is that for middle chunk of three digits, three_digit_to_words(0, 0, 0) evaluates to None, which isn't properly handled.

Comments and style

I find it annoying that your comments often appear after the corresponding code.  It is more conventional to either put the comment before the code, or at the end of the same line.

The most important kind of comment is the docstring, and you didn't write any.  (Your comment on to_base_1000() was almost like a docstring.)  Fortunately, your function names were clear enough to indicate their purpose.  Still, one feature of docstrings that you are missing out on is the ability to embed doctests, which would be extremely helpful for this kind of code.  For each function, a simple example, a complex example, and some corner cases would clarify exactly how it behaves.

I would change your brace style for the definitions of ONES, TEENS, etc. so that they all have the same indentation.  Also, if you write ONES = [None, 'one', …], then you should also be consistent and write TENS_PREFIXES = [None, None, 'twen', …].

Logic and organization

I am slightly annoyed by your

TENS_PREFIXES = ['_', '_', 'twen', 'thir', 'for',
                 'fif', 'six', 'seven', 'eigh', 'nine']

# Tens places words without "-ty". ex. twenty > twen, thirty > thir

There is no situation in which you would ever output "twen" rather than "twenty", so why skimp on those letters, when you could have written 'twenty' and avoided the need for that apologetic comment?

If you use "chunk" as your terminology for a block of three digits, consider using that name instead of to_base_1000().  Then, your numbers_to_words() function would be a composition of chunk_to_words() and number_to_chunks(), which I find pleasing.

In my opinion, you would be better off rolling the helper functions to_hundreds_tens_ones(), two_digit_to_words(), and three_digit_to_words() into chunk_to_words().  The code would be more readable with less jumping around.

A lot of the conditions exist to ensure that exactly one space appears between words.  For example:

if last_two_digits is None:
    return '{} hundred'.format(ONES[hundreds])

else:
    return '{} hundred {}'.format(ONES[hundreds], last_two_digits)

I would prefer to yield each word as a generator, then let ' '.join(…) take care of inserting the spaces.

Suggested solution

ONES = [
    None, 'one', 'two', 'three', 'four',
    'five', 'six', 'seven', 'eight', 'nine'
]

TEENS = [
    'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
    'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
]

TENS = [
    None, None, 'twenty', 'thirty', 'forty',
    'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
]

POWERS_OF_1000 = [
    None, 'thousand', 'million', 'billion', 'trillion',
    'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion'
]

def number_to_chunks(number):
    """
    Split an integer into little-endian base-1000 chunks.

    >>> list(number_to_chunks(1234))
    [234, 1]
    >>> list(number_to_chunks(31415000))
    [0, 415, 31]
    >>> list(number_to_chunks(0))
    []
    """
    while number:
        number, n = divmod(number, 1000)
        yield n

def chunk_to_words(chunk, scale):
    """
    Generate English words given a chunk (an integer less than 1000) and its
    scale (power of 1000).

    >>> list(chunk_to_words(31, 1))
    ['thirty', 'one', 'thousand']
    >>> list(chunk_to_words(50, 2))
    ['fifty', 'million']
    >>> list(chunk_to_words(0, 0))
    []
    >>> list(chunk_to_words(12, 3))
    ['twelve', 'billion']
    """
    assert 0 <= chunk < 1000
    hundreds, tens, ones = chunk // 100, chunk // 10 % 10, chunk % 10

    if hundreds:
        yield ONES[hundreds]
        yield 'hundred'

    if tens == 1:
        yield TEENS[ones]
    else:
        if tens:
            yield TENS[tens]
        if ones:
            yield ONES[ones]

    if chunk and scale:
        yield POWERS_OF_1000[scale]

def number_to_words(number):
    """
    Convert a nonnegative integer less than 10**30 to an English phrase.

    >>> number_to_words(103)
    'one hundred three'
    >>> number_to_words(0)
    'zero'
    >>> number_to_words(1_000_001)
    'one million one'
    >>> number_to_words(31_415_926_535)
    'thirty one billion four hundred fifteen million nine hundred twenty six thousand five hundred thirty five'
    """
    chunks = [
        ' '.join(chunk_to_words(chunk, i))
        for i, chunk in enumerate(number_to_chunks(number))
    ]
    return ' '.join(c for c in chunks[::-1] if c) or 'zero'


Simplify:

        count[x] = ++count[x];

        // Why not just;
        ++count[x];

Variable name length:

for (auto i = 0; i < test_cases; ++i) {

Have you ever tried searching for all occurrences of the variable i in the resulting loop. The number of false positives will be a pain in the arse. Name your loop variables so you can find them easily.

Hiding variables names:

    for (std::size_t i = 0; i < size; ++i) {

Though not technically illegal. This becomes a maintenance problem. It's OK for you today as you just wrote the code. But for anybody else (or you in years time) this is can be a pain. Try and give your variables unique meaningful names (self documenting code is a brilliant practice but it requires variable names to be meaningful).

The whole loop where you search for the largest repeat:

    for (std::size_t i = 0; i < size; ++i) {

This can be done inline while you were counting. I would not have a second loop to work it out after the fact.

I would simplify this condition:

} else if (i.second == numberCount) {
            if (i.first < number) {

// I find it easier to read as:

} else if (i.second == numberCount) && (i.first < number) {

This seems a bit redundant:

        } else {
            continue;
        }

Personally I think initializing integers with {} looks terrible (and is slightly confusing).

std::size_t size{};

std::size_t size = 0;  // Much easier to read.

Whats the point in initizliaing a variable just before you write over it?

    std::size_t size{};   // Why initialize it here
    std::cin >> size;     // Only to trash the initialization here.

Address Comments:

    int number{};
    int numberCount{};
    for (std::size_t i = 0; i < size; ++i) {

        std::cin >> x;
        std::size_t&  countV = count[x];

        ++countV;

        if (countV > numberCount || (countV == numberCount && x < number))
        {
            number      = x;
            numberCount = countV;
        }
    }


Extending built-in types always carries a risk that your code will interact poorly with other code.  Often, web page authors cobble together pages that use many JavaScript libraries.  Consider making it a regular function.

The function has a silent cap of "99:59".  That's an odd limit.  Either the number of hours should be unlimited, or it should be modulo 24.  Modulo 100 is totally unexpected.

The code would also fail to output the minutes correctly in some non-standard time zones, such as India, where the time zone offset relative to UTC is not an integral number of hours.

You don't need to compute remainder, as the Date object takes care of extracting the minutes portion in any case.

It took me a few seconds to figure out the significance of 3600 and 1000.  A comment would be helpful.

Here's my recommendation for a modulo 24 solution:

Number.prototype.display_hours_minutes = function () {
  var date = new Date(this * 3600 /* sec per hr */
                           * 1000 /* msec per sec */);
  return ('0' + date.getUTCHours()  ).slice(-2) + ':' +
         ('0' + date.getUTCMinutes()).slice(-2);
};


Generate String with Random Consonants and Vowels

I think if I were doing this, I'd do it...somewhat (a lot?) differently. My immediate reaction would be to do something on this general order (using C++ syntax instead of Java, but I'm pretty sure the same basic idea should work in Java about the same way):

char gen_rand(std::string const &input) {
    // A quick and dirty method, for now.
    return input[rand() % input.size()];
}

static const string lower_c = "bcdfghjklmnpqrstvwxyz";
static const string upper_c = "BCDFGHJKLMNPQRSTVWXYZ";
static const string lower_v = "aeiou";
static const string upper_v = "AEIOU";

string genRandomString(std::string const &input) {
    string output; // I suppose needs to be a StringBuilder in Java

    for (char ch : input)
        switch (ch) {
        case 'c': output.push_back(gen_rand(lower_c));    break;
        case 'C': output.push_back(gen_rand(upper_c));    break;
        case 'v': output.push_back(gen_rand(lower_v));    break;
        case 'V': output.push_back(gen_rand(upper_v));    break;
        default: throw std::runtime_error("Unexpected character in input");
        }
     return output;
 }

If I'm allowed to speak in generalities, your code seems (to me) to spend a lot of effort on issues that are almost incidental to the question at hand (e.g., 37 lines just to decide that c, C, v and V refer to lower- and upper-case consonants and vowels). At least as I see things, the fact that the case of the input corresponds to the case of the output is really mostly incidental--they could just as well be a, b, c and d instead.

Another option that seems obvious to me, would be to use a map to take an input character and retrieve the collection of characters to choose from for that input. This is probably more work than it's worth for only 4 fixed inputs, but if you might have a lot of inputs, or (especially) if you want to support those inputs being specified at run time (e.g., reading them from a configuration file) a map becomes much more attractive.

Bottom line: it's a lot simpler and more flexible to just treat the mapping from input character to action as entirely arbitrary rather than go to a lot of work to classify the inputs as upper/lower case.


Effecient Use Sieve of Eratosthenes algorithm

Ways to decrease the allocation
Since your main question was about the allocation length, I'll suggest two ways to decrease the allocation (although 1 MB really isn't that much to begin with).

Since the only even number that is prime is 2, you can only allocate half the amount by only considering odd numbers.  When you perform the sieve, you skip all even numbers and use index [j/2] for each odd number.  Just remember at the end to count 2 as one of the primes if the range includes it.

You can use 1 bit per number instead of 1 boolean per number.  You can use BitSet or your own bit array.

Combining both of the above allows you to allocate 1/16 the amount that you originally allocated (so about 64KB instead of 1MB).  I don't think it will help at all though.  If anything, your program will only get slower.
Reuse the allocation
Also, since you are running up to 100 test cases, you might as well just run the sieve once on the maximum input (10^6).  Then you can compute the 100 answers quickly without redoing all the work each time.


You might be better off just using a module with some static methods, e.g.:

module Vlogger
  class << self
    def logger
      @logger ||= ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
    end

    def with_context(tags, message)
      logger.tagged(*tags) { logger.info message }
    end
  end
end

Add attribute access as needed.

Now you can simply call Vlogger.with_context directly when you need it without having to use instance or otherwise keeping a reference to things elsewhere.

class Worker
  def perform
    Vlogger.with_context(["tag1"], "Started work")
    Provider.say_hello
  end
end

class Provider
  def self.say_hello
    Vlogger.with_context(["tag2"], "hello")
  end
end

It's an option, at least.


Assuming that I've correctly managed to extrapolate the SUT and friends from the question, I'd reduce the tests to the following. Please note that this focuses only on AutoFixture mechanics, and not on the general design of neither test nor SUT API.

AFAICT, the following tests state the same as the tests in the OP, but reduced to only the necessary statements. Still, I agree with Nikos Baxevanis that it would be possible to reduce these tests dramatically with xUnit.net instead of MSTest.

using System.Collections.Generic;
using System.Linq;
using FakeItEasy;
using FirstAutoFixtureReviewForKellySommers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoFakeItEasy;
using Ploeh.AutoFixture.Kernel;

namespace HaywireMQ.Server.Tests
{
    /// <summary>
    /// Tests for HaywireServer
    /// </summary>
    [TestClass]
    public class HaywireServerTests
    {
        [TestMethod]
        public void Should_use_defaults_without_ModuleCatalog()
        {
            // Given
            var fixture = new Fixture().Customize(new TestConventions());

            // When
            var target = fixture.CreateAnonymous<HaywireServer>();

            // Then
            Assert.IsInstanceOfType(target.MessageStore, typeof(InMemoryMessageStore));
            Assert.IsInstanceOfType(target.MessageChannel, typeof(InMemoryMessageChannel));
        }

        [TestMethod]
        public void Should_use_ModuleCatalog()
        {
            // Given
            var fixture = new Fixture().Customize(new TestConventions());

            var catalog = fixture.Freeze<ModuleCatalog>();
            fixture.AddManyTo(catalog.MessageStores, 1);
            fixture.AddManyTo(catalog.MessageChannels, 1);

            // When
            var target = fixture.CreateAnonymous<HaywireServer>();

            // Then
            Assert.AreEqual(catalog.MessageStores.Single(), target.MessageStore);
            Assert.AreEqual(catalog.MessageChannels.Single(), target.MessageChannel);
        }

        [TestMethod]
        public void Should_create_MessageQueue()
        {
            // Given
            var fixture = new Fixture().Customize(new TestConventions());

            var catalog = fixture.Freeze<ModuleCatalog>();
            fixture.AddManyTo(catalog.MessageStores, 1);

            List<string> ids = fixture.CreateMany<string>(1).ToList();
            A.CallTo(() => catalog.MessageStores.Single().GetQueues()).Returns(ids);

            var target = fixture.CreateAnonymous<HaywireServer>();

            // When
            target.Start();

            // Then
            A.CallTo(() => catalog.MessageStores.Single().GetQueues()).MustHaveHappened();
            Assert.AreEqual(1, target.MessageQueues.Count);
            Assert.AreEqual(ids.First(), target.MessageQueues[0].Id);
        }

        private class TestConventions : CompositeCustomization
        {
            public TestConventions()
                : base(
                    new AutoFakeItEasyCustomization(),
                    new GreedyHaywireServerCustomization())
            {
            }
        }

        private class GreedyHaywireServerCustomization : ICustomization
        {
            public void Customize(IFixture fixture)
            {
                fixture.Customize<HaywireServer>(c =>
                    c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));
            }
        }
    }
}


find the first "biggest" url size name. A more convenient way is using Array.prototype.find() method:
p.id can be used directly as a key for object imgUrls - instead of generating constant const id = p.id; for each p(photo)

const imgUrls = {};
const sizes = ['url_o', 'url_6k', 'url_5k', 'url_4k', 'url_3k', 'url_k', 'url_h', 'url_l'];

function onXhrLoad() {
  const json = JSON.parse(js);
  const photos = json.photos ? json.photos.photo : [json.photo];
  for (var p of photos) {
      imgUrls[p.id] = p[sizes.find((s) => p[s])];
  }
}


from time import sleep

Since you already imported time and are only calling time.sleep, this import is obsolete.

name = raw_input("Hey there, what's your name?") #Basic raw_input
intro = "Welcome to my Udacity, Mad-Libs game " + name #text plus value of "name"

The comments at the end of the lines do not tell you anything that is not already in the code, so you don't need them. Comments should usually tell you, why something is done, not what is done. What is done is already in the code.

answers_list_easy = ["object", "dynamic", "Guido", "machine"]

Having the type in the variable name is not needed, and rather bad practice. You might want to change the type later, for example to a tuple. Using a plural name (like answers_easy or easy_answers) already tells you (and possibly other developers) that the variable contains a collection, probably a sequence of answers (and a list is a kind of sequence).

game_data = {
   'easy': {
        'quiz': questions_easy,
        'answers': answers_list_easy,
        'message': "you chose easy, okay"
    },
   'medium': {
        'quiz': questions_medium,
        'answers': answers_list_medium,
        'message': "You chose medium, a fair challenge"
    },
   'hard': {
        'quiz': questions_hard,
        'answers': answers_list_hard,
        'message': "So you're a tough nugget aren't ya!!"
    }
}

This is not pretty, and probably useless. Since you need to access these values via strings as keys anyway, you might as well just access the global variables. These nested dictionaries do not really simplify the access to the variables, rather make it harder, and since at no point in the future "easy" will suddenly point towards questions_medium, you do not need to abstract the variable access.

def get_level(): #Inputs easy, medium or hard. Output, Relevant questions and answers.
    pick_level = raw_input("Type in your difficulty level. Choose from easy, medium or hard")
    while pick_level not in ["easy", "medium", "hard"]:
        pick_level = raw_input("Invalid input, please try again. Choose from easy, medium or hard")
    print game_data[pick_level]['message']
    return pick_level

Printing the level here is a side effect that you might want to prevent. The method should do only what its name implies, which is getting the level. A better name might be ask_level or input_level, since get is normally used for just returning a value that is already there. Then you can print the return value where you call this method.

def check_answer(user_answer, answers_list, answers_index):
    if user_answer == answers_list[answers_index]:
        return "right_answer"
    return "Wrong"
    pass

This name is not good, because it does not tell you what kind of answer is being checked, and what a positive result means. A better name would be is_answer_correct, or just is_correct if the parameter names are explicit enough (which I would say here they are).

Considering that the method just does a simple logical comparison with values that are all provided as parameters, you might just remove the method and replace its calls with the comparison.

As already hinted by kyrill in a comment, the method should not return strings (which are even very inconsistent here), but Trueor False boolean values. Then you can handle printing out the strings where you call the method depending on its result. And the pass does not do anything, actually it never does anything, but everything that comes after a return will not be reached.

you_lost and you_win are bad method names, and the methods alltogether are obsolete, since it is more readible to just see these 2 lines in your code than not knowing what you_lost() actually does.

blanks_index = 0
# [...]
while blanks_index < len(blanks):
    # your code

Here you should iterate using a for-loop:

for blank in blanks:
    # your code


I think your performance issue is caused by going to file multiple times. The more you read in at once the less time you'll spend asking the operating system to provide you with a few more bytes for unpack to operate on.

Similar to the above answer:

$data = fread(fh,12);
$a = unpack("L",substr($data,0,4));
$b = unpack("f",substr($data,4,4));
$c = unpack('I',substr($data,8,4));

If you want to reorganize your code you could load the entire file and then work on the data within it.

$packed = file_get_contents("somefile.dat");
$len  = strlen($packed);

$offset = 0;
while ( $offset < $len )
{
  $a[] = unpack("L",$packed,$offset,4);
  $b[] = unpack("f",$packed,$offset+4,4);
  $c[] = unpack("I",$packed,$offset+8,4);
  $offset += 12;
}

Of course, you may have to reorganize various sections of code to support working on larger chunks of the input data at a time.

Note: It appears that unpacked is being unfairly blamed for being slow due to the filesystem access embedded in the function call. You might also want to do a few tests to clarify what is taking time in the small chunk method and see how much it speeds up based on increasing the read size used (if you have the time and inclination).

EDIT: Adding the following after comments.

You are right. I did some tests and while reading more data at once does save time it isn't as significant as reducing calls to unpack.

Running unpack on binary file (12 byte reads, 3 unpacks per read)...
... fread time: 3.5979931354523
... unpack time: 12.179003238678
... total measured time: 15.77699637413
... records: 265533

Running unpack on binary file (preload file, 3 unpacks per 12 bytes)...
... fread time: 0.016999959945679
... unpack time: 12.446995973587
... total measured time: 12.463995933533
... records: 265533

Running unpack on binary file (preload file, 12 bytes per unpack)...
... fread time: 0.01200008392334
... unpack time: 4.1770012378693
... total measured time: 4.1890013217926
... records: 265533

Running unpack on binary file (preload, 24 bytes per unpack)...
... fread time: 0.010999917984009
... unpack time: 2.189001083374
... total measured time: 2.200001001358
... records: 265534 (* padding added at end of input)

Run using PHP with microtime(true) capture before and after relevant actions.

EDIT: With a bit more fooling around I can now give you an "answer" regarding how to increase performance.

Split your data internally in order to get as much work as possible out of a single call to unpack.

if ( 1 )
{
  echo "
\n";
  echo "Running unpack on binary file (preload, split into 3 streams, unpack each stream)...
\n";
  ob_flush();
  flush();

  $records = 0;
  $fread_time = 0.0;
  $unpack_time = 0.0;
  $measured = 0.0;

  $start = microtime(true);
  $data  = file_get_contents($bin_file);
  $size  = filesize($bin_file);
  $stop  = microtime(true);
  $fread_time = $stop - $start;

  $Ldata = '';
  $fdata = '';
  $Idata = '';
  $offset = 0;
  $start = microtime(true);
  while ($offset < $size)
  {
    $Ldata .= substr($data,$offset,4);
    $offset += 4;
    $fdata .= substr($data,$offset,4);
    $offset += 4;
    $Idata .= substr($data,$offset,4);
    $offset += 4;

    $records++;
  }
  $stop = microtime(true);
  $split_time = $stop - $start;

  $start = microtime(true);
  $a = unpack('L*',$Ldata);
  $b = unpack('f*',$fdata);
  $c = unpack('I*',$Idata);
  $stop = microtime(true);
  $unpack_time += ($stop - $start);
  $measured_time = $fread_time + $split_time + $unpack_time;

  echo "... fread time: $fread_time
\n";
  echo "... split_time: $split_time
\n";
  echo "... unpack time: $unpack_time
\n";
  echo "... total measured time: $measured_time
\n";
  echo "... records: $records
\n";
  ob_flush();
  flush();
}

This provides a much better time.

Running unpack on binary file (preload, split into 3 streams, unpack each stream)...
... fread time: 0.013000011444092
... split_time: 0.29400014877319
... unpack time: 0.54299998283386
... total measured time: 0.85000014305115
... records: 265533

Hopefully this is a bit more useful.


Random iteration over an array using divide and conquer

Bug?

    private final ThreadLocalRandom random = ThreadLocalRandom.current();

This doesn't look right.  What happens if your current thread copies your object and spawns a new thread?  It will copy the current random instance.

When you use it

            final int randomIndex = random.nextInt(lowerBound, upperBound);

You should instead say

            final int randomIndex = ThreadLocalRandom.current().nextInt(lowerBound, upperBound);

That way, even if your object exists in multiple threads, each one will access a separate instance of ThreadLocalRandom.

Your current implementation may return the same random result multiple times, which would give the "non-random" appearance that you're seeing.

Note that if you are using an old version of Java, there was apparently a bug that could cause this to happen even when called correctly.


class Foo:
  def __iter__(self):
     def innergen():
        yield something
     return innergen()

Is the same as:

class Foo:
  def __iter__(self):
     yield something

In other words, there is no need to define the generator, just yield the values.

Defining a class inside the method just serves to make things complicated and hard to read. Define the class outside of the method.

Having return at the end of a function doesn't do anything and makes it look like you don't know what you are doing. (I'm not saying that you don't, but whenever you include code with effect it raises a red flag. Did you think it do something?)

Unless you really need to access the data row by row I suggesting flattening the iterator.

Stylistically, I prefer to break expressions up rather then trying to split them across several lines as you've done. I think it produces less clutter.

Here is my resulting code:

class ViewPlane(object):
    def __init__(self, resolution, pixel_size, gamma):
        self.resolution = resolution
        self.pixel_size = pixel_size
        self.gamma = gamma

    def __iter__(self):
        for row in xrange(self.resolution[0]):
            for column in xrange(self.resolution[1]):
                origin_x = self.pixel_size * self.resolution[0] / 2.0 + 0.5
                origin_y = self.pixel_size * self.resolution[1] / 2.0 + 0.5
                origin = (origin_x, origin_y, 100)
                ray = Ray(origin = origin, direction = (0.0, 0.0, -1.0) )

                yield ray, (row, column)

I'm not familiar enough with RayTracers to know but I question having the iterator over ViewPlane produce Ray objects. An iterator is for producing the contents of the object. Is a really contained inside the ViewPlane? Or should the iterator produce coordinates and let the caller construct the Ray objects?

EDIT

Here is a version that doesn't flatten the iterator:

class ViewPlane(object):
    def __init__(self, resolution, pixel_size, gamma):
        self.resolution = resolution
        self.pixel_size = pixel_size
        self.gamma = gamma

    def row_iter(self, row):
        for column in xrange(self.resolution[1]):
            origin_x = self.pixel_size * self.resolution[0] / 2.0 + 0.5
            origin_y = self.pixel_size * self.resolution[1] / 2.0 + 0.5
            origin = (origin_x, origin_y, 100)
            ray = Ray(origin = origin, direction = (0.0, 0.0, -1.0) )

            yield ray, (row, column)

    def __iter__(self):
        for row in xrange(self.resolution[0]):
            yield self.row_iter(row)


As said above adding an extra Array does not change the space complexity to n^2.

Another thing is you do not need that extra Array also. All you need is 3 or 4 variables.
You can store the previous beginIndex and length of and the currentBeginIndex and length and if it crosses the previous maxLength then store the max as the crrentMax else continue with the iteration.

Let me know if you want some code sample.


In a program comment it is said that the program

# Accepts any date/time format accepted by 'date'

That information should be printed with the usage help, plus one or two examples. Something like

$ ./sleep_until.sh --help
Usage: ./sleep_until.sh TIME

    TIME can be any date/time as accepted by date(1).

Examples:

    ...

That'll save me from looking into the source code (and possibly from
looking up man date) in order to figure out the correct parameters.

Due to the truncation in

test ${end%.*} -gt ${now%.*} || die "$1 is in the past!"

there is a (albeit small) chance that a valid date is not recognized.
This can be avoided by computing the delay first, and then checking
it to be positive (e.g. as in How to compare to floating point number in a shell script):

end=$(date -d "$1" +%s.%N)
now=$(date +%s.%N)
delay=$(echo $end - $now | bc)
test 1 -eq $(echo "$delay > 0" | bc) || die "$1 is in the past!"
exec sleep $delay

Note: I'm using bc rather than dc here just because I needed it for the check $delay > 0 and found a bc-based solution first (and then I did not want to use two different tools). Also I am a little bit more familiar with bc. Some criteria are given in the Unix & Linux question How is bc different from dc?, such as “bc is standardised by POSIX and so is probably the more portable of the two.”


Node.js RethinkDB connection wrapper with built in retries

You can use recursive promises. If promises don't exist in your platform, you could use a third party library or a polyfill to do the same thing.

function tryConnecting(config, remainingHosts){

    // Make a copy of hosts that we can shift off stuff. Don't modify config.
    remainingHosts = config.hosts.slice(0);

    // Promises resolve or reject only when we call resolve and recject.
    // When we see that we can still retry, we don't call either.
    return new Promise(function(resolve, reject)){

        // Update host
        config.host = remainingHosts.shift();

        // Try connecting
        r.connect(config, function(error, connection) {

            // If it fails and we still have hosts remaining, call the function
            // again. This promise's resolve and reject will be called when that
            // call's promise resolves or rejects
            if(error && remainingHosts.length) tryConnecting(config, remainingHosts).then(resolve, reject);

            // If it's an error, and we have no more remaining hosts, we reject
            // the promise. If this call was not the first (ie. previous call
            // failed with remaining hosts), then that promise will be rejected
            // with the same values.
            else if(error && !remainingHosts.length) reject(error, null);

            // If no error, then we resolve with the connection. If this was
            // not the first call (ie. previous call failed with remaining
            // hosts) then, that promise will resolve with the same values.
            else resolve(null, connection);
        });
    });
}

exports.connect = function(config, callback) {
    tryConnecting(config, config.hosts).then(callback, callback);
};


Watch for mixed idioms

        for (int i = 1; i < (int)(Math.sqrt(number)); i++) {

This is wasteful.  All you need to do is

        for (int i = 1; primes[i] <= (int)(Math.sqrt(number)); i++) {

This only works in that it always checks too many values.  i and number are not actually related here.  The comparative relation is between primes[i] and number.  This relies on i < primes[i] for all i.

And as noted in a comment, this puts a lot of reliance on the compiler to figure out that the square root will be constant.  Consider

        int largestSmallerFactor = (int)(Math.sqrt(number));
        for (int i = 1; primes[i] <= largestSmallerFactor; i++) {

Now it's clear that we only take the square root once.

Helper method

        if (numberIsPrime){

Consider

        if (isOddPrime(number, primes)) {

Then you just need a helper method and can get rid of numberIsPrime altogether.

private boolean isOddPrime(int candidate, int[] primes) {
    int largestSmallerFactor = (int)(Math.sqrt(candidate));
    for (int i = 1; primes[i] <= largestSmallerFactor; i++) {
        if (candidate % primes[i] == 0) {
            return false;
        }
    }

    return true;
}

Optimization

Perhaps you are concerned that a method call has too much overhead.  If so, consider

    nextCandidate:
    while (count < n) {
        int largestSmallerFactor = (int)(Math.sqrt(number));
        for (int i = 1; primes[i] <= largestSmallerFactor; i++) {
            if (number % primes[i] == 0) {
                continue nextCandidate;
            }
        }

        primes[count] = number;
        count++;
    }

No method overhead.

People will point out that the method is a more readable and robust solution, which it is.  But if you're trying to wring out every possible efficiency, this might be better.  You'd have to compile and compare both versions to see.  Remember that the compiler might have an even better optimization for the method version.

Sieve of Eratosthenes

A comment suggested using the Sieve of Eratosthenes.  While it is true that that's an efficient way to find primes, it is not well suited to finding the nth prime.  The problem is that it checks a certain number of numbers, so there is a tendency to either overshoot or undershoot.

You can use a segmented sieve to process the sieve partially.  So if you undershoot, you can continue.  This also allows you to make smaller jumps, so you are less likely to overshoot.

It was asserted that a sieve avoids repeated division.  That's true but it replaces it with redundant multiplication.  For example, 210 is marked as not prime by the sieving operations for 2, 3, 5, and 7.  Or more generally, a number divisible by 6 will be sieved by both 2 and 3.  By contrast, trial division can stop as soon as it finds the first factor.

It may be that the sieve is faster on average.  After all, a square root is an expensive operation.  But it can do more work for a particular number than trial division does.

Here is an example of a windowed sieve which you could try to modify to this purpose.  Don't forget to time it both ways.


Implementation:

It’s generally discouraged to open namespaces (using namespace …;). Instead, import single symbols (using std::vector;) or qualify symbols explicitly.
Three-ways min can be written entirely in terms of std::min:

template <typename T>
T min(T const& a, T const& b, T const& c) {
   return std::min(std::min(a, b), c);
}

“Bug”: the edit distance generally defines the cost for a substitution as 1 (since Levenshtein defined three equivalent edit operations), not 2 which you used in your code;
Algorithmic: Your code needs O(n * m) space. There’s a not too hard to implement variant which requires just O(min{n, m}) due to the fact that for the computation we only need to save the previous column (or row). In fact, with a bit of trickery you can make do with a single vector and two additional variables to save all the active values.

But apart from that it’s a very clean and efficient implementation.


Decimal to Binary Conversion and vice-versa in Python

Rather than repeating the same logic you could make a couple of functions binary_to_decimal and decimal_to_binary.

def binary_to_decimal(num):
    return int("{0:d}".format(num), 2)

def decimal_to_binary(num):
    return int("{0:b}".format(num))

Whilst it doesn't have too big an impact on the readability of your code it abstracts the code enough for anyone passing by to understand what you mean when you're doing the string formatting. You could also change binary_to_decimal to use str rather than string formatting, as I don't think we're going to change to the binary form any time soon. I also thing your string formatting for changing to binary is better than using bin as you'd have to cut the first 0b off the output of bin, which would make the code more cryptic.


public class AESEncryption {

Make the class final unless you design for it to have child classes.

    private Cipher cipher = null;
    private ByteArrayOutputStream outputStream;

Cipher is a stateful object. It should not be used as a field. Imagine sharing an object instance between multiple threads or methods. Try and never assign null (if only because Java will do it itself).

outputStream is only necessary locally. Again, a stateful object, while there is otherwise no message specific state.

            e.printStackTrace();

Never ever do this. Use a // TODO tagging comment and then throw IllegalStateException(e); even configure your IDE to to this by default. Don't keep running with illegal state (and behold, if you do this, you can even make cipher final - which would have been useful if you'd needed it anyway).

        return new String(bytes);

Don't even convert random bytes to a string. Furthermore, if you decode bytes to a string, explicitly identify the encoding. You may lose data if you find invalid bytes (.e.g. anything above 0x7F for UTF-8).

        PBEKeySpec spec = new PBEKeySpec("12345asdqwe".toCharArray(), salt.getBytes("UTF-8"), 65536, 128);

Don't use static password values stuck in source code. Why do I even have to explain this? Note by the way that the reason that the password is a character array is to make it easier to destroy the password when it is not required any more. Beware that Java only uses the lowest 8 bits of each character - better check that you don't accept passwords that contain other values!

The 65537 value is a magic value, and should be constant. But generally you want to use a much higher value nowadays - unless your password is really complex. Making such a value configurable is very important. This however also means that you will have to indicate the value for the ciphertext somehow.

All in all, you are using stringified input / output and you simply throw Exception - which is simply telling your user to be screwed upon any error. Please look at my answer on how to use security exceptions on StackOverflow.

You don't specify any protocol that you are using. The user will have to guess the encodings of what you return. There is no warning of the mode, the inclusion of the IV or that the salt needs to be saved, the iteration count, the character encoding or the base-64 encoding.

You use CBC, which is not an authenticated mode such as GCM.

The salt is random, which means that the key is random. Since you don't include the salt, nobody will ever be able to decrypt. If the salt is saved otherwise, then it will probably get mangled because you forgot to base 64 encode it.

The key derivation is simply copied for the encrypt and decrypt methods. Why wasn't this put into a separate method?

And "mum's the word" apparently - this code seems to encrypt any strings, not just words?

Let's finish with a positive note: you do always perform UTF-8 encoding / decoding on the "word". Base 64 is not wrong either if a text interface is assumed. That's nice!


Break music player into usable components in SwiftUI

I need to ask a question when I break up my player into usable
components. How should I take this approach

The idea is to break a long and not so readable code into smaller parts. Also, each individual part needs to access variables etc.
For this you can use a private extension (unless it's in another file, then skip private):
struct ContentView: View {
    @State private var sliderValue = 1.0

    var body: some View {
        VStack {
            Image("albumCover")
            infoView
            sliderView
            actionsView
            bottomView
        }
    }
}

private extension ContentView {
    var infoView: some View {
        HStack {
            VStack {
                Text("Album name")
                Text("Artist name")
            }
            Spacer()
            Button(action: {}) {
                Image(systemName: "heart")
            }
        }
        .padding()
    }
}

private extension ContentView {
    var sliderView: some View {
        HStack {
            Text("0")
            Slider(value: $sliderValue)
            Text("-5:00")
        }
        .padding()
    }
}

private extension ContentView {
    var actionsView: some View {
        HStack {
            Button(action: {}) {
                Image(systemName: "shuffle")
            }
            Spacer()
            Button(action: {}) {
                Image(systemName: "backward.end")
            }
            Spacer()
            Button(action: {}) {
                Image(systemName: "play")
            }
            Spacer()
            Button(action: {}) {
                Image(systemName: "forward.end")
            }
            Spacer()
            Button(action: {}) {
                Image(systemName: "repeat")
            }
        }
        .padding()
    }
}

private extension ContentView {
    var bottomView: some View {
        HStack {
            Button(action: {}) {
                Image(systemName: "hifispeaker")
            }
            Spacer()
            Button(action: {}) {
                Image(systemName: "music.note.list")
            }
        }
        .padding()
    }
}

Note that you can declare sliderValue directly in ContentView:
struct ContentView: View {
    @State private var sliderValue = 1.0

and access it in the extension:
private extension ContentView {
    var sliderView: some View {
        Slider(value: $sliderValue)

But the code above still doesn't address the problem of repeating blocks of code in your ContentView. See how often this block is reused:
Button(action: {}) {
    Image(systemName: "hifispeaker")
}

What if you want to apply a modifier to every Image?
A solution may be to extract the repeating code to one function:
private extension ContentView {
    func customButton(imageName: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Image(systemName: imageName)
        }
    }
}

and use it like this:
private extension ContentView {
    var bottomView: some View {
        HStack {
            customButton(imageName: "hifispeaker", action: {})
            customButton(imageName: "music.note.list", action: {})
        }
        .padding()
    }
}


Return list with numbers of color occurrences in another list

I think you're tripping yourself up by position-encoding the colors. Position-encoding is usually a code smell in Haskell, what you probably want is an association. Consider the difference between [Int] and [(Peg, Int)], and just how much more expressive of intent the latter is.

(You could be even more specific at the type level with something like type Count = Int countColors :: Code -> Map Peg Count but that's probably excessive for a small game.)

So then how do you write a function with type Code -> [(Peg, Int)]? As you noticed the [Peg] may be in any order, so to compensate you can filter for each individual color, or you could leverage the Ord Peg instance and sort the original list to group identical colors together. After the colors are in order, what's left is to simply run-length encode the list.

countColors :: Code -> [(Peg, Int)]
countColors = map (\shade -> (head shade, length shade)) . group . sort


Actually reviewing your question again it looks like what you are trying to do is to group all offerings by the same year and month and then iterate over each offering. Hence a GroupBy query is probably what you want:

foreach (
    var offerings in
        courses.SelectMany(x => x.Offerings)
            .Where(x => !string.IsNullOrEmpty(x.StartDate))
            .Select(x =>
                    new {
                        Offer = x,
                        StartDateMonth = new DateTime(DateTime.Parse(x.StartDate).Year, DateTime.Parse(x.StartDate).Month, 1)
                    })
            .GroupBy(x => x.StartDateMonth)
            .OrderBy(g => g.Key))
{

    //some display code using the writer
    // offerings will be a group of offerings which have the StartDate in the same year/month

    foreach (var offering in offerings.Select(o => o.Offer))
    {
        // iterate over all offers in the group
    }
}

Not sure if there is a nice effective way to avoid the double parsing.


Summary page with react-redux: container or presentational component

In my opinion (which also aligns with the official Redux FAQ ("Should I only connect my top component, or can I connect multiple components in my tree?"):

If MerchantContainer and ReviewContainer use mostly the same state or actions, you could reduce duplication by having a common container for both of those.
If MerchantContainer and ReviewContainer don't have any state in common (which I think is the case here), there's no real value in having Summary as a common container. Quite the oppositive: If you'd make Summary the common container, Summary would have access to state and actions that Summary doesn't care about at all.

To summarize: It's perfectly fine to have multiple connected components that might be children of a "dumb" component. If you have a similar setup in a couple of the children, you might consider extracting a common container.


Heres how I did it properly with topological sorting. Each key of the object is a vertex on a graph, the value dependencies are the adjacent vertices. https://www.youtube.com/watch?v=ddTC4Zovtbc

var deps = {
    p1: ['p2', 'p3'],
    p2: [],
    p3: ['p3']
};

function depSort(deps) {
    var visited = [];
    var sorted = [];

    for (var dep in deps) {
        if (!visited[dep]) {
            depSortUtil(dep, visited, sorted);
        }
    }

    return sorted;
}

function depSortUtil(dep, visited, sorted) {
    visited[dep] = true;

    for (var i = 0; i < deps[dep].length; i++) {
        if (!visited[deps[dep][i]]) {
            depSortUtil(deps[dep][i], visited, sorted);
        }
    }
    sorted.push(dep);
}

console.log(depSort(deps));